Create common and api types packages for the savedObjects domain (#136722)

* Creating empty @kbn/core-saved-objects-common package

* start moving types around

* start fixing imports

* fix entrypoint exports

* fix external import

* create explicit ISavedObjectsRepository interface

* fix another external usage

* rewrite browser exports

* create explicit SavedObjectsClientContract interface

* move client/repository types to @kbn/core-saved-objects-api-server

* start fixing imports

* one more

* fix global re-exports

* fix some browser-side imports

* fix more violations

* prepare the browser-side client

* fix one more usage

* fix external usage

* fix more external usages

* one more

* Create @kbn/core-saved-objects-api-browser package

* fix more usages of error helper

* fix more internal imports

* use interface for SSO

* adapt more imports

* damn those types were a mess

* fix more usages of SSO

* Revert "fix more usages of SSO"

This reverts commit 07a12e5353.

* Revert "use interface for SSO"

This reverts commit 6240fc86c5.

* export the interface with the old name instead.

* adapt tests concrete usages of SSO

* export reference type, more fixes

* this gonna be long

* one more

* other resolve type change

* more usages

* Am I getting close?

* yet more fixes

* back to client impl

* fix bulkGetting undefined

* fix SS mock

* some cleanup

* self-review

* fix new usages
This commit is contained in:
Pierre Gayvallet 2022-07-26 13:01:33 +02:00 committed by GitHub
parent b3d7d1288d
commit 0645a3ba38
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
198 changed files with 3628 additions and 2287 deletions

View file

@ -224,6 +224,9 @@
"@kbn/core-preboot-server": "link:bazel-bin/packages/core/preboot/core-preboot-server",
"@kbn/core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal",
"@kbn/core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks",
"@kbn/core-saved-objects-api-browser": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser",
"@kbn/core-saved-objects-api-server": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server",
"@kbn/core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common",
"@kbn/core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser",
"@kbn/core-theme-browser": "link:bazel-bin/packages/core/theme/core-theme-browser",
"@kbn/core-theme-browser-internal": "link:bazel-bin/packages/core/theme/core-theme-browser-internal",
@ -830,6 +833,9 @@
"@types/kbn__core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal/npm_module_types",
"@types/kbn__core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks/npm_module_types",
"@types/kbn__core-public-internal-base": "link:bazel-bin/packages/core/public/internal-base/npm_module_types",
"@types/kbn__core-saved-objects-api-browser": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser/npm_module_types",
"@types/kbn__core-saved-objects-api-server": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server/npm_module_types",
"@types/kbn__core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common/npm_module_types",
"@types/kbn__core-server-internal-base": "link:bazel-bin/packages/core/server/internal-base/npm_module_types",
"@types/kbn__core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser/npm_module_types",
"@types/kbn__core-theme-browser": "link:bazel-bin/packages/core/theme/core-theme-browser/npm_module_types",

View file

@ -92,6 +92,9 @@ filegroup(
"//packages/core/preboot/core-preboot-server-internal:build",
"//packages/core/preboot/core-preboot-server-mocks:build",
"//packages/core/preboot/core-preboot-server:build",
"//packages/core/saved-objects/core-saved-objects-api-browser:build",
"//packages/core/saved-objects/core-saved-objects-api-server:build",
"//packages/core/saved-objects/core-saved-objects-common:build",
"//packages/core/test-helpers/core-test-helpers-http-setup-browser:build",
"//packages/core/theme/core-theme-browser-internal:build",
"//packages/core/theme/core-theme-browser-mocks:build",
@ -322,6 +325,9 @@ filegroup(
"//packages/core/preboot/core-preboot-server-internal:build_types",
"//packages/core/preboot/core-preboot-server-mocks:build_types",
"//packages/core/preboot/core-preboot-server:build_types",
"//packages/core/saved-objects/core-saved-objects-api-browser:build_types",
"//packages/core/saved-objects/core-saved-objects-api-server:build_types",
"//packages/core/saved-objects/core-saved-objects-common:build_types",
"//packages/core/test-helpers/core-test-helpers-http-setup-browser:build_types",
"//packages/core/theme/core-theme-browser-internal:build_types",
"//packages/core/theme/core-theme-browser-mocks:build_types",

View file

@ -0,0 +1,108 @@
load("@npm//@bazel/typescript:index.bzl", "ts_config")
load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project")
PKG_DIRNAME = "core-saved-objects-api-browser"
PKG_REQUIRE_NAME = "@kbn/core-saved-objects-api-browser"
SOURCE_FILES = glob(
[
"src/**/*.ts",
"src/**/*.tsx",
],
exclude = [
"**/*.test.*",
"**/*.stories.*",
],
)
SRCS = SOURCE_FILES
filegroup(
name = "srcs",
srcs = SRCS,
)
NPM_MODULE_EXTRA_FILES = [
"package.json",
]
RUNTIME_DEPS = [
"@npm//react"
]
TYPES_DEPS = [
"@npm//@types/node",
"@npm//@types/jest",
"//packages/core/saved-objects/core-saved-objects-common:npm_module_types",
"//packages/core/saved-objects/core-saved-objects-api-server:npm_module_types",
]
jsts_transpiler(
name = "target_node",
srcs = SRCS,
build_pkg_name = package_name(),
)
jsts_transpiler(
name = "target_web",
srcs = SRCS,
build_pkg_name = package_name(),
web = True,
)
ts_config(
name = "tsconfig",
src = "tsconfig.json",
deps = [
"//:tsconfig.base.json",
"//:tsconfig.bazel.json",
],
)
ts_project(
name = "tsc_types",
args = ['--pretty'],
srcs = SRCS,
deps = TYPES_DEPS,
declaration = True,
declaration_map = True,
emit_declaration_only = True,
out_dir = "target_types",
root_dir = "src",
tsconfig = ":tsconfig",
)
js_library(
name = PKG_DIRNAME,
srcs = NPM_MODULE_EXTRA_FILES,
deps = RUNTIME_DEPS + [":target_node", ":target_web"],
package_name = PKG_REQUIRE_NAME,
visibility = ["//visibility:public"],
)
pkg_npm(
name = "npm_module",
deps = [":" + PKG_DIRNAME],
)
filegroup(
name = "build",
srcs = [":npm_module"],
visibility = ["//visibility:public"],
)
pkg_npm_types(
name = "npm_module_types",
srcs = SRCS,
deps = [":tsc_types"],
package_name = PKG_REQUIRE_NAME,
tsconfig = ":tsconfig",
visibility = ["//visibility:public"],
)
filegroup(
name = "build_types",
srcs = [":npm_module_types"],
visibility = ["//visibility:public"],
)

View file

@ -0,0 +1,3 @@
# @kbn/core-saved-objects-api-browser
This package contains the public types for core's browser-side savedObjects client APIs.

View file

@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
module.exports = {
preset: '@kbn/test',
rootDir: '../../../..',
roots: ['<rootDir>/packages/core/saved-objects/core-saved-objects-api-browser'],
};

View file

@ -0,0 +1,8 @@
{
"name": "@kbn/core-saved-objects-api-browser",
"private": true,
"version": "1.0.0",
"main": "./target_node/index.js",
"browser": "./target_web/index.js",
"license": "SSPL-1.0 OR Elastic License 2.0"
}

View file

@ -0,0 +1,14 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { SimpleSavedObject } from '../simple_saved_object';
/** @public */
export interface SavedObjectsBatchResponse<T = unknown> {
savedObjects: Array<SimpleSavedObject<T>>;
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsCreateOptions } from './create';
/**
* @param type - Create a SavedObject of the given type
* @param attributes - Create a SavedObject with the given attributes
*
* @public
*/
export interface SavedObjectsBulkCreateObject<T = unknown> extends SavedObjectsCreateOptions {
type: string;
attributes: T;
}
/** @public */
export interface SavedObjectsBulkCreateOptions {
/** If a document with the given `id` already exists, overwrite it's contents (default=false). */
overwrite?: boolean;
}

View file

@ -0,0 +1,14 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { ResolvedSimpleSavedObject } from './resolve';
/** @public */
export interface SavedObjectsBulkResolveResponse<T = unknown> {
resolved_objects: Array<ResolvedSimpleSavedObject<T>>;
}

View file

@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectReference } from '@kbn/core-saved-objects-common';
/** @public */
export interface SavedObjectsBulkUpdateObject<T = unknown> {
type: string;
id: string;
attributes: T;
version?: string;
references?: SavedObjectReference[];
}
/** @public */
export interface SavedObjectsBulkUpdateOptions {
namespace?: string;
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type {
SavedObjectReference,
SavedObjectsMigrationVersion,
} from '@kbn/core-saved-objects-common';
/** @public */
export interface SavedObjectsCreateOptions {
/**
* (Not recommended) Specify an id instead of having the saved objects service generate one for you.
*/
id?: string;
/** If a document with the given `id` already exists, overwrite it's contents (default=false). */
overwrite?: boolean;
/** {@inheritDoc SavedObjectsMigrationVersion} */
migrationVersion?: SavedObjectsMigrationVersion;
/** A semver value that is used when upgrading objects between Kibana versions. */
coreMigrationVersion?: string;
references?: SavedObjectReference[];
}

View file

@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/** @public */
export interface SavedObjectsDeleteOptions {
/** Force deletion of an object that exists in multiple namespaces */
force?: boolean;
}

View file

@ -0,0 +1,39 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsFindOptions as SavedObjectFindOptionsServer } from '@kbn/core-saved-objects-api-server';
import type { SavedObjectsBatchResponse } from './base';
/**
* @public
*/
export type SavedObjectsFindOptions = Omit<
SavedObjectFindOptionsServer,
'pit' | 'rootSearchFields' | 'searchAfter' | 'sortOrder' | 'typeToNamespacesMap'
>;
/**
* Return type of the Saved Objects `find()` method.
*
* @public
*/
export interface SavedObjectsFindResponse<T = unknown, A = unknown>
extends SavedObjectsBatchResponse<T> {
aggregations?: A;
total: number;
perPage: number;
page: number;
}
/**
* @public
*/
export interface SavedObjectsFindOptionsReference {
type: string;
id: string;
}

View file

@ -0,0 +1,21 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export type { SavedObjectsBatchResponse } from './base';
export type { SavedObjectsBulkCreateObject, SavedObjectsBulkCreateOptions } from './bulk_create';
export type { SavedObjectsBulkResolveResponse } from './bulk_resolve';
export type { SavedObjectsBulkUpdateObject, SavedObjectsBulkUpdateOptions } from './bulk_update';
export type { SavedObjectsCreateOptions } from './create';
export type { SavedObjectsDeleteOptions } from './delete';
export type {
SavedObjectsFindResponse,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
} from './find';
export type { ResolvedSimpleSavedObject } from './resolve';
export type { SavedObjectsUpdateOptions } from './update';

View file

@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
import type { SavedObjectsResolveResponse } from '../../server';
import { SimpleSavedObject } from './simple_saved_object';
import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server';
import { SimpleSavedObject } from '../simple_saved_object';
/**
* This interface is a very simple wrapper for SavedObjects resolved from the server

View file

@ -0,0 +1,16 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectReference } from '@kbn/core-saved-objects-common';
/** @public */
export interface SavedObjectsUpdateOptions<Attributes = unknown> {
version?: string;
upsert?: Attributes;
references?: SavedObjectReference[];
}

View file

@ -0,0 +1,25 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export type { SavedObjectsClientContract } from './saved_objects_client';
export type { SimpleSavedObject } from './simple_saved_object';
export type {
SavedObjectsCreateOptions,
SavedObjectsDeleteOptions,
SavedObjectsBatchResponse,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsUpdateOptions,
ResolvedSimpleSavedObject,
SavedObjectsBulkUpdateObject,
SavedObjectsFindResponse,
SavedObjectsBulkCreateOptions,
SavedObjectsBulkUpdateOptions,
SavedObjectsBulkResolveResponse,
SavedObjectsBulkCreateObject,
} from './apis';

View file

@ -0,0 +1,157 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectTypeIdTuple } from '@kbn/core-saved-objects-common';
import type {
ResolvedSimpleSavedObject,
SavedObjectsBatchResponse,
SavedObjectsBulkCreateObject,
SavedObjectsBulkCreateOptions,
SavedObjectsBulkResolveResponse,
SavedObjectsBulkUpdateObject,
SavedObjectsCreateOptions,
SavedObjectsFindResponse,
SavedObjectsFindOptions,
SavedObjectsUpdateOptions,
SavedObjectsDeleteOptions,
} from './apis';
import type { SimpleSavedObject } from './simple_saved_object';
/**
* The client-side SavedObjectsClient is a thin convenience library around the SavedObjects
* HTTP API for interacting with Saved Objects.
*
* @public
*/
export interface SavedObjectsClientContract {
/**
* Persists an object
*/
create<T = unknown>(
type: string,
attributes: T,
options?: SavedObjectsCreateOptions
): Promise<SimpleSavedObject<T>>;
/**
* Creates multiple documents at once
* @returns The result of the create operation containing created saved objects.
*/
bulkCreate(
objects: SavedObjectsBulkCreateObject[],
options?: SavedObjectsBulkCreateOptions
): Promise<SavedObjectsBatchResponse<unknown>>;
/**
* Deletes an object
*/
delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>;
/**
* Search for objects
*
* @param {object} [options={}]
* @property {string} options.type
* @property {string} options.search
* @property {string} options.searchFields - see Elasticsearch Simple Query String
* Query field argument for more information
* @property {integer} [options.page=1]
* @property {integer} [options.perPage=20]
* @property {array} options.fields
* @property {object} [options.hasReference] - { type, id }
* @returns A find result with objects matching the specified search.
*/
find<T = unknown, A = unknown>(
options: SavedObjectsFindOptions
): Promise<SavedObjectsFindResponse<T>>;
/**
* Fetches a single object
*
* @param {string} type
* @param {string} id
* @returns The saved object for the given type and id.
*/
get<T = unknown>(type: string, id: string): Promise<SimpleSavedObject<T>>;
/**
* Returns an array of objects by id
*
* @param {array} objects - an array ids, or an array of objects containing id and optionally type
* @returns The saved objects with the given type and ids requested
* @example
*
* bulkGet([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*/
bulkGet(objects: SavedObjectTypeIdTuple[]): Promise<SavedObjectsBatchResponse<unknown>>;
/**
* Resolves a single object
*
* @param {string} type
* @param {string} id
* @returns The resolve result for the saved object for the given type and id.
*
* @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the
* outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior for the `resolve`
* API is unique to the public client, which batches individual calls with `bulkResolve` under the hood. We don't throw an error in that
* case for legacy compatibility reasons.
*/
resolve<T = unknown>(type: string, id: string): Promise<ResolvedSimpleSavedObject<T>>;
/**
* Resolves an array of objects by id, using any legacy URL aliases if they exist
*
* @param objects - an array of objects containing id, type
* @returns The bulk resolve result for the saved objects for the given types and ids.
* @example
*
* bulkResolve([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*
* @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the
* outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. The `resolve` method in the
* public client uses `bulkResolve` under the hood, so it behaves the same way.
*/
bulkResolve<T = unknown>(
objects: SavedObjectTypeIdTuple[]
): Promise<SavedObjectsBulkResolveResponse<T>>;
/**
* Updates an object
*
* @param {string} type
* @param {string} id
* @param {object} attributes
* @param {object} options
* @prop {integer} options.version - ensures version matches that of persisted object
* @prop {object} options.migrationVersion - The optional migrationVersion of this document
* @returns
*/
update<T = unknown>(
type: string,
id: string,
attributes: T,
options?: SavedObjectsUpdateOptions
): Promise<SimpleSavedObject<T>>;
/**
* Update multiple documents at once
*
* @param {array} objects - [{ type, id, attributes, options: { version, references } }]
* @returns The result of the update operation containing both failed and updated saved objects.
*/
bulkUpdate<T = unknown>(
objects: SavedObjectsBulkUpdateObject[]
): Promise<SavedObjectsBatchResponse<T>>;
}

View file

@ -0,0 +1,45 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObject as SavedObjectType } from '@kbn/core-saved-objects-common';
/**
* Very simple wrapper for SavedObjects loaded from the server
* with the {@link SavedObjectsClientContract}.
*
* It provides basic functionality for creating/saving/deleting saved objects,
* but doesn't include any type-specific implementations.
*
* @public
*/
export interface SimpleSavedObject<T = unknown> {
attributes: T;
_version?: SavedObjectType<T>['version'];
id: SavedObjectType<T>['id'];
type: SavedObjectType<T>['type'];
migrationVersion: SavedObjectType<T>['migrationVersion'];
coreMigrationVersion: SavedObjectType<T>['coreMigrationVersion'];
error: SavedObjectType<T>['error'];
references: SavedObjectType<T>['references'];
updatedAt: SavedObjectType<T>['updated_at'];
/**
* Space(s) that this saved object exists in. This attribute is not used for "global" saved object types which are registered with
* `namespaceType: 'agnostic'`.
*/
namespaces: SavedObjectType<T>['namespaces'];
get(key: string): any;
set(key: string, value: any): T;
has(key: string): boolean;
save(): Promise<SimpleSavedObject<T>>;
delete(): Promise<{}>;
}

View file

@ -0,0 +1,18 @@
{
"extends": "../../../../tsconfig.bazel.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"outDir": "target_types",
"rootDir": "src",
"stripInternal": false,
"types": [
"jest",
"node"
]
},
"include": [
"src/**/*"
]
}

View file

@ -0,0 +1,99 @@
load("@npm//@bazel/typescript:index.bzl", "ts_config")
load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project")
PKG_DIRNAME = "core-saved-objects-api-server"
PKG_REQUIRE_NAME = "@kbn/core-saved-objects-api-server"
SOURCE_FILES = glob(
[
"src/**/*.ts",
],
exclude = [
"**/*.test.*",
"**/*.stories.*",
],
)
SRCS = SOURCE_FILES
filegroup(
name = "srcs",
srcs = SRCS,
)
NPM_MODULE_EXTRA_FILES = [
"package.json",
]
RUNTIME_DEPS = [
]
TYPES_DEPS = [
"@npm//@types/node",
"@npm//@types/jest",
"@npm//@elastic/elasticsearch",
"//packages/core/saved-objects/core-saved-objects-common:npm_module_types"
]
jsts_transpiler(
name = "target_node",
srcs = SRCS,
build_pkg_name = package_name(),
)
ts_config(
name = "tsconfig",
src = "tsconfig.json",
deps = [
"//:tsconfig.base.json",
"//:tsconfig.bazel.json",
],
)
ts_project(
name = "tsc_types",
args = ['--pretty'],
srcs = SRCS,
deps = TYPES_DEPS,
declaration = True,
declaration_map = True,
emit_declaration_only = True,
out_dir = "target_types",
root_dir = "src",
tsconfig = ":tsconfig",
)
js_library(
name = PKG_DIRNAME,
srcs = NPM_MODULE_EXTRA_FILES,
deps = RUNTIME_DEPS + [":target_node"],
package_name = PKG_REQUIRE_NAME,
visibility = ["//visibility:public"],
)
pkg_npm(
name = "npm_module",
deps = [":" + PKG_DIRNAME],
)
filegroup(
name = "build",
srcs = [":npm_module"],
visibility = ["//visibility:public"],
)
pkg_npm_types(
name = "npm_module_types",
srcs = SRCS,
deps = [":tsc_types"],
package_name = PKG_REQUIRE_NAME,
tsconfig = ":tsconfig",
visibility = ["//visibility:public"],
)
filegroup(
name = "build_types",
srcs = [":npm_module_types"],
visibility = ["//visibility:public"],
)

View file

@ -0,0 +1,5 @@
# @kbn/core-saved-objects-api-server
This package contains the public types for core's server-side savedObjects client (and repository) APIs.

View file

@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
module.exports = {
preset: '@kbn/test/jest_node',
rootDir: '../../../..',
roots: ['<rootDir>/packages/core/saved-objects/core-saved-objects-api-server'],
};

View file

@ -0,0 +1,7 @@
{
"name": "@kbn/core-saved-objects-api-server",
"private": true,
"version": "1.0.0",
"main": "./target_node/index.js",
"license": "SSPL-1.0 OR Elastic License 2.0"
}

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObject } from '@kbn/core-saved-objects-common';
/**
* Base options used by most of the savedObject APIs.
* @public
*/
export interface SavedObjectsBaseOptions {
/** Specify the namespace for this operation */
namespace?: string;
}
/**
* Elasticsearch Refresh setting for mutating operation
* @public
*/
export type MutatingOperationRefreshSetting = boolean | 'wait_for';
/**
*
* @public
*/
export interface SavedObjectsBulkResponse<T = unknown> {
saved_objects: Array<SavedObject<T>>;
}

View file

@ -0,0 +1,49 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type {
SavedObjectReference,
SavedObjectsMigrationVersion,
} from '@kbn/core-saved-objects-common';
/**
*
* @public
*/
export interface SavedObjectsBulkCreateObject<T = unknown> {
id?: string;
type: string;
attributes: T;
version?: string;
references?: SavedObjectReference[];
/** {@inheritDoc SavedObjectsMigrationVersion} */
migrationVersion?: SavedObjectsMigrationVersion;
/**
* A semver value that is used when upgrading objects between Kibana versions. If undefined, this will be automatically set to the current
* Kibana version when the object is created. If this is set to a non-semver value, or it is set to a semver value greater than the
* current Kibana version, it will result in an error.
*
* @remarks
* Do not attempt to set this manually. It should only be used if you retrieved an existing object that had the `coreMigrationVersion`
* field set and you want to create it again.
*/
coreMigrationVersion?: string;
/** Optional ID of the original saved object, if this object's `id` was regenerated */
originId?: string;
/**
* Optional initial namespaces for the object to be created in. If this is defined, it will supersede the namespace ID that is in
* {@link SavedObjectsCreateOptions}.
*
* * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces,
* including the "All spaces" identifier (`'*'`).
* * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only
* be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed.
* * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used.
*/
initialNamespaces?: string[];
}

View file

@ -0,0 +1,29 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/**
*
* @public
*/
export interface SavedObjectsBulkGetObject {
id: string;
type: string;
/** SavedObject fields to include in the response */
fields?: string[];
/**
* Optional namespace(s) for the object to be retrieved in. If this is defined, it will supersede the namespace ID that is in the
* top-level options.
*
* * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces,
* including the "All spaces" identifier (`'*'`).
* * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only
* be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed.
* * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used.
*/
namespaces?: string[];
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsResolveResponse } from './resolve';
/**
*
* @public
*/
export interface SavedObjectsBulkResolveObject {
id: string;
type: string;
}
/**
*
* @public
*/
export interface SavedObjectsBulkResolveResponse<T = unknown> {
resolved_objects: Array<SavedObjectsResolveResponse<T>>;
}

View file

@ -0,0 +1,48 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base';
import type { SavedObjectsUpdateOptions, SavedObjectsUpdateResponse } from './update';
/**
*
* @public
*/
export interface SavedObjectsBulkUpdateObject<T = unknown>
extends Pick<SavedObjectsUpdateOptions<T>, 'version' | 'references'> {
/** The ID of this Saved Object, guaranteed to be unique for all objects of the same `type` */
id: string;
/** The type of this Saved Object. Each plugin can define it's own custom Saved Object types. */
type: string;
/** {@inheritdoc SavedObjectAttributes} */
attributes: Partial<T>;
/**
* Optional namespace string to use when searching for this object. If this is defined, it will supersede the namespace ID that is in
* {@link SavedObjectsBulkUpdateOptions}.
*
* Note: the default namespace's string representation is `'default'`, and its ID representation is `undefined`.
**/
namespace?: string;
}
/**
*
* @public
*/
export interface SavedObjectsBulkUpdateOptions extends SavedObjectsBaseOptions {
/** The Elasticsearch Refresh setting for this operation */
refresh?: MutatingOperationRefreshSetting;
}
/**
*
* @public
*/
export interface SavedObjectsBulkUpdateResponse<T = unknown> {
saved_objects: Array<SavedObjectsUpdateResponse<T>>;
}

View file

@ -0,0 +1,30 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectError } from '@kbn/core-saved-objects-common';
/**
*
* @public
*/
export interface SavedObjectsCheckConflictsObject {
id: string;
type: string;
}
/**
*
* @public
*/
export interface SavedObjectsCheckConflictsResponse {
errors: Array<{
id: string;
type: string;
error: SavedObjectError;
}>;
}

View file

@ -0,0 +1,29 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsBaseOptions } from './base';
/**
* @public
*/
export type SavedObjectsClosePointInTimeOptions = SavedObjectsBaseOptions;
/**
* @public
*/
export interface SavedObjectsClosePointInTimeResponse {
/**
* If true, all search contexts associated with the PIT id are
* successfully closed.
*/
succeeded: boolean;
/**
* The number of search contexts that have been successfully closed.
*/
num_freed: number;
}

View file

@ -0,0 +1,77 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsBaseOptions } from './base';
/**
* An object to collect references for. It must be a multi-namespace type (in other words, the object type must be registered with the
* `namespaceType: 'multiple'` or `namespaceType: 'multiple-isolated'` option).
*
* Note: if options.purpose is 'updateObjectsSpaces', it must be a shareable type (in other words, the object type must be registered with
* the `namespaceType: 'multiple'`).
*
* @public
*/
export interface SavedObjectsCollectMultiNamespaceReferencesObject {
id: string;
type: string;
}
/**
* Options for collecting references.
*
* @public
*/
export interface SavedObjectsCollectMultiNamespaceReferencesOptions
extends SavedObjectsBaseOptions {
/** Optional purpose used to determine filtering and authorization checks; default is 'collectMultiNamespaceReferences' */
purpose?: 'collectMultiNamespaceReferences' | 'updateObjectsSpaces';
}
/**
* A returned input object or one of its references, with additional context.
*
* @public
*/
export interface SavedObjectReferenceWithContext {
/** The type of the referenced object */
type: string;
/** The ID of the referenced object */
id: string;
/** The origin ID of the referenced object (if it has one) */
originId?: string;
/** The space(s) that the referenced object exists in */
spaces: string[];
/**
* References to this object; note that this does not contain _all inbound references everywhere for this object_, it only contains
* inbound references for the scope of this operation
*/
inboundReferences: Array<{
/** The type of the object that has the inbound reference */
type: string;
/** The ID of the object that has the inbound reference */
id: string;
/** The name of the inbound reference */
name: string;
}>;
/** Whether or not this object or reference is missing */
isMissing?: boolean;
/** The space(s) that legacy URL aliases matching this type/id exist in */
spacesWithMatchingAliases?: string[];
/** The space(s) that objects matching this origin exist in (including this one) */
spacesWithMatchingOrigins?: string[];
}
/**
* The response when object references are collected.
*
* @public
*/
export interface SavedObjectsCollectMultiNamespaceReferencesResponse {
objects: SavedObjectReferenceWithContext[];
}

View file

@ -0,0 +1,57 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type {
SavedObjectsMigrationVersion,
SavedObjectReference,
} from '@kbn/core-saved-objects-common';
import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base';
/**
*
* @public
*/
export interface SavedObjectsCreateOptions extends SavedObjectsBaseOptions {
/** (not recommended) Specify an id for the document */
id?: string;
/** Overwrite existing documents (defaults to false) */
overwrite?: boolean;
/**
* An opaque version number which changes on each successful write operation.
* Can be used in conjunction with `overwrite` for implementing optimistic concurrency control.
**/
version?: string;
/** {@inheritDoc SavedObjectsMigrationVersion} */
migrationVersion?: SavedObjectsMigrationVersion;
/**
* A semver value that is used when upgrading objects between Kibana versions. If undefined, this will be automatically set to the current
* Kibana version when the object is created. If this is set to a non-semver value, or it is set to a semver value greater than the
* current Kibana version, it will result in an error.
*
* @remarks
* Do not attempt to set this manually. It should only be used if you retrieved an existing object that had the `coreMigrationVersion`
* field set and you want to create it again.
*/
coreMigrationVersion?: string;
references?: SavedObjectReference[];
/** The Elasticsearch Refresh setting for this operation */
refresh?: MutatingOperationRefreshSetting;
/** Optional ID of the original saved object, if this object's `id` was regenerated */
originId?: string;
/**
* Optional initial namespaces for the object to be created in. If this is defined, it will supersede the namespace ID that is in
* {@link SavedObjectsCreateOptions}.
*
* * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces,
* including the "All spaces" identifier (`'*'`).
* * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only
* be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed.
* * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used.
*/
initialNamespaces?: string[];
}

View file

@ -0,0 +1,47 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsFindOptions, SavedObjectsFindResponse } from './find';
import type { SavedObjectsClientContract } from '../saved_objects_client';
/**
* @public
*/
export type SavedObjectsCreatePointInTimeFinderOptions = Omit<
SavedObjectsFindOptions,
'page' | 'pit' | 'searchAfter'
>;
/**
* @public
*/
export interface SavedObjectsCreatePointInTimeFinderDependencies {
client: Pick<SavedObjectsClientContract, 'find' | 'openPointInTimeForType' | 'closePointInTime'>;
}
/** @public */
export interface ISavedObjectsPointInTimeFinder<T, A> {
/**
* An async generator which wraps calls to `savedObjectsClient.find` and
* iterates over multiple pages of results using `_pit` and `search_after`.
* This will open a new Point-In-Time (PIT), and continue paging until a set
* of results is received that's smaller than the designated `perPage` size.
*/
find: () => AsyncGenerator<SavedObjectsFindResponse<T, A>>;
/**
* Closes the Point-In-Time associated with this finder instance.
*
* Once you have retrieved all of the results you need, it is recommended
* to call `close()` to clean up the PIT and prevent Elasticsearch from
* consuming resources unnecessarily. This is only required if you are
* done iterating and have not yet paged through all of the results: the
* PIT will automatically be closed for you once you reach the last page
* of results, or if the underlying call to `find` fails for any reason.
*/
close: () => Promise<void>;
}

View file

@ -0,0 +1,20 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base';
/**
*
* @public
*/
export interface SavedObjectsDeleteOptions extends SavedObjectsBaseOptions {
/** The Elasticsearch Refresh setting for this operation */
refresh?: MutatingOperationRefreshSetting;
/** Force deletion of an object that exists in multiple namespaces */
force?: boolean;
}

View file

@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsBaseOptions } from './base';
/**
*
* @public
*/
export interface SavedObjectsDeleteByNamespaceOptions extends SavedObjectsBaseOptions {
/** The Elasticsearch supports only boolean flag for this operation */
refresh?: boolean;
}

View file

@ -0,0 +1,173 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type {
SortOrder,
AggregationsAggregationContainer,
Id as EsId,
} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SavedObject } from '@kbn/core-saved-objects-common';
type KueryNode = any;
/**
* @public
*/
export interface SavedObjectsFindOptionsReference {
type: string;
id: string;
}
/**
* @public
*/
export interface SavedObjectsPitParams {
id: string;
keepAlive?: string;
}
/**
*
* @public
*/
export interface SavedObjectsFindOptions {
type: string | string[];
page?: number;
perPage?: number;
sortField?: string;
sortOrder?: SortOrder;
/**
* An array of fields to include in the results
* @example
* SavedObjects.find({type: 'dashboard', fields: ['attributes.name', 'attributes.location']})
*/
fields?: string[];
/** Search documents using the Elasticsearch Simple Query String syntax. See Elasticsearch Simple Query String `query` argument for more information */
search?: string;
/** The fields to perform the parsed query against. See Elasticsearch Simple Query String `fields` argument for more information */
searchFields?: string[];
/**
* Use the sort values from the previous page to retrieve the next page of results.
*/
searchAfter?: EsId[];
/**
* The fields to perform the parsed query against. Unlike the `searchFields` argument, these are expected to be root fields and will not
* be modified. If used in conjunction with `searchFields`, both are concatenated together.
*/
rootSearchFields?: string[];
/**
* Search for documents having a reference to the specified objects.
* Use `hasReferenceOperator` to specify the operator to use when searching for multiple references.
*/
hasReference?: SavedObjectsFindOptionsReference | SavedObjectsFindOptionsReference[];
/**
* The operator to use when searching by multiple references using the `hasReference` option. Defaults to `OR`
*/
hasReferenceOperator?: 'AND' | 'OR';
/**
* The search operator to use with the provided filter. Defaults to `OR`
*/
defaultSearchOperator?: 'AND' | 'OR';
filter?: string | KueryNode;
/**
* A record of aggregations to perform.
* The API currently only supports a limited set of metrics and bucket aggregation types.
* Additional aggregation types can be contributed to Core.
*
* @example
* Aggregating on SO attribute field
* ```ts
* const aggs = { latest_version: { max: { field: 'dashboard.attributes.version' } } };
* return client.find({ type: 'dashboard', aggs })
* ```
*
* @example
* Aggregating on SO root field
* ```ts
* const aggs = { latest_update: { max: { field: 'dashboard.updated_at' } } };
* return client.find({ type: 'dashboard', aggs })
* ```
*
* @alpha
*/
aggs?: Record<string, AggregationsAggregationContainer>;
namespaces?: string[];
/**
* This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved
* object client wrapper.
* If this is defined, it supersedes the `type` and `namespaces` fields when building the Elasticsearch query.
* Any types that are not included in this map will be excluded entirely.
* If a type is included but its value is undefined, the operation will search for that type in the Default namespace.
*/
typeToNamespacesMap?: Map<string, string[] | undefined>;
/** An optional ES preference value to be used for the query **/
preference?: string;
/**
* Search against a specific Point In Time (PIT) that you've opened with {@link SavedObjectsClient.openPointInTimeForType}.
*/
pit?: SavedObjectsPitParams;
}
/**
*
* @public
*/
export interface SavedObjectsFindResult<T = unknown> extends SavedObject<T> {
/**
* The Elasticsearch `_score` of this result.
*/
score: number;
/**
* The Elasticsearch `sort` value of this result.
*
* @remarks
* This can be passed directly to the `searchAfter` param in the {@link SavedObjectsFindOptions}
* in order to page through large numbers of hits. It is recommended you use this alongside
* a Point In Time (PIT) that was opened with {@link SavedObjectsClient.openPointInTimeForType}.
*
* @example
* ```ts
* const { id } = await savedObjectsClient.openPointInTimeForType('visualization');
* const page1 = await savedObjectsClient.find({
* type: 'visualization',
* sortField: 'updated_at',
* sortOrder: 'asc',
* pit: { id },
* });
* const lastHit = page1.saved_objects[page1.saved_objects.length - 1];
* const page2 = await savedObjectsClient.find({
* type: 'visualization',
* sortField: 'updated_at',
* sortOrder: 'asc',
* pit: { id: page1.pit_id },
* searchAfter: lastHit.sort,
* });
* await savedObjectsClient.closePointInTime(page2.pit_id);
* ```
*/
sort?: string[];
}
/**
* Return type of the Saved Objects `find()` method.
*
* *Note*: this type is different between the Public and Server Saved Objects
* clients.
*
* @public
*/
export interface SavedObjectsFindResponse<T = unknown, A = unknown> {
aggregations?: A;
saved_objects: Array<SavedObjectsFindResult<T>>;
total: number;
per_page: number;
page: number;
pit_id?: string;
}

View file

@ -0,0 +1,43 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsMigrationVersion } from '@kbn/core-saved-objects-common';
import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base';
/**
* @public
*/
export interface SavedObjectsIncrementCounterOptions<Attributes = unknown>
extends SavedObjectsBaseOptions {
/**
* (default=false) If true, sets all the counter fields to 0 if they don't
* already exist. Existing fields will be left as-is and won't be incremented.
*/
initialize?: boolean;
/** {@link SavedObjectsMigrationVersion} */
migrationVersion?: SavedObjectsMigrationVersion;
/**
* (default='wait_for') The Elasticsearch refresh setting for this
* operation. See {@link MutatingOperationRefreshSetting}
*/
refresh?: MutatingOperationRefreshSetting;
/**
* Attributes to use when upserting the document if it doesn't exist.
*/
upsertAttributes?: Attributes;
}
/**
* @public
*/
export interface SavedObjectsIncrementCounterField {
/** The field name to increment the counter by.*/
fieldName: string;
/** The number to increment the field by (defaults to 1).*/
incrementBy?: number;
}

View file

@ -0,0 +1,73 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export type {
SavedObjectsBaseOptions,
MutatingOperationRefreshSetting,
SavedObjectsBulkResponse,
} from './base';
export type { SavedObjectsBulkCreateObject } from './bulk_create';
export type { SavedObjectsBulkGetObject } from './bulk_get';
export type {
SavedObjectsBulkResolveObject,
SavedObjectsBulkResolveResponse,
} from './bulk_resolve';
export type {
SavedObjectsBulkUpdateObject,
SavedObjectsBulkUpdateResponse,
SavedObjectsBulkUpdateOptions,
} from './bulk_update';
export type {
SavedObjectsCheckConflictsObject,
SavedObjectsCheckConflictsResponse,
} from './check_conflicts';
export type {
SavedObjectsClosePointInTimeOptions,
SavedObjectsClosePointInTimeResponse,
} from './close_point_in_time';
export type {
SavedObjectsCollectMultiNamespaceReferencesObject,
SavedObjectReferenceWithContext,
SavedObjectsCollectMultiNamespaceReferencesResponse,
SavedObjectsCollectMultiNamespaceReferencesOptions,
} from './collect_multinamespace_references';
export type { SavedObjectsCreateOptions } from './create';
export type {
SavedObjectsCreatePointInTimeFinderOptions,
SavedObjectsCreatePointInTimeFinderDependencies,
ISavedObjectsPointInTimeFinder,
} from './create_point_in_time_finder';
export type { SavedObjectsDeleteOptions } from './delete';
export type { SavedObjectsDeleteByNamespaceOptions } from './delete_by_namespace';
export type {
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsFindResponse,
SavedObjectsFindResult,
SavedObjectsPitParams,
} from './find';
export type {
SavedObjectsIncrementCounterField,
SavedObjectsIncrementCounterOptions,
} from './increment_counter';
export type {
SavedObjectsOpenPointInTimeOptions,
SavedObjectsOpenPointInTimeResponse,
} from './open_point_in_time_for_type';
export type {
SavedObjectsRemoveReferencesToOptions,
SavedObjectsRemoveReferencesToResponse,
} from './remove_references_to';
export type { SavedObjectsResolveResponse } from './resolve';
export type { SavedObjectsUpdateResponse, SavedObjectsUpdateOptions } from './update';
export type {
SavedObjectsUpdateObjectsSpacesObject,
SavedObjectsUpdateObjectsSpacesResponse,
SavedObjectsUpdateObjectsSpacesOptions,
SavedObjectsUpdateObjectsSpacesResponseObject,
} from './update_objects_spaces';

View file

@ -0,0 +1,40 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/**
* @public
*/
export interface SavedObjectsOpenPointInTimeOptions {
/**
* Optionally specify how long ES should keep the PIT alive until the next request. Defaults to `5m`.
*/
keepAlive?: string;
/**
* An optional ES preference value to be used for the query.
*/
preference?: string;
/**
* An optional list of namespaces to be used when opening the PIT.
*
* When the spaces plugin is enabled:
* - this will default to the user's current space (as determined by the URL)
* - if specified, the user's current space will be ignored
* - `['*']` will search across all available spaces
*/
namespaces?: string[];
}
/**
* @public
*/
export interface SavedObjectsOpenPointInTimeResponse {
/**
* PIT ID returned from ES.
*/
id: string;
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectsBaseOptions } from './base';
/**
*
* @public
*/
export interface SavedObjectsRemoveReferencesToOptions extends SavedObjectsBaseOptions {
/** The Elasticsearch Refresh setting for this operation. Defaults to `true` */
refresh?: boolean;
}
/**
*
* @public
*/
export interface SavedObjectsRemoveReferencesToResponse extends SavedObjectsBaseOptions {
/** The number of objects that have been updated by this operation */
updated: number;
}

View file

@ -0,0 +1,45 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObject } from '@kbn/core-saved-objects-common';
/**
*
* @public
*/
export interface SavedObjectsResolveResponse<T = unknown> {
/**
* The saved object that was found.
*/
saved_object: SavedObject<T>;
/**
* The outcome for a successful `resolve` call is one of the following values:
*
* * `'exactMatch'` -- One document exactly matched the given ID.
* * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different
* than the given ID.
* * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the
* `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID.
*/
outcome: 'exactMatch' | 'aliasMatch' | 'conflict';
/**
* The ID of the object that the legacy URL alias points to.
*
* **Note:** this field is *only* included when an alias was found (in other words, when the outcome is `'aliasMatch'` or `'conflict'`).
*/
alias_target_id?: string;
/**
* The reason this alias was created.
*
* Currently this is used to determine whether or not a toast should be shown when a user is redirected from a legacy URL; if the alias
* was created because of saved object conversion, then we will display a toast telling the user that the object has a new URL.
*
* **Note:** this field is *only* included when an alias was found (in other words, when the outcome is `'aliasMatch'` or `'conflict'`).
*/
alias_purpose?: 'savedObjectConversion' | 'savedObjectImport';
}

View file

@ -0,0 +1,43 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectReference, SavedObject } from '@kbn/core-saved-objects-common';
import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base';
/**
*
* @public
*/
export interface SavedObjectsUpdateOptions<Attributes = unknown> extends SavedObjectsBaseOptions {
/**
* An opaque version number which changes on each successful write operation.
* Can be used for implementing optimistic concurrency control.
*/
version?: string;
/** {@inheritdoc SavedObjectReference} */
references?: SavedObjectReference[];
/** The Elasticsearch Refresh setting for this operation */
refresh?: MutatingOperationRefreshSetting;
/** If specified, will be used to perform an upsert if the document doesn't exist */
upsert?: Attributes;
/**
* The Elasticsearch `retry_on_conflict` setting for this operation.
* Defaults to `0` when `version` is provided, `3` otherwise.
*/
retryOnConflict?: number;
}
/**
*
* @public
*/
export interface SavedObjectsUpdateResponse<T = unknown>
extends Omit<SavedObject<T>, 'attributes' | 'references'> {
attributes: Partial<T>;
references: SavedObjectReference[] | undefined;
}

View file

@ -0,0 +1,69 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObjectError } from '@kbn/core-saved-objects-common';
import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base';
/**
* An object that should have its spaces updated.
*
* @public
*/
export interface SavedObjectsUpdateObjectsSpacesObject {
/** The type of the object to update */
id: string;
/** The ID of the object to update */
type: string;
/**
* The space(s) that the object to update currently exists in. This is only intended to be used by SOC wrappers.
*
* @internal
*/
spaces?: string[];
/**
* The version of the object to update; this is used for optimistic concurrency control. This is only intended to be used by SOC wrappers.
*
* @internal
*/
version?: string;
}
/**
* Options for the update operation.
*
* @public
*/
export interface SavedObjectsUpdateObjectsSpacesOptions extends SavedObjectsBaseOptions {
/** The Elasticsearch Refresh setting for this operation */
refresh?: MutatingOperationRefreshSetting;
}
/**
* The response when objects' spaces are updated.
*
* @public
*/
export interface SavedObjectsUpdateObjectsSpacesResponse {
objects: SavedObjectsUpdateObjectsSpacesResponseObject[];
}
/**
* Details about a specific object's update result.
*
* @public
*/
export interface SavedObjectsUpdateObjectsSpacesResponseObject {
/** The type of the referenced object */
type: string;
/** The ID of the referenced object */
id: string;
/** The space(s) that the referenced object exists in */
spaces: string[];
/** Included if there was an error updating this object's spaces */
error?: SavedObjectError;
}

View file

@ -0,0 +1,54 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export type { SavedObjectsClientContract } from './saved_objects_client';
export type { ISavedObjectsRepository } from './saved_objects_repository';
export type {
MutatingOperationRefreshSetting,
SavedObjectsBaseOptions,
SavedObjectsIncrementCounterOptions,
SavedObjectsDeleteByNamespaceOptions,
SavedObjectsBulkResponse,
SavedObjectsUpdateResponse,
SavedObjectsBulkGetObject,
SavedObjectsBulkResolveObject,
SavedObjectsIncrementCounterField,
SavedObjectsBulkCreateObject,
SavedObjectsBulkResolveResponse,
SavedObjectsCreateOptions,
SavedObjectsFindResponse,
SavedObjectsBulkUpdateResponse,
SavedObjectsUpdateObjectsSpacesResponse,
SavedObjectsUpdateObjectsSpacesOptions,
SavedObjectsCollectMultiNamespaceReferencesOptions,
SavedObjectsCollectMultiNamespaceReferencesResponse,
SavedObjectsRemoveReferencesToResponse,
SavedObjectsCheckConflictsObject,
SavedObjectsCheckConflictsResponse,
SavedObjectsBulkUpdateOptions,
SavedObjectsFindOptionsReference,
SavedObjectsFindResult,
SavedObjectsRemoveReferencesToOptions,
SavedObjectsDeleteOptions,
SavedObjectsOpenPointInTimeResponse,
SavedObjectsBulkUpdateObject,
SavedObjectsClosePointInTimeResponse,
ISavedObjectsPointInTimeFinder,
SavedObjectsCreatePointInTimeFinderDependencies,
SavedObjectsPitParams,
SavedObjectsResolveResponse,
SavedObjectsCollectMultiNamespaceReferencesObject,
SavedObjectsUpdateObjectsSpacesResponseObject,
SavedObjectsUpdateObjectsSpacesObject,
SavedObjectReferenceWithContext,
SavedObjectsUpdateOptions,
SavedObjectsOpenPointInTimeOptions,
SavedObjectsClosePointInTimeOptions,
SavedObjectsCreatePointInTimeFinderOptions,
SavedObjectsFindOptions,
} from './apis';

View file

@ -0,0 +1,359 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type {
SavedObjectsBaseOptions,
SavedObjectsFindOptions,
SavedObjectsClosePointInTimeOptions,
SavedObjectsOpenPointInTimeOptions,
SavedObjectsCreatePointInTimeFinderOptions,
SavedObjectsUpdateOptions,
SavedObjectsUpdateResponse,
SavedObjectsUpdateObjectsSpacesObject,
SavedObjectsUpdateObjectsSpacesOptions,
SavedObjectsCollectMultiNamespaceReferencesObject,
SavedObjectsUpdateObjectsSpacesResponse,
SavedObjectsResolveResponse,
ISavedObjectsPointInTimeFinder,
SavedObjectsRemoveReferencesToOptions,
SavedObjectsClosePointInTimeResponse,
SavedObjectsDeleteOptions,
SavedObjectsCreatePointInTimeFinderDependencies,
SavedObjectsCheckConflictsResponse,
SavedObjectsBulkUpdateOptions,
SavedObjectsCollectMultiNamespaceReferencesResponse,
SavedObjectsBulkUpdateResponse,
SavedObjectsFindResponse,
SavedObjectsCreateOptions,
SavedObjectsCheckConflictsObject,
SavedObjectsBulkUpdateObject,
SavedObjectsBulkResolveResponse,
SavedObjectsBulkResolveObject,
SavedObjectsBulkGetObject,
SavedObjectsBulkCreateObject,
SavedObjectsOpenPointInTimeResponse,
SavedObjectsRemoveReferencesToResponse,
SavedObjectsCollectMultiNamespaceReferencesOptions,
SavedObjectsBulkResponse,
} from './apis';
/**
* Saved Objects is Kibana's data persisentence mechanism allowing plugins to
* use Elasticsearch for storing plugin state.
*
* ## SavedObjectsClient errors
*
* Since the SavedObjectsClient has its hands in everything we
* are a little paranoid about the way we present errors back to
* to application code. Ideally, all errors will be either:
*
* 1. Caused by bad implementation (ie. undefined is not a function) and
* as such unpredictable
* 2. An error that has been classified and decorated appropriately
* by the decorators in {@link SavedObjectsErrorHelpers}
*
* Type 1 errors are inevitable, but since all expected/handle-able errors
* should be Type 2 the `isXYZError()` helpers exposed at
* `SavedObjectsErrorHelpers` should be used to understand and manage error
* responses from the `SavedObjectsClient`.
*
* Type 2 errors are decorated versions of the source error, so if
* the elasticsearch client threw an error it will be decorated based
* on its type. That means that rather than looking for `error.body.error.type` or
* doing substring checks on `error.body.error.reason`, just use the helpers to
* understand the meaning of the error:
*
* ```js
* if (SavedObjectsErrorHelpers.isNotFoundError(error)) {
* // handle 404
* }
*
* if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) {
* // 401 handling should be automatic, but in case you wanted to know
* }
*
* // always rethrow the error unless you handle it
* throw error;
* ```
*
* ### 404s from missing index
*
* From the perspective of application code and APIs the SavedObjectsClient is
* a black box that persists objects. One of the internal details that users have
* no control over is that we use an elasticsearch index for persistence and that
* index might be missing.
*
* At the time of writing we are in the process of transitioning away from the
* operating assumption that the SavedObjects index is always available. Part of
* this transition is handling errors resulting from an index missing. These used
* to trigger a 500 error in most cases, and in others cause 404s with different
* error messages.
*
* From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The
* object the request/call was targeting could not be found. This is why #14141
* takes special care to ensure that 404 errors are generic and don't distinguish
* between index missing or document missing.
*
* See {@link SavedObjectsClient}
* See {@link SavedObjectsErrorHelpers}
*
* @public
*/
export interface SavedObjectsClientContract {
/**
* Persists a SavedObject
*
* @param type
* @param attributes
* @param options
*/
create<T = unknown>(
type: string,
attributes: T,
options?: SavedObjectsCreateOptions
): Promise<SavedObject<T>>;
/**
* Persists multiple documents batched together as a single request
*
* @param objects
* @param options
*/
bulkCreate<T = unknown>(
objects: Array<SavedObjectsBulkCreateObject<T>>,
options?: SavedObjectsCreateOptions
): Promise<SavedObjectsBulkResponse<T>>;
/**
* Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are
* multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten.
*
* @param objects
* @param options
*/
checkConflicts(
objects: SavedObjectsCheckConflictsObject[],
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsCheckConflictsResponse>;
/**
* Deletes a SavedObject
*
* @param type
* @param id
* @param options
*/
delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>;
/**
* Find all SavedObjects matching the search query
*
* @param options
*/
find<T = unknown, A = unknown>(
options: SavedObjectsFindOptions
): Promise<SavedObjectsFindResponse<T, A>>;
/**
* Returns an array of objects by id
*
* @param objects - an array of ids, or an array of objects containing id, type and optionally fields
* @example
*
* bulkGet([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*/
bulkGet<T = unknown>(
objects: SavedObjectsBulkGetObject[],
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsBulkResponse<T>>;
/**
* Retrieves a single object
*
* @param type - The type of SavedObject to retrieve
* @param id - The ID of the SavedObject to retrieve
* @param options
*/
get<T = unknown>(
type: string,
id: string,
options?: SavedObjectsBaseOptions
): Promise<SavedObject<T>>;
/**
* Resolves an array of objects by id, using any legacy URL aliases if they exist
*
* @param objects - an array of objects containing id, type
* @example
*
* bulkResolve([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*
* @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the
* outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior is unique to
* `bulkResolve`; the regular `resolve` API will throw an error instead.
*/
bulkResolve<T = unknown>(
objects: SavedObjectsBulkResolveObject[],
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsBulkResolveResponse<T>>;
/**
* Resolves a single object, using any legacy URL alias if it exists
*
* @param type - The type of SavedObject to retrieve
* @param id - The ID of the SavedObject to retrieve
* @param options
*/
resolve<T = unknown>(
type: string,
id: string,
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsResolveResponse<T>>;
/**
* Updates an SavedObject
*
* @param type
* @param id
* @param options
*/
update<T = unknown>(
type: string,
id: string,
attributes: Partial<T>,
options?: SavedObjectsUpdateOptions<T>
): Promise<SavedObjectsUpdateResponse<T>>;
/**
* Bulk Updates multiple SavedObject at once
*
* @param objects
*/
bulkUpdate<T = unknown>(
objects: Array<SavedObjectsBulkUpdateObject<T>>,
options?: SavedObjectsBulkUpdateOptions
): Promise<SavedObjectsBulkUpdateResponse<T>>;
/**
* Updates all objects containing a reference to the given {type, id} tuple to remove the said reference.
*/
removeReferencesTo(
type: string,
id: string,
options?: SavedObjectsRemoveReferencesToOptions
): Promise<SavedObjectsRemoveReferencesToResponse>;
/**
* Opens a Point In Time (PIT) against the indices for the specified Saved Object types.
* The returned `id` can then be passed to {@link SavedObjectsClient.find} to search
* against that PIT.
*
* Only use this API if you have an advanced use case that's not solved by the
* {@link SavedObjectsClient.createPointInTimeFinder} method.
*/
openPointInTimeForType(
type: string | string[],
options?: SavedObjectsOpenPointInTimeOptions
): Promise<SavedObjectsOpenPointInTimeResponse>;
/**
* Closes a Point In Time (PIT) by ID. This simply proxies the request to ES via the
* Elasticsearch client, and is included in the Saved Objects Client as a convenience
* for consumers who are using {@link SavedObjectsClient.openPointInTimeForType}.
*
* Only use this API if you have an advanced use case that's not solved by the
* {@link SavedObjectsClient.createPointInTimeFinder} method.
*/
closePointInTime(
id: string,
options?: SavedObjectsClosePointInTimeOptions
): Promise<SavedObjectsClosePointInTimeResponse>;
/**
* Returns a {@link ISavedObjectsPointInTimeFinder} to help page through
* large sets of saved objects. We strongly recommend using this API for
* any `find` queries that might return more than 1000 saved objects,
* however this API is only intended for use in server-side "batch"
* processing of objects where you are collecting all objects in memory
* or streaming them back to the client.
*
* Do NOT use this API in a route handler to facilitate paging through
* saved objects on the client-side unless you are streaming all of the
* results back to the client at once. Because the returned generator is
* stateful, you cannot rely on subsequent http requests retrieving new
* pages from the same Kibana server in multi-instance deployments.
*
* The generator wraps calls to {@link SavedObjectsClient.find} and iterates
* over multiple pages of results using `_pit` and `search_after`. This will
* open a new Point-In-Time (PIT), and continue paging until a set of
* results is received that's smaller than the designated `perPage`.
*
* Once you have retrieved all of the results you need, it is recommended
* to call `close()` to clean up the PIT and prevent Elasticsearch from
* consuming resources unnecessarily. This is only required if you are
* done iterating and have not yet paged through all of the results: the
* PIT will automatically be closed for you once you reach the last page
* of results, or if the underlying call to `find` fails for any reason.
*
* @example
* ```ts
* const findOptions: SavedObjectsCreatePointInTimeFinderOptions = {
* type: 'visualization',
* search: 'foo*',
* perPage: 100,
* };
*
* const finder = savedObjectsClient.createPointInTimeFinder(findOptions);
*
* const responses: SavedObjectFindResponse[] = [];
* for await (const response of finder.find()) {
* responses.push(...response);
* if (doneSearching) {
* await finder.close();
* }
* }
* ```
*/
createPointInTimeFinder<T = unknown, A = unknown>(
findOptions: SavedObjectsCreatePointInTimeFinderOptions,
dependencies?: SavedObjectsCreatePointInTimeFinderDependencies
): ISavedObjectsPointInTimeFinder<T, A>;
/**
* Gets all references and transitive references of the listed objects. Ignores any object that is not a multi-namespace type.
*
* @param objects
* @param options
*/
collectMultiNamespaceReferences(
objects: SavedObjectsCollectMultiNamespaceReferencesObject[],
options?: SavedObjectsCollectMultiNamespaceReferencesOptions
): Promise<SavedObjectsCollectMultiNamespaceReferencesResponse>;
/**
* Updates one or more objects to add and/or remove them from specified spaces.
*
* @param objects
* @param spacesToAdd
* @param spacesToRemove
* @param options
*/
updateObjectsSpaces(
objects: SavedObjectsUpdateObjectsSpacesObject[],
spacesToAdd: string[],
spacesToRemove: string[],
options?: SavedObjectsUpdateObjectsSpacesOptions
): Promise<SavedObjectsUpdateObjectsSpacesResponse>;
}

View file

@ -0,0 +1,476 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type {
SavedObjectsBaseOptions,
SavedObjectsFindOptions,
SavedObjectsClosePointInTimeOptions,
SavedObjectsOpenPointInTimeOptions,
SavedObjectsCreatePointInTimeFinderOptions,
SavedObjectsUpdateOptions,
SavedObjectsUpdateResponse,
SavedObjectsUpdateObjectsSpacesObject,
SavedObjectsUpdateObjectsSpacesOptions,
SavedObjectsCollectMultiNamespaceReferencesObject,
SavedObjectsUpdateObjectsSpacesResponse,
SavedObjectsResolveResponse,
ISavedObjectsPointInTimeFinder,
SavedObjectsRemoveReferencesToOptions,
SavedObjectsClosePointInTimeResponse,
SavedObjectsDeleteOptions,
SavedObjectsCreatePointInTimeFinderDependencies,
SavedObjectsCheckConflictsResponse,
SavedObjectsBulkUpdateOptions,
SavedObjectsCollectMultiNamespaceReferencesResponse,
SavedObjectsBulkUpdateResponse,
SavedObjectsFindResponse,
SavedObjectsCreateOptions,
SavedObjectsCheckConflictsObject,
SavedObjectsBulkUpdateObject,
SavedObjectsBulkResolveResponse,
SavedObjectsBulkResolveObject,
SavedObjectsBulkGetObject,
SavedObjectsBulkCreateObject,
SavedObjectsOpenPointInTimeResponse,
SavedObjectsRemoveReferencesToResponse,
SavedObjectsCollectMultiNamespaceReferencesOptions,
SavedObjectsBulkResponse,
SavedObjectsDeleteByNamespaceOptions,
SavedObjectsIncrementCounterField,
SavedObjectsIncrementCounterOptions,
} from './apis';
/**
* The savedObjects repository contract.
*
* @public
*/
export interface ISavedObjectsRepository {
/**
* Persists an object
*
* @param {string} type
* @param {object} attributes
* @param {object} [options={}]
* @property {string} [options.id] - force id on creation, not recommended
* @property {boolean} [options.overwrite=false]
* @property {object} [options.migrationVersion=undefined]
* @property {string} [options.namespace]
* @property {array} [options.references=[]] - [{ name, type, id }]
* @returns {promise} - { id, type, version, attributes }
*/
create<T = unknown>(
type: string,
attributes: T,
options?: SavedObjectsCreateOptions
): Promise<SavedObject<T>>;
/**
* Creates multiple documents at once
*
* @param {array} objects - [{ type, id, attributes, references, migrationVersion }]
* @param {object} [options={}]
* @property {boolean} [options.overwrite=false] - overwrites existing documents
* @property {string} [options.namespace]
* @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]}
*/
bulkCreate<T = unknown>(
objects: Array<SavedObjectsBulkCreateObject<T>>,
options?: SavedObjectsCreateOptions
): Promise<SavedObjectsBulkResponse<T>>;
/**
* Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are
* multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten.
*/
checkConflicts(
objects: SavedObjectsCheckConflictsObject[],
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsCheckConflictsResponse>;
/**
* Deletes an object
*
* @param {string} type
* @param {string} id
* @param {object} [options={}]
* @property {string} [options.namespace]
* @returns {promise}
*/
delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>;
/**
* Deletes all objects from the provided namespace.
*
* @param {string} namespace
* @returns {promise} - { took, timed_out, total, deleted, batches, version_conflicts, noops, retries, failures }
*/
deleteByNamespace(
namespace: string,
options?: SavedObjectsDeleteByNamespaceOptions
): Promise<any>;
/**
* @param {object} [options={}]
* @property {(string|Array<string>)} [options.type]
* @property {string} [options.search]
* @property {string} [options.defaultSearchOperator]
* @property {Array<string>} [options.searchFields] - see Elasticsearch Simple Query String
* Query field argument for more information
* @property {integer} [options.page=1]
* @property {integer} [options.perPage=20]
* @property {Array<unknown>} [options.searchAfter]
* @property {string} [options.sortField]
* @property {string} [options.sortOrder]
* @property {Array<string>} [options.fields]
* @property {string} [options.namespace]
* @property {object} [options.hasReference] - { type, id }
* @property {string} [options.pit]
* @property {string} [options.preference]
* @returns {promise} - { saved_objects: [{ id, type, version, attributes }], total, per_page, page }
*/
find<T = unknown, A = unknown>(
options: SavedObjectsFindOptions
): Promise<SavedObjectsFindResponse<T, A>>;
/**
* Returns an array of objects by id
*
* @param {array} objects - an array of objects containing id, type and optionally fields
* @param {object} [options={}]
* @property {string} [options.namespace]
* @returns {promise} - { saved_objects: [{ id, type, version, attributes }] }
* @example
*
* bulkGet([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*/
bulkGet<T = unknown>(
objects: SavedObjectsBulkGetObject[],
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsBulkResponse<T>>;
/**
* Resolves an array of objects by id, using any legacy URL aliases if they exist
*
* @param {array} objects - an array of objects containing id, type
* @param {object} [options={}]
* @property {string} [options.namespace]
* @returns {promise} - { resolved_objects: [{ saved_object, outcome }] }
* @example
*
* bulkResolve([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*/
bulkResolve<T = unknown>(
objects: SavedObjectsBulkResolveObject[],
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsBulkResolveResponse<T>>;
/**
* Gets a single object
*
* @param {string} type
* @param {string} id
* @param {object} [options={}]
* @property {string} [options.namespace]
* @returns {promise} - { id, type, version, attributes }
*/
get<T = unknown>(
type: string,
id: string,
options?: SavedObjectsBaseOptions
): Promise<SavedObject<T>>;
/**
* Resolves a single object, using any legacy URL alias if it exists
*
* @param {string} type
* @param {string} id
* @param {object} [options={}]
* @property {string} [options.namespace]
* @returns {promise} - { saved_object, outcome }
*/
resolve<T = unknown>(
type: string,
id: string,
options?: SavedObjectsBaseOptions
): Promise<SavedObjectsResolveResponse<T>>;
/**
* Updates an object
*
* @param {string} type
* @param {string} id
* @param {object} [options={}]
* @property {string} options.version - ensures version matches that of persisted object
* @property {string} [options.namespace]
* @property {array} [options.references] - [{ name, type, id }]
* @returns {promise}
*/
update<T = unknown>(
type: string,
id: string,
attributes: Partial<T>,
options?: SavedObjectsUpdateOptions<T>
): Promise<SavedObjectsUpdateResponse<T>>;
/**
* Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace
* type.
*
* @param objects The objects to get the references for.
*/
collectMultiNamespaceReferences(
objects: SavedObjectsCollectMultiNamespaceReferencesObject[],
options?: SavedObjectsCollectMultiNamespaceReferencesOptions
): Promise<SavedObjectsCollectMultiNamespaceReferencesResponse>;
/**
* Updates one or more objects to add and/or remove them from specified spaces.
*
* @param objects
* @param spacesToAdd
* @param spacesToRemove
* @param options
*/
updateObjectsSpaces(
objects: SavedObjectsUpdateObjectsSpacesObject[],
spacesToAdd: string[],
spacesToRemove: string[],
options?: SavedObjectsUpdateObjectsSpacesOptions
): Promise<SavedObjectsUpdateObjectsSpacesResponse>;
/**
* Updates multiple objects in bulk
*
* @param {array} objects - [{ type, id, attributes, options: { version, namespace } references }]
* @property {string} options.version - ensures version matches that of persisted object
* @property {string} [options.namespace]
* @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]}
*/
bulkUpdate<T = unknown>(
objects: Array<SavedObjectsBulkUpdateObject<T>>,
options?: SavedObjectsBulkUpdateOptions
): Promise<SavedObjectsBulkUpdateResponse<T>>;
/**
* Updates all objects containing a reference to the given {type, id} tuple to remove the said reference.
*
* @remarks Will throw a conflict error if the `update_by_query` operation returns any failure. In that case
* some references might have been removed, and some were not. It is the caller's responsibility
* to handle and fix this situation if it was to happen.
*/
removeReferencesTo(
type: string,
id: string,
options?: SavedObjectsRemoveReferencesToOptions
): Promise<SavedObjectsRemoveReferencesToResponse>;
/**
* Increments all the specified counter fields (by one by default). Creates the document
* if one doesn't exist for the given id.
*
* @remarks
* When supplying a field name like `stats.api.counter` the field name will
* be used as-is to create a document like:
* `{attributes: {'stats.api.counter': 1}}`
* It will not create a nested structure like:
* `{attributes: {stats: {api: {counter: 1}}}}`
*
* When using incrementCounter for collecting usage data, you need to ensure
* that usage collection happens on a best-effort basis and doesn't
* negatively affect your plugin or users. See https://github.com/elastic/kibana/blob/main/src/plugins/usage_collection/README.mdx#tracking-interactions-with-incrementcounter)
*
* @example
* ```ts
* const repository = coreStart.savedObjects.createInternalRepository();
*
* // Initialize all fields to 0
* repository
* .incrementCounter('dashboard_counter_type', 'counter_id', [
* 'stats.apiCalls',
* 'stats.sampleDataInstalled',
* ], {initialize: true});
*
* // Increment the apiCalls field counter
* repository
* .incrementCounter('dashboard_counter_type', 'counter_id', [
* 'stats.apiCalls',
* ])
*
* // Increment the apiCalls field counter by 4
* repository
* .incrementCounter('dashboard_counter_type', 'counter_id', [
* { fieldName: 'stats.apiCalls' incrementBy: 4 },
* ])
*
* // Initialize the document with arbitrary fields if not present
* repository.incrementCounter<{ appId: string }>(
* 'dashboard_counter_type',
* 'counter_id',
* [ 'stats.apiCalls'],
* { upsertAttributes: { appId: 'myId' } }
* )
* ```
*
* @param type - The type of saved object whose fields should be incremented
* @param id - The id of the document whose fields should be incremented
* @param counterFields - An array of field names to increment or an array of {@link SavedObjectsIncrementCounterField}
* @param options - {@link SavedObjectsIncrementCounterOptions}
* @returns The saved object after the specified fields were incremented
*/
incrementCounter<T = unknown>(
type: string,
id: string,
counterFields: Array<string | SavedObjectsIncrementCounterField>,
options?: SavedObjectsIncrementCounterOptions<T>
): Promise<SavedObject<T>>;
/**
* Opens a Point In Time (PIT) against the indices for the specified Saved Object types.
* The returned `id` can then be passed to `SavedObjects.find` to search against that PIT.
*
* Only use this API if you have an advanced use case that's not solved by the
* {@link SavedObjectsRepository.createPointInTimeFinder} method.
*
* @example
* ```ts
* const { id } = await savedObjectsClient.openPointInTimeForType(
* type: 'visualization',
* { keepAlive: '5m' },
* );
* const page1 = await savedObjectsClient.find({
* type: 'visualization',
* sortField: 'updated_at',
* sortOrder: 'asc',
* pit: { id, keepAlive: '2m' },
* });
* const lastHit = page1.saved_objects[page1.saved_objects.length - 1];
* const page2 = await savedObjectsClient.find({
* type: 'visualization',
* sortField: 'updated_at',
* sortOrder: 'asc',
* pit: { id: page1.pit_id },
* searchAfter: lastHit.sort,
* });
* await savedObjectsClient.closePointInTime(page2.pit_id);
* ```
*
* @param {string|Array<string>} type
* @param {object} [options] - {@link SavedObjectsOpenPointInTimeOptions}
* @property {string} [options.keepAlive]
* @property {string} [options.preference]
* @returns {promise} - { id: string }
*/
openPointInTimeForType(
type: string | string[],
options?: SavedObjectsOpenPointInTimeOptions
): Promise<SavedObjectsOpenPointInTimeResponse>;
/**
* Closes a Point In Time (PIT) by ID. This simply proxies the request to ES
* via the Elasticsearch client, and is included in the Saved Objects Client
* as a convenience for consumers who are using `openPointInTimeForType`.
*
* Only use this API if you have an advanced use case that's not solved by the
* {@link SavedObjectsRepository.createPointInTimeFinder} method.
*
* @remarks
* While the `keepAlive` that is provided will cause a PIT to automatically close,
* it is highly recommended to explicitly close a PIT when you are done with it
* in order to avoid consuming unneeded resources in Elasticsearch.
*
* @example
* ```ts
* const repository = coreStart.savedObjects.createInternalRepository();
*
* const { id } = await repository.openPointInTimeForType(
* type: 'index-pattern',
* { keepAlive: '2m' },
* );
*
* const response = await repository.find({
* type: 'index-pattern',
* search: 'foo*',
* sortField: 'name',
* sortOrder: 'desc',
* pit: {
* id: 'abc123',
* keepAlive: '2m',
* },
* searchAfter: [1234, 'abcd'],
* });
*
* await repository.closePointInTime(response.pit_id);
* ```
*
* @param {string} id
* @param {object} [options] - {@link SavedObjectsClosePointInTimeOptions}
* @returns {promise} - {@link SavedObjectsClosePointInTimeResponse}
*/
closePointInTime(
id: string,
options?: SavedObjectsClosePointInTimeOptions
): Promise<SavedObjectsClosePointInTimeResponse>;
/**
* Returns a {@link ISavedObjectsPointInTimeFinder} to help page through
* large sets of saved objects. We strongly recommend using this API for
* any `find` queries that might return more than 1000 saved objects,
* however this API is only intended for use in server-side "batch"
* processing of objects where you are collecting all objects in memory
* or streaming them back to the client.
*
* Do NOT use this API in a route handler to facilitate paging through
* saved objects on the client-side unless you are streaming all of the
* results back to the client at once. Because the returned generator is
* stateful, you cannot rely on subsequent http requests retrieving new
* pages from the same Kibana server in multi-instance deployments.
*
* This generator wraps calls to {@link SavedObjectsRepository.find} and
* iterates over multiple pages of results using `_pit` and `search_after`.
* This will open a new Point-In-Time (PIT), and continue paging until a
* set of results is received that's smaller than the designated `perPage`.
*
* Once you have retrieved all of the results you need, it is recommended
* to call `close()` to clean up the PIT and prevent Elasticsearch from
* consuming resources unnecessarily. This is only required if you are
* done iterating and have not yet paged through all of the results: the
* PIT will automatically be closed for you once you reach the last page
* of results, or if the underlying call to `find` fails for any reason.
*
* @example
* ```ts
* const findOptions: SavedObjectsCreatePointInTimeFinderOptions = {
* type: 'visualization',
* search: 'foo*',
* perPage: 100,
* };
*
* const finder = savedObjectsClient.createPointInTimeFinder(findOptions);
*
* const responses: SavedObjectFindResponse[] = [];
* for await (const response of finder.find()) {
* responses.push(...response);
* if (doneSearching) {
* await finder.close();
* }
* }
* ```
*/
createPointInTimeFinder<T = unknown, A = unknown>(
findOptions: SavedObjectsCreatePointInTimeFinderOptions,
dependencies?: SavedObjectsCreatePointInTimeFinderDependencies
): ISavedObjectsPointInTimeFinder<T, A>;
}

View file

@ -0,0 +1,18 @@
{
"extends": "../../../../tsconfig.bazel.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"outDir": "target_types",
"rootDir": "src",
"stripInternal": false,
"types": [
"jest",
"node"
]
},
"include": [
"src/**/*"
]
}

View file

@ -0,0 +1,106 @@
load("@npm//@bazel/typescript:index.bzl", "ts_config")
load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project")
PKG_DIRNAME = "core-saved-objects-common"
PKG_REQUIRE_NAME = "@kbn/core-saved-objects-common"
SOURCE_FILES = glob(
[
"src/**/*.ts",
"src/**/*.tsx",
],
exclude = [
"**/*.test.*",
"**/*.stories.*",
],
)
SRCS = SOURCE_FILES
filegroup(
name = "srcs",
srcs = SRCS,
)
NPM_MODULE_EXTRA_FILES = [
"package.json",
]
RUNTIME_DEPS = [
"@npm//react"
]
TYPES_DEPS = [
"@npm//@types/node",
"@npm//@types/jest"
]
jsts_transpiler(
name = "target_node",
srcs = SRCS,
build_pkg_name = package_name(),
)
jsts_transpiler(
name = "target_web",
srcs = SRCS,
build_pkg_name = package_name(),
web = True,
)
ts_config(
name = "tsconfig",
src = "tsconfig.json",
deps = [
"//:tsconfig.base.json",
"//:tsconfig.bazel.json",
],
)
ts_project(
name = "tsc_types",
args = ['--pretty'],
srcs = SRCS,
deps = TYPES_DEPS,
declaration = True,
declaration_map = True,
emit_declaration_only = True,
out_dir = "target_types",
root_dir = "src",
tsconfig = ":tsconfig",
)
js_library(
name = PKG_DIRNAME,
srcs = NPM_MODULE_EXTRA_FILES,
deps = RUNTIME_DEPS + [":target_node", ":target_web"],
package_name = PKG_REQUIRE_NAME,
visibility = ["//visibility:public"],
)
pkg_npm(
name = "npm_module",
deps = [":" + PKG_DIRNAME],
)
filegroup(
name = "build",
srcs = [":npm_module"],
visibility = ["//visibility:public"],
)
pkg_npm_types(
name = "npm_module_types",
srcs = SRCS,
deps = [":tsc_types"],
package_name = PKG_REQUIRE_NAME,
tsconfig = ":tsconfig",
visibility = ["//visibility:public"],
)
filegroup(
name = "build_types",
srcs = [":npm_module_types"],
visibility = ["//visibility:public"],
)

View file

@ -0,0 +1,3 @@
# @kbn/core-saved-objects-common
This package contains the common types shared between the browser and server-side savedObjects APIs.

View file

@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
module.exports = {
preset: '@kbn/test',
rootDir: '../../../..',
roots: ['<rootDir>/packages/core/saved-objects/core-saved-objects-common'],
};

View file

@ -0,0 +1,8 @@
{
"name": "@kbn/core-saved-objects-common",
"private": true,
"version": "1.0.0",
"main": "./target_node/index.js",
"browser": "./target_web/index.js",
"license": "SSPL-1.0 OR Elastic License 2.0"
}

View file

@ -0,0 +1,35 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export type {
SavedObject,
SavedObjectsNamespaceType,
SavedObjectAttributeSingle,
SavedObjectAttribute,
SavedObjectAttributes,
SavedObjectError,
SavedObjectReference,
SavedObjectsMigrationVersion,
} from './saved_objects';
export type {
SavedObjectsImportResponse,
SavedObjectsImportSuccess,
SavedObjectsImportFailure,
SavedObjectsImportRetry,
SavedObjectsImportWarning,
SavedObjectsImportSimpleWarning,
SavedObjectsImportAmbiguousConflictError,
SavedObjectsImportUnsupportedTypeError,
SavedObjectsImportMissingReferencesError,
SavedObjectsImportUnknownError,
SavedObjectsImportActionRequiredWarning,
SavedObjectsImportConflictError,
} from './saved_objects_imports';
export type { SavedObjectTypeIdTuple } from './types';

View file

@ -98,6 +98,20 @@ export interface SavedObject<T = unknown> {
originId?: string;
}
/**
* The namespace type dictates how a saved object can be interacted in relation to namespaces. Each type is mutually exclusive:
* * single (default): This type of saved object is namespace-isolated, e.g., it exists in only one namespace.
* * multiple: This type of saved object is shareable, e.g., it can exist in one or more namespaces.
* * multiple-isolated: This type of saved object is namespace-isolated, e.g., it exists in only one namespace, but object IDs must be
* unique across all namespaces. This is intended to be an intermediate step when objects with a "single" namespace type are being
* converted to a "multiple" namespace type. In other words, objects with a "multiple-isolated" namespace type will be *share-capable*,
* but will not actually be shareable until the namespace type is changed to "multiple".
* * agnostic: This type of saved object is global.
*
* @public
*/
export type SavedObjectsNamespaceType = 'single' | 'multiple' | 'multiple-isolated' | 'agnostic';
export interface SavedObjectError {
error: string;
message: string;

View file

@ -0,0 +1,181 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/**
* Describes a retry operation for importing a saved object.
* @public
*/
export interface SavedObjectsImportRetry {
type: string;
id: string;
overwrite: boolean;
/**
* The object ID that will be created or overwritten. If not specified, the `id` field will be used.
*/
destinationId?: string;
replaceReferences: Array<{
type: string;
from: string;
to: string;
}>;
/**
* If `createNewCopy` is specified, the new object has a new (undefined) origin ID. This is only needed for the case where
* `createNewCopies` mode is disabled and ambiguous source conflicts are detected.
*/
createNewCopy?: boolean;
/**
* If `ignoreMissingReferences` is specified, reference validation will be skipped for this object.
*/
ignoreMissingReferences?: boolean;
}
/**
* Represents a failure to import due to a conflict.
* @public
*/
export interface SavedObjectsImportConflictError {
type: 'conflict';
destinationId?: string;
}
/**
* Represents a failure to import due to a conflict, which can be resolved in different ways with an overwrite.
* @public
*/
export interface SavedObjectsImportAmbiguousConflictError {
type: 'ambiguous_conflict';
destinations: Array<{ id: string; title?: string; updatedAt?: string }>;
}
/**
* Represents a failure to import due to having an unsupported saved object type.
* @public
*/
export interface SavedObjectsImportUnsupportedTypeError {
type: 'unsupported_type';
}
/**
* Represents a failure to import due to an unknown reason.
* @public
*/
export interface SavedObjectsImportUnknownError {
type: 'unknown';
message: string;
statusCode: number;
}
/**
* Represents a failure to import due to missing references.
* @public
*/
export interface SavedObjectsImportMissingReferencesError {
type: 'missing_references';
references: Array<{ type: string; id: string }>;
}
/**
* Represents a failure to import.
* @public
*/
export interface SavedObjectsImportFailure {
id: string;
type: string;
meta: { title?: string; icon?: string };
/**
* If `overwrite` is specified, an attempt was made to overwrite an existing object.
*/
overwrite?: boolean;
error:
| SavedObjectsImportConflictError
| SavedObjectsImportAmbiguousConflictError
| SavedObjectsImportUnsupportedTypeError
| SavedObjectsImportMissingReferencesError
| SavedObjectsImportUnknownError;
}
/**
* Represents a successful import.
* @public
*/
export interface SavedObjectsImportSuccess {
id: string;
type: string;
/**
* If `destinationId` is specified, the new object has a new ID that is different from the import ID.
*/
destinationId?: string;
/**
* @deprecated Can be removed when https://github.com/elastic/kibana/issues/91615 is done.
* If `createNewCopy` is specified, the new object has a new (undefined) origin ID. This is only needed for the case where
* `createNewCopies` mode is disabled and ambiguous source conflicts are detected. When `createNewCopies` mode is permanently enabled,
* this field will be redundant and can be removed.
*/
createNewCopy?: boolean;
meta: {
title?: string;
icon?: string;
};
/**
* If `overwrite` is specified, this object overwrote an existing one (or will do so, in the case of a pending resolution).
*/
overwrite?: boolean;
}
/**
* A simple informative warning that will be displayed to the user.
*
* @public
*/
export interface SavedObjectsImportSimpleWarning {
type: 'simple';
/** The translated message to display to the user */
message: string;
}
/**
* A warning meant to notify that a specific user action is required to finalize the import
* of some type of object.
*
* @remark The `actionUrl` must be a path relative to the basePath, and not include it.
*
* @public
*/
export interface SavedObjectsImportActionRequiredWarning {
type: 'action_required';
/** The translated message to display to the user. */
message: string;
/** The path (without the basePath) that the user should be redirect to address this warning. */
actionPath: string;
/** An optional label to use for the link button. If unspecified, a default label will be used. */
buttonLabel?: string;
}
/**
* Composite type of all the possible types of import warnings.
*
* See {@link SavedObjectsImportSimpleWarning} and {@link SavedObjectsImportActionRequiredWarning}
* for more details.
*
* @public
*/
export type SavedObjectsImportWarning =
| SavedObjectsImportSimpleWarning
| SavedObjectsImportActionRequiredWarning;
/**
* The response describing the result of an import.
* @public
*/
export interface SavedObjectsImportResponse {
success: boolean;
successCount: number;
successResults?: SavedObjectsImportSuccess[];
warnings: SavedObjectsImportWarning[];
errors?: SavedObjectsImportFailure[];
}

View file

@ -0,0 +1,19 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/**
* An identifier for a saved object within a space.
*
* @public
*/
export interface SavedObjectTypeIdTuple {
/** The id of the saved object */
id: string;
/** The type of the saved object */
type: string;
}

View file

@ -0,0 +1,18 @@
{
"extends": "../../../../tsconfig.bazel.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"outDir": "target_types",
"rootDir": "src",
"stripInternal": false,
"types": [
"jest",
"node"
]
},
"include": [
"src/**/*"
]
}

View file

@ -128,31 +128,33 @@ export type {
NavigateToUrlOptions,
} from './application';
export { SimpleSavedObject } from './saved_objects';
export type { ResolvedSimpleSavedObject } from './saved_objects';
export { SimpleSavedObjectImpl } from './saved_objects';
export type {
SavedObjectsBatchResponse,
SavedObjectsBulkCreateObject,
SavedObjectsBulkCreateOptions,
SavedObjectsBulkResolveObject,
SavedObjectsBulkResolveResponse,
SavedObjectsBulkUpdateObject,
SavedObjectsBulkUpdateOptions,
SavedObjectsClientContract,
SimpleSavedObject,
SavedObjectsCreateOptions,
SavedObjectsFindResponsePublic,
SavedObjectsResolveResponse,
SavedObjectsDeleteOptions,
SavedObjectsBatchResponse,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsUpdateOptions,
ResolvedSimpleSavedObject,
SavedObjectsBulkUpdateObject,
SavedObjectsFindResponse,
SavedObjectsBulkCreateOptions,
SavedObjectsBulkUpdateOptions,
SavedObjectsBulkResolveResponse,
SavedObjectsBulkCreateObject,
} from '@kbn/core-saved-objects-api-browser';
export type {
SavedObject,
SavedObjectTypeIdTuple,
SavedObjectAttribute,
SavedObjectAttributes,
SavedObjectAttributeSingle,
SavedObjectError,
SavedObjectReference,
SavedObjectsBaseOptions,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsMigrationVersion,
SavedObjectsClientContract,
SavedObjectsImportResponse,
SavedObjectsImportSuccess,
SavedObjectsImportConflictError,
@ -166,9 +168,7 @@ export type {
SavedObjectsImportSimpleWarning,
SavedObjectsImportActionRequiredWarning,
SavedObjectsImportWarning,
SavedObjectReferenceWithContext,
SavedObjectsCollectMultiNamespaceReferencesResponse,
} from './saved_objects';
} from '@kbn/core-saved-objects-common';
export type {
HttpHeadersInit,

View file

@ -5,53 +5,8 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export { SavedObjectsService } from './saved_objects_service';
export type {
SavedObjectsBatchResponse,
SavedObjectsBulkCreateObject,
SavedObjectsBulkCreateOptions,
SavedObjectsBulkUpdateObject,
SavedObjectsClient,
SavedObjectsClientContract,
SavedObjectsCreateOptions,
SavedObjectsFindResponsePublic,
SavedObjectsUpdateOptions,
SavedObjectsBulkUpdateOptions,
SavedObjectsBulkResolveResponse,
} from './saved_objects_client';
export { SimpleSavedObject } from './simple_saved_object';
export type { ResolvedSimpleSavedObject } from './types';
export type { SavedObjectsClient } from './saved_objects_client';
export { SimpleSavedObjectImpl } from './simple_saved_object';
export type { SavedObjectsStart } from './saved_objects_service';
export type {
SavedObjectsBaseOptions,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsMigrationVersion,
SavedObjectsImportResponse,
SavedObjectsImportSuccess,
SavedObjectsImportConflictError,
SavedObjectsImportAmbiguousConflictError,
SavedObjectsImportUnsupportedTypeError,
SavedObjectsImportMissingReferencesError,
SavedObjectsImportUnknownError,
SavedObjectsImportFailure,
SavedObjectsImportRetry,
SavedObjectsNamespaceType,
SavedObjectsImportSimpleWarning,
SavedObjectsImportActionRequiredWarning,
SavedObjectsImportWarning,
SavedObjectReferenceWithContext,
SavedObjectsCollectMultiNamespaceReferencesResponse,
SavedObjectsBulkResolveObject,
SavedObjectsResolveResponse,
} from '../../server';
export type {
SavedObject,
SavedObjectAttribute,
SavedObjectAttributes,
SavedObjectAttributeSingle,
SavedObjectError,
SavedObjectReference,
} from '../../types';

View file

@ -8,7 +8,7 @@
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
import { SavedObjectsClient } from './saved_objects_client';
import { SimpleSavedObject } from './simple_saved_object';
import { SimpleSavedObjectImpl as SimpleSavedObject } from './simple_saved_object';
describe('SavedObjectsClient', () => {
const doc = {

View file

@ -8,113 +8,33 @@
import { pick, throttle, cloneDeep } from 'lodash';
import type { HttpSetup, HttpFetchOptions } from '@kbn/core-http-browser';
import type { SavedObject, SavedObjectTypeIdTuple } from '@kbn/core-saved-objects-common';
import type {
SavedObject,
SavedObjectReference,
SavedObjectsBulkResolveResponse as SavedObjectsBulkResolveResponseServer,
SavedObjectsClientContract as SavedObjectsApi,
SavedObjectsFindOptions as SavedObjectFindOptionsServer,
SavedObjectsMigrationVersion,
SavedObjectsFindResponse as SavedObjectsFindResponseServer,
SavedObjectsResolveResponse,
} from '../../server';
} from '@kbn/core-saved-objects-api-server';
import type {
SavedObjectsClientContract,
SavedObjectsCreateOptions,
SavedObjectsDeleteOptions,
SavedObjectsBatchResponse,
SavedObjectsFindOptions,
SavedObjectsUpdateOptions,
ResolvedSimpleSavedObject,
SavedObjectsBulkUpdateObject,
SavedObjectsFindResponse,
SavedObjectsBulkCreateOptions,
SavedObjectsBulkCreateObject,
SimpleSavedObject,
} from '@kbn/core-saved-objects-api-browser';
import { SimpleSavedObject } from './simple_saved_object';
import type { ResolvedSimpleSavedObject } from './types';
import { SimpleSavedObjectImpl } from './simple_saved_object';
type PromiseType<T extends Promise<any>> = T extends Promise<infer U> ? U : never;
type SavedObjectsFindOptions = Omit<
SavedObjectFindOptionsServer,
'pit' | 'rootSearchFields' | 'searchAfter' | 'sortOrder' | 'typeToNamespacesMap'
>;
type SavedObjectsFindResponse = Omit<PromiseType<ReturnType<SavedObjectsApi['find']>>, 'pit_id'>;
/** @public */
export interface SavedObjectsCreateOptions {
/**
* (Not recommended) Specify an id instead of having the saved objects service generate one for you.
*/
id?: string;
/** If a document with the given `id` already exists, overwrite it's contents (default=false). */
overwrite?: boolean;
/** {@inheritDoc SavedObjectsMigrationVersion} */
migrationVersion?: SavedObjectsMigrationVersion;
/** A semver value that is used when upgrading objects between Kibana versions. */
coreMigrationVersion?: string;
references?: SavedObjectReference[];
}
/**
* @param type - Create a SavedObject of the given type
* @param attributes - Create a SavedObject with the given attributes
*
* @public
*/
export interface SavedObjectsBulkCreateObject<T = unknown> extends SavedObjectsCreateOptions {
type: string;
attributes: T;
}
/** @public */
export interface SavedObjectsBulkCreateOptions {
/** If a document with the given `id` already exists, overwrite it's contents (default=false). */
overwrite?: boolean;
}
/** @public */
export interface SavedObjectsBulkUpdateObject<T = unknown> {
type: string;
id: string;
attributes: T;
version?: string;
references?: SavedObjectReference[];
}
/** @public */
export interface SavedObjectsBulkUpdateOptions {
namespace?: string;
}
/** @public */
export interface SavedObjectsUpdateOptions<Attributes = unknown> {
version?: string;
upsert?: Attributes;
references?: SavedObjectReference[];
}
/** @public */
export interface SavedObjectsBatchResponse<T = unknown> {
savedObjects: Array<SimpleSavedObject<T>>;
}
/** @public */
export interface SavedObjectsDeleteOptions {
/** Force deletion of an object that exists in multiple namespaces */
force?: boolean;
}
/** @public */
export interface SavedObjectsBulkResolveResponse<T = unknown> {
resolved_objects: Array<ResolvedSimpleSavedObject<T>>;
}
/**
* Return type of the Saved Objects `find()` method.
*
* *Note*: this type is different between the Public and Server Saved Objects
* clients.
*
* @public
*/
export interface SavedObjectsFindResponsePublic<T = unknown, A = unknown>
extends SavedObjectsBatchResponse<T> {
aggregations?: A;
total: number;
perPage: number;
page: number;
}
type SavedObjectsFindResponseInternal = Omit<SavedObjectsFindResponseServer, 'pit_id'>;
interface BatchGetQueueEntry {
type: string;
@ -144,149 +64,8 @@ const BATCH_INTERVAL = 100;
const API_BASE_URL = '/api/saved_objects/';
/**
* The client-side SavedObjectsClient is a thin convenience library around the SavedObjects
* HTTP API for interacting with Saved Objects.
*
* @public
*/
export interface SavedObjectsClientContract {
/**
* Persists an object
*/
create<T = unknown>(
type: string,
attributes: T,
options?: SavedObjectsCreateOptions
): Promise<SimpleSavedObject<T>>;
/**
* Creates multiple documents at once
* @returns The result of the create operation containing created saved objects.
*/
bulkCreate(
objects: SavedObjectsBulkCreateObject[],
options?: SavedObjectsBulkCreateOptions
): Promise<SavedObjectsBatchResponse<unknown>>;
/**
* Deletes an object
*/
delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>;
/**
* Search for objects
*
* @param {object} [options={}]
* @property {string} options.type
* @property {string} options.search
* @property {string} options.searchFields - see Elasticsearch Simple Query String
* Query field argument for more information
* @property {integer} [options.page=1]
* @property {integer} [options.perPage=20]
* @property {array} options.fields
* @property {object} [options.hasReference] - { type, id }
* @returns A find result with objects matching the specified search.
*/
find<T = unknown, A = unknown>(
options: SavedObjectsFindOptions
): Promise<SavedObjectsFindResponsePublic<T>>;
/**
* Fetches a single object
*
* @param {string} type
* @param {string} id
* @returns The saved object for the given type and id.
*/
get<T = unknown>(type: string, id: string): Promise<SimpleSavedObject<T>>;
/**
* Returns an array of objects by id
*
* @param {array} objects - an array ids, or an array of objects containing id and optionally type
* @returns The saved objects with the given type and ids requested
* @example
*
* bulkGet([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*/
bulkGet(
objects: Array<{ id: string; type: string }>
): Promise<SavedObjectsBatchResponse<unknown>>;
/**
* Resolves a single object
*
* @param {string} type
* @param {string} id
* @returns The resolve result for the saved object for the given type and id.
*
* @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the
* outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior for the `resolve`
* API is unique to the public client, which batches individual calls with `bulkResolve` under the hood. We don't throw an error in that
* case for legacy compatibility reasons.
*/
resolve<T = unknown>(type: string, id: string): Promise<ResolvedSimpleSavedObject<T>>;
/**
* Resolves an array of objects by id, using any legacy URL aliases if they exist
*
* @param objects - an array of objects containing id, type
* @returns The bulk resolve result for the saved objects for the given types and ids.
* @example
*
* bulkResolve([
* { id: 'one', type: 'config' },
* { id: 'foo', type: 'index-pattern' }
* ])
*
* @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the
* outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. The `resolve` method in the
* public client uses `bulkResolve` under the hood, so it behaves the same way.
*/
bulkResolve<T = unknown>(
objects: Array<{ id: string; type: string }>
): Promise<SavedObjectsBulkResolveResponse<T>>;
/**
* Updates an object
*
* @param {string} type
* @param {string} id
* @param {object} attributes
* @param {object} options
* @prop {integer} options.version - ensures version matches that of persisted object
* @prop {object} options.migrationVersion - The optional migrationVersion of this document
* @returns
*/
update<T = unknown>(
type: string,
id: string,
attributes: T,
options?: SavedObjectsUpdateOptions
): Promise<SimpleSavedObject<T>>;
/**
* Update multiple documents at once
*
* @param {array} objects - [{ type, id, attributes, options: { version, references } }]
* @returns The result of the update operation containing both failed and updated saved objects.
*/
bulkUpdate<T = unknown>(
objects: SavedObjectsBulkUpdateObject[]
): Promise<SavedObjectsBatchResponse<T>>;
}
interface ObjectTypeAndId {
id: string;
type: string;
}
const getObjectsToFetch = (queue: BatchGetQueueEntry[]): ObjectTypeAndId[] => {
const objects: ObjectTypeAndId[] = [];
const getObjectsToFetch = (queue: BatchGetQueueEntry[]): SavedObjectTypeIdTuple[] => {
const objects: SavedObjectTypeIdTuple[] = [];
const inserted = new Set<string>();
queue.forEach(({ id, type }) => {
if (!inserted.has(`${type}|${id}`)) {
@ -299,7 +78,7 @@ const getObjectsToFetch = (queue: BatchGetQueueEntry[]): ObjectTypeAndId[] => {
const getObjectsToResolve = (queue: BatchResolveQueueEntry[]) => {
const responseIndices: number[] = [];
const objectsToResolve: ObjectTypeAndId[] = [];
const objectsToResolve: SavedObjectTypeIdTuple[] = [];
const inserted = new Map<string, number>();
queue.forEach(({ id, type }) => {
const key = `${type}|${id}`;
@ -478,7 +257,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract {
public find = <T = unknown, A = unknown>(
options: SavedObjectsFindOptions
): Promise<SavedObjectsFindResponsePublic<T>> => {
): Promise<SavedObjectsFindResponse<T>> => {
const path = this.getPath(['_find']);
const renameMap = {
defaultSearchOperator: 'default_search_operator',
@ -520,7 +299,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract {
query,
});
return request.then((resp) => {
return renameKeys<SavedObjectsFindResponse, SavedObjectsFindResponsePublic>(
return renameKeys<SavedObjectsFindResponseInternal, SavedObjectsFindResponse>(
{
aggregations: 'aggregations',
saved_objects: 'savedObjects',
@ -532,7 +311,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract {
...resp,
saved_objects: resp.saved_objects.map((d) => this.createSavedObject(d)),
}
) as SavedObjectsFindResponsePublic<T>;
) as SavedObjectsFindResponse<T>;
});
};
@ -558,7 +337,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract {
});
};
private async performBulkGet(objects: ObjectTypeAndId[]) {
private async performBulkGet(objects: SavedObjectTypeIdTuple[]) {
const path = this.getPath(['_bulk_get']);
const request: ReturnType<SavedObjectsApi['bulkGet']> = this.savedObjectsFetch(path, {
method: 'POST',
@ -591,7 +370,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract {
};
};
private async performBulkResolve<T>(objects: ObjectTypeAndId[]) {
private async performBulkResolve<T>(objects: SavedObjectTypeIdTuple[]) {
const path = this.getPath(['_bulk_resolve']);
const request: Promise<SavedObjectsBulkResolveResponseServer<T>> = this.savedObjectsFetch(
path,
@ -645,13 +424,13 @@ export class SavedObjectsClient implements SavedObjectsClientContract {
}
private createSavedObject<T = unknown>(options: SavedObject<T>): SimpleSavedObject<T> {
return new SimpleSavedObject(this, options);
return new SimpleSavedObjectImpl(this, options);
}
private createResolvedSavedObject<T = unknown>(
resolveResponse: SavedObjectsResolveResponse<T>
): ResolvedSimpleSavedObject<T> {
const simpleSavedObject = new SimpleSavedObject<T>(this, resolveResponse.saved_object);
const simpleSavedObject = new SimpleSavedObjectImpl<T>(this, resolveResponse.saved_object);
return {
saved_object: simpleSavedObject,
outcome: resolveResponse.outcome,

View file

@ -8,7 +8,8 @@
import type { CoreService } from '@kbn/core-base-browser-internal';
import type { HttpStart } from '@kbn/core-http-browser';
import { SavedObjectsClient, type SavedObjectsClientContract } from './saved_objects_client';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-browser';
import { SavedObjectsClient } from './saved_objects_client';
/**
* @public
@ -20,8 +21,10 @@ export interface SavedObjectsStart {
export class SavedObjectsService implements CoreService<void, SavedObjectsStart> {
public async setup() {}
public async start({ http }: { http: HttpStart }): Promise<SavedObjectsStart> {
return { client: new SavedObjectsClient(http) };
}
public async stop() {}
}

View file

@ -6,11 +6,11 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../server';
import { SimpleSavedObject } from './simple_saved_object';
import { SavedObjectsClientContract } from './saved_objects_client';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-browser';
import { SimpleSavedObjectImpl as SimpleSavedObject } from './simple_saved_object';
describe('SimpleSavedObject', () => {
describe('SimpleSavedObjectImpl', () => {
let client: SavedObjectsClientContract;
beforeEach(() => {

View file

@ -8,21 +8,19 @@
import { set } from '@elastic/safer-lodash-set';
import { get, has } from 'lodash';
import { SavedObject as SavedObjectType } from '../../server';
import { SavedObjectsClientContract } from './saved_objects_client';
import type { SavedObject as SavedObjectType } from '@kbn/core-saved-objects-common';
import type {
SavedObjectsClientContract,
SimpleSavedObject,
} from '@kbn/core-saved-objects-api-browser';
/**
* This class is a very simple wrapper for SavedObjects loaded from the server
* with the {@link SavedObjectsClientContract}.
* Core internal implementation of {@link SimpleSavedObject}
*
* It provides basic functionality for creating/saving/deleting saved objects,
* but doesn't include any type-specific implementations.
*
* @public
* @internal Should use the {@link SimpleSavedObject} interface instead
*/
export class SimpleSavedObject<T = unknown> {
export class SimpleSavedObjectImpl<T = unknown> implements SimpleSavedObject<T> {
public attributes: T;
// We want to use the same interface this class had in JS
public _version?: SavedObjectType<T>['version'];
public id: SavedObjectType<T>['id'];
public type: SavedObjectType<T>['type'];
@ -31,10 +29,6 @@ export class SimpleSavedObject<T = unknown> {
public error: SavedObjectType<T>['error'];
public references: SavedObjectType<T>['references'];
public updatedAt: SavedObjectType<T>['updated_at'];
/**
* Space(s) that this saved object exists in. This attribute is not used for "global" saved object types which are registered with
* `namespaceType: 'agnostic'`.
*/
public namespaces: SavedObjectType<T>['namespaces'];
constructor(

View file

@ -283,6 +283,27 @@ export {
mergeSavedObjectMigrationMaps,
} from './saved_objects';
export type {
SavedObject,
SavedObjectAttribute,
SavedObjectAttributes,
SavedObjectAttributeSingle,
SavedObjectReference,
SavedObjectsMigrationVersion,
SavedObjectsImportConflictError,
SavedObjectsImportAmbiguousConflictError,
SavedObjectsImportFailure,
SavedObjectsImportMissingReferencesError,
SavedObjectsImportResponse,
SavedObjectsImportRetry,
SavedObjectsImportSuccess,
SavedObjectsImportUnknownError,
SavedObjectsImportUnsupportedTypeError,
SavedObjectsNamespaceType,
SavedObjectsImportSimpleWarning,
SavedObjectsImportActionRequiredWarning,
SavedObjectsImportWarning,
} from '@kbn/core-saved-objects-common';
export type {
SavedObjectsBulkCreateObject,
SavedObjectsBulkGetObject,
@ -292,42 +313,16 @@ export type {
SavedObjectsBulkUpdateResponse,
SavedObjectsCheckConflictsObject,
SavedObjectsCheckConflictsResponse,
SavedObjectsClientProviderOptions,
SavedObjectsClientWrapperFactory,
SavedObjectsClientWrapperOptions,
SavedObjectsClientFactory,
SavedObjectsClientFactoryProvider,
SavedObjectsClosePointInTimeOptions,
SavedObjectsClosePointInTimeResponse,
ISavedObjectsPointInTimeFinder,
SavedObjectsCreatePointInTimeFinderDependencies,
SavedObjectsCreatePointInTimeFinderOptions,
SavedObjectsCreateOptions,
SavedObjectTypeExcludeFromUpgradeFilterHook,
SavedObjectsExportResultDetails,
SavedObjectsExportExcludedObject,
SavedObjectsFindResult,
SavedObjectsFindResponse,
SavedObjectsImportConflictError,
SavedObjectsImportAmbiguousConflictError,
SavedObjectsImportFailure,
SavedObjectsImportMissingReferencesError,
SavedObjectsImportOptions,
SavedObjectsImportResponse,
SavedObjectsImportRetry,
SavedObjectsImportSuccess,
SavedObjectsImportUnknownError,
SavedObjectsImportUnsupportedTypeError,
SavedObjectMigrationContext,
SavedObjectsMigrationLogger,
SavedObjectsOpenPointInTimeOptions,
SavedObjectsOpenPointInTimeResponse,
SavedObjectsRawDoc,
SavedObjectsRawDocParseOptions,
SavedObjectSanitizedDoc,
SavedObjectUnsanitizedDoc,
SavedObjectsRepositoryFactory,
SavedObjectsResolveImportErrorsOptions,
SavedObjectsBulkResolveObject,
SavedObjectsBulkResolveResponse,
SavedObjectsResolveResponse,
@ -343,20 +338,44 @@ export type {
SavedObjectsUpdateObjectsSpacesOptions,
SavedObjectsUpdateObjectsSpacesResponse,
SavedObjectsUpdateObjectsSpacesResponseObject,
SavedObjectsServiceStart,
SavedObjectsServiceSetup,
SavedObjectStatusMeta,
SavedObjectsDeleteOptions,
ISavedObjectsRepository,
SavedObjectsRepository,
SavedObjectsDeleteByNamespaceOptions,
SavedObjectsIncrementCounterOptions,
SavedObjectsIncrementCounterField,
SavedObjectsBaseOptions,
MutatingOperationRefreshSetting,
SavedObjectsClientContract,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsPitParams,
} from '@kbn/core-saved-objects-api-server';
export type {
SavedObjectsClientProviderOptions,
SavedObjectsClientWrapperFactory,
SavedObjectsClientWrapperOptions,
SavedObjectsClientFactory,
SavedObjectsClientFactoryProvider,
SavedObjectTypeExcludeFromUpgradeFilterHook,
SavedObjectsExportResultDetails,
SavedObjectsExportExcludedObject,
SavedObjectsImportOptions,
SavedObjectMigrationContext,
SavedObjectsMigrationLogger,
SavedObjectsRawDoc,
SavedObjectsRawDocParseOptions,
SavedObjectSanitizedDoc,
SavedObjectUnsanitizedDoc,
SavedObjectsRepositoryFactory,
SavedObjectsResolveImportErrorsOptions,
SavedObjectsServiceStart,
SavedObjectsServiceSetup,
SavedObjectStatusMeta,
SavedObjectsRepository,
SavedObjectsFieldMapping,
SavedObjectsTypeMappingDefinition,
SavedObjectsMappingProperties,
ISavedObjectTypeRegistry,
SavedObjectsNamespaceType,
SavedObjectsType,
SavedObjectsTypeManagementDefinition,
SavedObjectMigrationMap,
@ -374,9 +393,6 @@ export type {
SavedObjectsImportError,
SavedObjectsImportHook,
SavedObjectsImportHookResult,
SavedObjectsImportSimpleWarning,
SavedObjectsImportActionRequiredWarning,
SavedObjectsImportWarning,
SavedObjectsValidationMap,
SavedObjectsValidationSpec,
SavedObjectsRequestHandlerContext,
@ -418,21 +434,6 @@ export type { DeprecationsDetails } from '@kbn/core-deprecations-common';
export type { AppCategory } from '../types';
export { DEFAULT_APP_CATEGORIES, APP_WRAPPER_CLASS } from '../utils';
export type {
SavedObject,
SavedObjectAttribute,
SavedObjectAttributes,
SavedObjectAttributeSingle,
SavedObjectReference,
SavedObjectsBaseOptions,
MutatingOperationRefreshSetting,
SavedObjectsClientContract,
SavedObjectsFindOptions,
SavedObjectsFindOptionsReference,
SavedObjectsPitParams,
SavedObjectsMigrationVersion,
} from './types';
export { ServiceStatusLevels } from './status';
export type { CoreStatus, ServiceStatus, ServiceStatusLevel, StatusServiceSetup } from './status';

View file

@ -9,8 +9,8 @@
import Hapi from '@hapi/hapi';
import h2o2 from '@hapi/h2o2';
import { URL } from 'url';
import { ISavedObjectsRepository } from '../../../../saved_objects/service/lib/repository';
import { SavedObject } from '../../../../saved_objects/types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server';
import { InternalCoreSetup, InternalCoreStart } from '../../../../internal_types';
import { Root } from '../../../../root';
import * as kbnTestServer from '../../../../../test_helpers/kbn_server';

View file

@ -12,8 +12,8 @@ import Util from 'util';
import { Env } from '@kbn/config';
import { schema } from '@kbn/config-schema';
import { REPO_ROOT } from '@kbn/utils';
import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server';
import { SavedObjectsType } from '../../../saved_objects/types';
import { ISavedObjectsRepository } from '../../../saved_objects/service/lib';
import { getEnvOptions } from '@kbn/config-mocks';
import { InternalCoreSetup, InternalCoreStart } from '../../../internal_types';
import { Root } from '../../../root';

View file

@ -8,7 +8,7 @@
import { CoreKibanaRequest } from '@kbn/core-http-router-server-internal';
import { httpServerMock } from '@kbn/core-http-server-mocks';
import { SavedObject } from '../../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import { applyExportTransforms } from './apply_export_transforms';
import { SavedObjectsExportTransform } from './types';

View file

@ -7,7 +7,7 @@
*/
import type { KibanaRequest } from '@kbn/core-http-server';
import { SavedObject } from '../../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import { SavedObjectsExportError } from './errors';
import { SavedObjectsExportTransform, SavedObjectsExportTransformContext } from './types';
import { getObjKey, SavedObjectComparator } from './utils';

View file

@ -7,10 +7,10 @@
*/
import { httpServerMock } from '@kbn/core-http-server-mocks';
import type { SavedObject, SavedObjectError } from '@kbn/core-saved-objects-common';
import { applyExportTransformsMock } from './collect_exported_objects.test.mocks';
import { savedObjectsClientMock } from '../../mocks';
import { loggerMock } from '@kbn/logging-mocks';
import { SavedObject, SavedObjectError } from '../../../types';
import { SavedObjectTypeRegistry } from '../saved_objects_type_registry';
import type { SavedObjectsExportTransform } from './types';
import { collectExportedObjects, ExclusionReason } from './collect_exported_objects';

View file

@ -8,8 +8,9 @@
import type { Logger } from '@kbn/logging';
import type { KibanaRequest } from '@kbn/core-http-server';
import type { SavedObject } from '../../../types';
import { SavedObjectsClientContract, SavedObjectsExportablePredicate } from '../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { SavedObjectsExportablePredicate } from '../types';
import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry';
import type { SavedObjectsExportTransform } from './types';
import { applyExportTransforms } from './apply_export_transforms';

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
/**
* @public

View file

@ -7,7 +7,7 @@
*/
import { httpServerMock } from '@kbn/core-http-server-mocks';
import type { SavedObject } from '../../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import { SavedObjectsExporter } from './saved_objects_exporter';
import { savedObjectsClientMock } from '../service/saved_objects_client.mock';
import { SavedObjectTypeRegistry } from '../saved_objects_type_registry';

View file

@ -9,8 +9,11 @@
import type { Readable } from 'stream';
import { createListStream } from '@kbn/utils';
import type { Logger } from '@kbn/logging';
import { SavedObject, SavedObjectsClientContract } from '../types';
import { SavedObjectsFindResult } from '../service';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type {
SavedObjectsClientContract,
SavedObjectsFindResult,
} from '@kbn/core-saved-objects-api-server';
import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry';
import { sortObjects } from './sort_objects';
import {

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
export function sortObjects(savedObjects: SavedObject[]): SavedObject[] {
const path = new Set<SavedObject>();

View file

@ -7,7 +7,8 @@
*/
import type { KibanaRequest } from '@kbn/core-http-server';
import { SavedObject, SavedObjectsFindOptionsReference } from '../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type { SavedObjectsFindOptionsReference } from '@kbn/core-saved-objects-api-server';
/** @public */
export interface SavedObjectExportBaseOptions {

View file

@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
import type { SavedObject } from '@kbn/core-saved-objects-common';
import { byIdAscComparator, getPreservedOrderComparator } from './utils';
import { SavedObject } from '../../../types';
const createObj = (id: string): SavedObject => ({
id,

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
export type SavedObjectComparator = (a: SavedObject, b: SavedObject) => number;

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
/**
* @public

View file

@ -19,17 +19,17 @@ import {
import { Readable } from 'stream';
import { v4 as uuidv4 } from 'uuid';
import {
SavedObjectsClientContract,
SavedObjectsType,
import type {
SavedObject,
SavedObjectsImportFailure,
} from '../types';
SavedObjectsImportWarning,
} from '@kbn/core-saved-objects-common';
import { SavedObjectsClientContract, SavedObjectsType } from '../types';
import { savedObjectsClientMock } from '../../mocks';
import { ISavedObjectTypeRegistry } from '..';
import { typeRegistryMock } from '../saved_objects_type_registry.mock';
import { importSavedObjectsFromStream, ImportSavedObjectsOptions } from './import_saved_objects';
import { SavedObjectsImportHook, SavedObjectsImportWarning } from './types';
import { SavedObjectsImportHook } from './types';
import type { ImportStateMap } from './lib';
describe('#importSavedObjectsFromStream', () => {

View file

@ -7,13 +7,13 @@
*/
import { Readable } from 'stream';
import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry';
import { SavedObjectsClientContract } from '../types';
import {
import type {
SavedObjectsImportFailure,
SavedObjectsImportResponse,
SavedObjectsImportHook,
} from './types';
} from '@kbn/core-saved-objects-common';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry';
import { SavedObjectsImportHook } from './types';
import {
checkReferenceOrigins,
validateReferences,

View file

@ -9,21 +9,9 @@
export { SavedObjectsImporter } from './saved_objects_importer';
export type { ISavedObjectsImporter } from './saved_objects_importer';
export type {
SavedObjectsImportResponse,
SavedObjectsImportSuccess,
SavedObjectsImportFailure,
SavedObjectsImportOptions,
SavedObjectsImportConflictError,
SavedObjectsImportAmbiguousConflictError,
SavedObjectsImportMissingReferencesError,
SavedObjectsImportUnknownError,
SavedObjectsImportUnsupportedTypeError,
SavedObjectsResolveImportErrorsOptions,
SavedObjectsImportRetry,
SavedObjectsImportHook,
SavedObjectsImportHookResult,
SavedObjectsImportSimpleWarning,
SavedObjectsImportActionRequiredWarning,
SavedObjectsImportWarning,
} from './types';
export { SavedObjectsImportError } from './errors';

View file

@ -7,8 +7,12 @@
*/
import { savedObjectsClientMock } from '../../../mocks';
import { SavedObjectReference, SavedObjectsImportRetry } from '../../../../public';
import { SavedObjectsClientContract, SavedObject } from '../../types';
import type {
SavedObject,
SavedObjectReference,
SavedObjectsImportRetry,
} from '@kbn/core-saved-objects-common';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { SavedObjectsErrorHelpers } from '../../service';
import { checkConflicts } from './check_conflicts';

View file

@ -7,13 +7,13 @@
*/
import { v4 as uuidv4 } from 'uuid';
import {
import type {
SavedObject,
SavedObjectsClientContract,
SavedObjectsImportFailure,
SavedObjectError,
SavedObjectsImportRetry,
} from '../../types';
} from '@kbn/core-saved-objects-common';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import type { ImportStateMap } from './types';
interface CheckConflictsParams {

View file

@ -8,13 +8,13 @@
import { mockCreateOriginQuery } from './check_reference_origins.test.mock';
import {
SavedObjectsClientContract,
import type {
SavedObjectReference,
SavedObject,
SavedObjectsImportFailure,
SavedObjectsImportRetry,
} from '../../types';
} from '@kbn/core-saved-objects-common';
import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { checkOriginConflicts } from './check_origin_conflicts';
import { savedObjectsClientMock } from '../../../mocks';
import { typeRegistryMock } from '../../saved_objects_type_registry.mock';

View file

@ -10,10 +10,10 @@ import pMap from 'p-map';
import { v4 as uuidv4 } from 'uuid';
import type {
SavedObject,
SavedObjectsClientContract,
SavedObjectsImportFailure,
SavedObjectsImportRetry,
} from '../../types';
} from '@kbn/core-saved-objects-common';
import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry';
import { getObjectKey } from '../../service/lib/internal_utils';
import type { ImportStateMap } from './types';
@ -44,14 +44,17 @@ interface InexactMatch<T> {
object: SavedObject<T>;
destinations: Array<{ id: string; title?: string; updatedAt?: string }>;
}
interface Left<T> {
tag: 'left';
value: InexactMatch<T>;
}
interface Right<T> {
tag: 'right';
value: SavedObject<T>;
}
type Either<T> = Left<T> | Right<T>;
const isLeft = <T>(object: Either<T>): object is Left<T> => object.tag === 'left';

View file

@ -8,7 +8,7 @@
import { mockCreateOriginQuery } from './check_reference_origins.test.mock';
import type { SavedObjectsFindResult } from '../../service';
import type { SavedObjectsFindResult } from '@kbn/core-saved-objects-api-server';
import type { SavedObjectsClientContract } from '../../types';
import { checkReferenceOrigins, CheckReferenceOriginsParams } from './check_reference_origins';
import { savedObjectsClientMock } from '../../../mocks';

View file

@ -14,8 +14,7 @@ import {
createPromiseFromStreams,
} from '@kbn/utils';
import { SavedObject } from '../../types';
import { SavedObjectsImportFailure } from '../types';
import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common';
import { SavedObjectsImportError } from '../errors';
import { getNonUniqueEntries } from './get_non_unique_entries';
import { createLimitStream } from './create_limit_stream';

View file

@ -6,8 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../types';
import { SavedObjectsImportRetry } from '../types';
import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common';
export function createObjectsFilter(retries: SavedObjectsImportRetry[]) {
const retryKeys = new Set<string>(retries.map((retry) => `${retry.type}:${retry.id}`));

View file

@ -7,8 +7,9 @@
*/
import { savedObjectsClientMock } from '../../../mocks';
import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common';
import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { createSavedObjects } from './create_saved_objects';
import { SavedObjectsClientContract, SavedObject, SavedObjectsImportFailure } from '../../types';
import { SavedObjectsErrorHelpers } from '../../service';
import { extractErrors } from './extract_errors';

View file

@ -6,7 +6,8 @@
* Side Public License, v 1.
*/
import { SavedObject, SavedObjectsClientContract, SavedObjectsImportFailure } from '../../types';
import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common';
import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { extractErrors } from './extract_errors';
import { CreatedObject } from '../types';
import type { ImportStateMap } from './types';
@ -20,6 +21,7 @@ export interface CreateSavedObjectsParams<T> {
overwrite?: boolean;
refresh?: boolean | 'wait_for';
}
export interface CreateSavedObjectsResult<T> {
createdObjects: Array<CreatedObject<T>>;
errors: SavedObjectsImportFailure[];

View file

@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../types';
import { SavedObjectsImportHookResult, SavedObjectsImportWarning } from '../types';
import type { SavedObject, SavedObjectsImportWarning } from '@kbn/core-saved-objects-common';
import { SavedObjectsImportHookResult } from '../types';
import { executeImportHooks } from './execute_import_hooks';
const createObject = (type: string, id: string): SavedObject => ({

View file

@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../types';
import { SavedObjectsImportHook, SavedObjectsImportWarning } from '../types';
import type { SavedObject, SavedObjectsImportWarning } from '@kbn/core-saved-objects-common';
import { SavedObjectsImportHook } from '../types';
export interface ExecuteImportHooksOptions {
objects: SavedObject[];

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import { extractErrors } from './extract_errors';
import { SavedObjectsErrorHelpers } from '../../service';
import { CreatedObject } from '../types';

View file

@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../types';
import { SavedObjectsImportFailure, CreatedObject } from '../types';
import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common';
import { CreatedObject } from '../types';
export function extractErrors(
// TODO: define saved object type

View file

@ -6,8 +6,7 @@
* Side Public License, v 1.
*/
import type { SavedObject } from '../../types';
import type { SavedObjectsImportRetry } from '../types';
import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common';
import { getImportStateMapForRetries } from './get_import_state_map_for_retries';
describe('#getImportStateMapForRetries', () => {

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject, SavedObjectsImportRetry } from '../../types';
import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common';
import type { ImportStateMap } from './types';
interface GetImportStateMapForRetriesParams {

View file

@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
import type { SavedObject } from '@kbn/core-saved-objects-common';
import { regenerateIds } from './regenerate_ids';
import { SavedObject } from '../../types';
jest.mock('uuid', () => ({
v4: jest

View file

@ -7,7 +7,7 @@
*/
import { v4 as uuidv4 } from 'uuid';
import { SavedObject } from '../../types';
import type { SavedObject } from '@kbn/core-saved-objects-common';
import type { ImportStateMap } from './types';
/**

View file

@ -6,8 +6,7 @@
* Side Public License, v 1.
*/
import { SavedObject } from '../../types';
import { SavedObjectsImportRetry } from '../types';
import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common';
export function splitOverwrites<T>(
savedObjects: Array<SavedObject<T>>,

Some files were not shown because too many files have changed in this diff Show more