From f75b5654c9a23524a829cca61532a350247bb6cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Thu, 18 Dec 2025 11:20:48 +0100 Subject: [PATCH 01/10] Modal: Fix modal button row (#115483) * Modal: Fix modal button row * update * update --- packages/grafana-ui/src/components/Modal/getModalStyles.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/grafana-ui/src/components/Modal/getModalStyles.ts b/packages/grafana-ui/src/components/Modal/getModalStyles.ts index 3c124d24e68..f1e92cfa3f6 100644 --- a/packages/grafana-ui/src/components/Modal/getModalStyles.ts +++ b/packages/grafana-ui/src/components/Modal/getModalStyles.ts @@ -79,7 +79,7 @@ export const getModalStyles = (theme: GrafanaTheme2) => { modalContent: css({ overflow: 'auto', padding: theme.spacing(3, 3, 0, 3), - marginBottom: theme.spacing(3), + marginBottom: theme.spacing(2.5), scrollbarWidth: 'thin', width: '100%', From 2123099e882c7cff6f914ce81ab089fa7e1e56ac Mon Sep 17 00:00:00 2001 From: Gonzalo Trigueros Manzanas <242162051+gttrigger@users.noreply.github.com> Date: Thu, 18 Dec 2025 11:28:10 +0100 Subject: [PATCH 02/10] Provisioning: escape URLs in PR comments to avoid malformed markdown. (#115486) provisioning: escape URLs in webhook changes to allow for proper markdown. --- .../webhooks/pullrequest/changes.go | 15 ++-- .../webhooks/pullrequest/changes_test.go | 74 ++++++++++++++++++- 2 files changed, 82 insertions(+), 7 deletions(-) diff --git a/pkg/registry/apis/provisioning/webhooks/pullrequest/changes.go b/pkg/registry/apis/provisioning/webhooks/pullrequest/changes.go index f8e485e8fe5..d6fec09bc96 100644 --- a/pkg/registry/apis/provisioning/webhooks/pullrequest/changes.go +++ b/pkg/registry/apis/provisioning/webhooks/pullrequest/changes.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "net/url" - "path" "strings" "time" @@ -141,14 +140,20 @@ func (e *evaluator) evaluateFile(ctx context.Context, repo repository.Reader, ba if info.Parsed.GVK.Kind == dashboardKind { // FIXME: extract the logic out of a dashboard URL builder/injector or similar // for testability and decoupling + urlBuilder, err := url.Parse(baseURL) + if err != nil { + info.Error = err.Error() + return info + } + if info.Parsed.Existing != nil { - info.GrafanaURL = fmt.Sprintf("%sd/%s/%s", baseURL, obj.GetName(), - slugify.Slugify(info.Title)) + grafanaURL := urlBuilder.JoinPath("d", obj.GetName(), slugify.Slugify(info.Title)) + info.GrafanaURL = grafanaURL.String() } // Load this file directly - info.PreviewURL = baseURL + path.Join("admin/provisioning", - info.Parsed.Repo.Name, "dashboard/preview", info.Parsed.Info.Path) + previewURL := urlBuilder.JoinPath("admin/provisioning", info.Parsed.Repo.Name, "dashboard/preview", info.Parsed.Info.Path) + info.PreviewURL = previewURL.String() query := url.Values{} query.Set("ref", info.Parsed.Info.Ref) diff --git a/pkg/registry/apis/provisioning/webhooks/pullrequest/changes_test.go b/pkg/registry/apis/provisioning/webhooks/pullrequest/changes_test.go index c8f0c33e92a..6c513830d29 100644 --- a/pkg/registry/apis/provisioning/webhooks/pullrequest/changes_test.go +++ b/pkg/registry/apis/provisioning/webhooks/pullrequest/changes_test.go @@ -737,8 +737,78 @@ func TestCalculateChanges(t *testing.T) { Path: "path/to/file.json", Ref: "ref", }, - GrafanaURL: "ht tp://bad url/d/the-uid/hello-world", // Malformed URL - PreviewURL: "ht tp://bad url/admin/provisioning/y/dashboard/preview/path/to/file.json?pull_request_url=http%253A%252F%252Fgithub.com%252Fpr%252F&ref=ref", + Error: "parse \"ht tp://bad url/\": first path segment in URL cannot contain colon", + }}, + }, + }, + { + name: "path with spaces", + setupMocks: func(parser *resources.MockParser, reader *repository.MockReader, progress *jobs.MockJobProgressRecorder, renderer *MockScreenshotRenderer, parserFactory *resources.MockParserFactory) { + finfo := &repository.FileInfo{ + Path: "path/to/file with spaces.json", + Ref: "ref", + Data: []byte("xxxx"), + } + obj := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": resources.DashboardResource.GroupVersion().String(), + "kind": dashboardKind, + "metadata": map[string]interface{}{ + "name": "the-uid", + }, + "spec": map[string]interface{}{ + "title": "hello world", + }, + }, + } + meta, _ := utils.MetaAccessor(obj) + + progress.On("SetMessage", mock.Anything, "process path/to/file with spaces.json").Return() + reader.On("Read", mock.Anything, "path/to/file with spaces.json", "ref").Return(finfo, nil) + reader.On("Config").Return(&provisioning.Repository{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-repo", + Namespace: "x", + }, + Spec: provisioning.RepositorySpec{ + GitHub: &provisioning.GitHubRepositoryConfig{ + GenerateDashboardPreviews: true, + }, + }, + }) + parser.On("Parse", mock.Anything, finfo).Return(&resources.ParsedResource{ + Info: finfo, + Repo: provisioning.ResourceRepositoryInfo{ + Namespace: "x", + Name: "y", + }, + GVK: schema.GroupVersionKind{ + Kind: dashboardKind, + }, + Obj: obj, + Existing: obj, + Meta: meta, + DryRunResponse: obj, + }, nil) + renderer.On("IsAvailable", mock.Anything, mock.Anything).Return(false) + parserFactory.On("GetParser", mock.Anything, mock.Anything).Return(parser, nil) + }, + changes: []repository.VersionedFileChange{{ + Action: repository.FileActionCreated, + Path: "path/to/file with spaces.json", + Ref: "ref", + }}, + expectedInfo: changeInfo{ + Changes: []fileChangeInfo{{ + Change: repository.VersionedFileChange{ + Action: repository.FileActionCreated, + Path: "path/to/file with spaces.json", + Ref: "ref", + }, + GrafanaURL: "http://host/d/the-uid/hello-world", + PreviewURL: "http://host/admin/provisioning/y/dashboard/preview/path/to/file%20with%20spaces.json?pull_request_url=http%253A%252F%252Fgithub.com%252Fpr%252F&ref=ref", + GrafanaScreenshotURL: "", + PreviewScreenshotURL: "", }}, }, }, From 5bedcc7bd7cf0d8636c1d0839466404f0790e48f Mon Sep 17 00:00:00 2001 From: Jack Westbrook Date: Thu, 18 Dec 2025 11:47:38 +0100 Subject: [PATCH 03/10] Frontend: use custom conditions for development and build (#111685) * build(frontend): enable custom condition for resolving source files during dev and build * feat(packages): apply conditional name to export properties * chore(packages): add standard exports to flamegraph and prometheus * chore(packages): resolve main, module, types to built files * build(packages): clean up prepare-npm-package for custom condition changes * refactor(packages): reduce repetition in conditional exports * build(storybook): add @grafana-app/source to conditionNames * test(frontend): add grafana-app/source customCondition for jest tests * refactor(frontend): remove nested package import paths * chore(jest): use customExportConditions for source files and browser * chore(i18n): use src for ./eslint-plugin export * chore(packages): set packages tsconfigs to moduleResolution bundler * chore(packages): fix rollup builds * build(packages): build cjs as multiple files * chore(sql): reference MonitoringLogger for moduleresolution bundler to pass typecheck * chore(ui): add type refs for moduleresolution bundler to pass typecheck * feat(schema): add exports for cleaner import paths * refactor(frontend): clean up schema paths to point to exports instead of nested file paths * build(storybook): hack the builder-manager for custom conditions to resolve * build(decoupled-plugins): fix broken builds due to missing conditionNames * chore(e2e): pass condition to playwright to resolve local packages * build(frontend): fix failing build * chore(select): fix typings * style(frontend): clean up eslint suppressions * chore(packages): fix type errors due to incorrect tsconfig settings * build(generate-apis): use swc with ts-node and moduleResolution bundler * chore(cypress): add conditionNames to resolve monorepo packages * build(npm): update prepare to work with latest exports changes * build(packages): fix prepare-npm-package script * fix(e2e-selectors): update debugoverlay for data-testid change * build(packages): stop editing package.json at pack n publish time * rerun ci * chore(api-clients): use moduleResolution: bundler for customConditions support * chore(api-clients): fix generation * build(packages): remove aliasing exports, remove exports with only customConditions * Revert "refactor(frontend): clean up schema paths to point to exports instead of nested file paths" This reverts commit 7949b6ea0e60e51989d2a8149b7a24647cd68916. * revert(schema): remove exports from package so builds work * build(api-clients): fix up api-clients exports and rollup config * build(api-clients): Update generated package exports for api clients * build(schema): add overrides to cjsOutput and esmOutput so built directory structure is correct * fix(packages): use rootDirs to prevent types/src directories in built d.ts file paths * build(packages): prevent empty exports added to package.json during pack * docs(packages): update readme with custom conditions information --------- Co-authored-by: Tom Ratcliffe --- ...@storybook-core-npm-8.6.2-8c752112c0.patch | 13 ++ e2e/cypress/plugins/typescriptPreprocessor.js | 1 + eslint-suppressions.json | 3 - jest.config.js | 3 + package.json | 13 +- packages/README.md | 31 +++- packages/grafana-alerting/package.json | 38 +++-- packages/grafana-alerting/rollup.config.ts | 6 +- packages/grafana-api-clients/package.json | 157 +++++++++++------- packages/grafana-api-clients/rollup.config.ts | 22 +-- .../src/generator/helpers.ts | 6 +- packages/grafana-api-clients/tsconfig.json | 12 +- packages/grafana-data/package.json | 35 ++-- packages/grafana-data/rollup.config.ts | 4 +- packages/grafana-data/tsconfig.json | 4 +- packages/grafana-e2e-selectors/package.json | 17 +- .../grafana-e2e-selectors/rollup.config.ts | 2 +- .../src/selectors/components.ts | 1 + packages/grafana-e2e-selectors/tsconfig.json | 3 +- packages/grafana-flamegraph/package.json | 17 +- packages/grafana-flamegraph/rollup.config.ts | 2 +- packages/grafana-flamegraph/tsconfig.json | 3 +- packages/grafana-i18n/package.json | 23 ++- packages/grafana-i18n/rollup.config.ts | 10 +- packages/grafana-i18n/tsconfig.json | 3 +- .../grafana-o11y-ds-frontend/tsconfig.json | 3 +- .../jest/jest.config.js | 3 + packages/grafana-plugin-configs/tsconfig.json | 7 +- .../grafana-plugin-configs/webpack.config.ts | 1 + packages/grafana-prometheus/package.json | 17 +- packages/grafana-prometheus/rollup.config.ts | 2 +- packages/grafana-runtime/package.json | 32 ++-- packages/grafana-runtime/rollup.config.ts | 4 +- packages/grafana-runtime/src/index.ts | 10 +- packages/grafana-runtime/tsconfig.json | 3 +- packages/grafana-schema/package.json | 9 +- packages/grafana-schema/rollup.config.ts | 7 +- packages/grafana-schema/tsconfig.json | 4 +- packages/grafana-sql/src/utils/logging.ts | 4 +- packages/grafana-sql/tsconfig.json | 3 +- packages/grafana-ui/.storybook/main.ts | 10 ++ packages/grafana-ui/.storybook/tsconfig.json | 3 +- packages/grafana-ui/package.json | 32 ++-- packages/grafana-ui/rollup.config.ts | 4 +- .../Forms/Legacy/Select/SelectOptionGroup.tsx | 3 +- .../src/components/Select/ValueContainer.tsx | 3 +- packages/grafana-ui/tsconfig.json | 3 +- packages/rollup.config.parts.ts | 12 +- project.json | 3 +- .../app/features/admin/UserListAdminPage.tsx | 2 +- .../features/admin/UserListAnonymousPage.tsx | 2 +- .../app/features/admin/UserListPage.test.tsx | 2 +- .../DashboardsListModalButton.tsx | 2 +- .../UserListPublicDashboardPage.tsx | 2 +- .../inspect/InspectJsonTab.tsx | 2 +- .../layout-auto-grid/AutoGridItemRenderer.tsx | 2 +- .../components/DashNav/ShareButton.tsx | 2 +- .../PublicDashboardNotAvailable.tsx | 2 +- .../ConfigPublicDashboard.tsx | 2 +- .../ConfigPublicDashboard/Configuration.tsx | 2 +- .../AcknowledgeCheckboxes.tsx | 2 +- .../ModalAlerts/NoUpsertPermissionsAlert.tsx | 2 +- .../UnsupportedDataSourcesAlert.tsx | 2 +- .../UnsupportedTemplateVariablesAlert.tsx | 2 +- .../SharePublicDashboard.test.tsx | 2 +- .../containers/PublicDashboardPage.test.tsx | 2 +- .../containers/PublicDashboardPage.tsx | 2 +- .../PrometheusListView/RawListItem.tsx | 2 +- .../logs/components/panel/LogListControls.tsx | 2 +- .../PublicDashboardListTable.test.tsx | 2 +- .../PublicDashboardListTable.tsx | 2 +- .../panel/geomap/components/DebugOverlay.tsx | 4 +- scripts/cli/tsconfig.json | 4 +- scripts/prepare-npm-package.js | 111 +++---------- scripts/tsconfig.base.json | 1 + scripts/validate-npm-packages.sh | 2 +- scripts/webpack/webpack.common.js | 1 + tsconfig.json | 3 +- yarn.lock | 24 +++ 79 files changed, 440 insertions(+), 365 deletions(-) create mode 100644 .yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch diff --git a/.yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch b/.yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch new file mode 100644 index 00000000000..730ecce8fb2 --- /dev/null +++ b/.yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch @@ -0,0 +1,13 @@ +diff --git a/dist/builder-manager/index.js b/dist/builder-manager/index.js +index 3d7f9b213dae1801bda62b31db31b9113e382ccd..212501c63d20146c29db63fb0f6300c6779eecb5 100644 +--- a/dist/builder-manager/index.js ++++ b/dist/builder-manager/index.js +@@ -1970,7 +1970,7 @@ var pa = /^\/($|\?)/, G, C, xt = /* @__PURE__ */ o(async (e) => { + bundle: !0, + minify: !0, + sourcemap: !1, +- conditions: ["browser", "module", "default"], ++ conditions: ["@grafana-app/source", "browser", "module", "default"], + jsxFactory: "React.createElement", + jsxFragment: "React.Fragment", + jsx: "transform", diff --git a/e2e/cypress/plugins/typescriptPreprocessor.js b/e2e/cypress/plugins/typescriptPreprocessor.js index 27765380994..ed054f6f943 100644 --- a/e2e/cypress/plugins/typescriptPreprocessor.js +++ b/e2e/cypress/plugins/typescriptPreprocessor.js @@ -18,6 +18,7 @@ const webpackOptions = { }, resolve: { extensions: ['.ts', '.js'], + conditionNames: ['@grafana-app/source', '...'], }, }; diff --git a/eslint-suppressions.json b/eslint-suppressions.json index dfa69ae64f4..08f37b316d6 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -4246,9 +4246,6 @@ } }, "public/app/plugins/panel/geomap/components/DebugOverlay.tsx": { - "@grafana/no-aria-label-selectors": { - "count": 1 - }, "react-prefer-function-component/react-prefer-function-component": { "count": 1 } diff --git a/jest.config.js b/jest.config.js index ef107c8cc24..17a2ce9ca32 100644 --- a/jest.config.js +++ b/jest.config.js @@ -40,6 +40,9 @@ const esModules = [ module.exports = { verbose: false, testEnvironment: 'jsdom', + testEnvironmentOptions: { + customExportConditions: ['@grafana-app/source', 'browser'], + }, transform: { '^.+\\.(ts|tsx|js|jsx)$': [require.resolve('ts-jest')], }, diff --git a/package.json b/package.json index e148217cac3..f2300869740 100644 --- a/package.json +++ b/package.json @@ -26,10 +26,10 @@ "e2e:enterprise": "./e2e/start-and-run-suite enterprise", "e2e:enterprise:dev": "./e2e/start-and-run-suite enterprise dev", "e2e:enterprise:debug": "./e2e/start-and-run-suite enterprise debug", - "e2e:playwright": "yarn playwright test --grep-invert @cloud-plugins", - "e2e:playwright:cloud-plugins": "yarn playwright test --grep @cloud-plugins", - "e2e:playwright:storybook": "yarn playwright test -c playwright.storybook.config.ts", - "e2e:acceptance": "yarn playwright test --grep @acceptance", + "e2e:playwright": "NODE_OPTIONS='-C @grafana-app/source' yarn playwright test --grep-invert @cloud-plugins", + "e2e:playwright:cloud-plugins": "NODE_OPTIONS='-C @grafana-app/source' yarn playwright test --grep @cloud-plugins", + "e2e:playwright:storybook": "NODE_OPTIONS='-C @grafana-app/source' yarn playwright test -c playwright.storybook.config.ts", + "e2e:acceptance": "NODE_OPTIONS='-C @grafana-app/source' yarn playwright test --grep @acceptance", "e2e:storybook": "PORT=9001 ./e2e/run-suite storybook true", "e2e:plugin:build": "nx run-many -t build --projects='@test-plugins/*'", "e2e:plugin:build:dev": "nx run-many -t dev --projects='@test-plugins/*' --maxParallel=100", @@ -63,7 +63,7 @@ "storybook": "yarn workspace @grafana/ui storybook --ci", "storybook:build": "yarn workspace @grafana/ui storybook:build", "themes-schema": "typescript-json-schema ./tsconfig.json NewThemeOptions --include 'packages/grafana-data/src/themes/createTheme.ts' --out public/app/features/theme-playground/schema.generated.json", - "themes-generate": "yarn themes-schema && esbuild --target=es6 ./scripts/cli/generateSassVariableFiles.ts --bundle --platform=node --tsconfig=./scripts/cli/tsconfig.json | node", + "themes-generate": "yarn themes-schema && esbuild --target=es6 ./scripts/cli/generateSassVariableFiles.ts --bundle --conditions=@grafana-app/source --platform=node --tsconfig=./scripts/cli/tsconfig.json | node", "themes:usage": "eslint . --ignore-pattern '*.test.ts*' --ignore-pattern '*.spec.ts*' --cache --plugin '@grafana' --rule '{ @grafana/theme-token-usage: \"error\" }'", "typecheck": "tsc --noEmit && yarn run packages:typecheck", "plugins:build-bundled": "echo 'bundled plugins are no longer supported'", @@ -460,7 +460,8 @@ "tmp@npm:^0.0.33": "~0.2.1", "js-yaml@npm:4.1.0": "^4.1.0", "js-yaml@npm:=4.1.0": "^4.1.0", - "nodemailer": "7.0.7" + "nodemailer": "7.0.7", + "@storybook/core@npm:8.6.2": "patch:@storybook/core@npm%3A8.6.2#~/.yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch" }, "workspaces": { "packages": [ diff --git a/packages/README.md b/packages/README.md index b42f7082c5c..3fa0dceebc7 100644 --- a/packages/README.md +++ b/packages/README.md @@ -2,13 +2,32 @@ ## Exporting code conventions -`@grafana/ui`, `@grafana/data` and `@grafana/runtime` makes use of `exports` in package.json to define three entrypoints that Grafana core and Grafana plugins can access. Before exposing anything in these packages please consider the table below to better understand the use case of each export. +All the `@grafana` packages in this repo (except `@grafana/schema`) make use of `exports` in package.json to define entrypoints that Grafana core and Grafana plugins can access. Exports can also be used to restrict access to internal files in packages. -| Export Name | Import Path | Description | Available to Grafana | Available to plugins | -| ------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | -------------------- | -| `./` | `@grafana/ui` | The public API entrypoint. If the code is stable and you want to share it everywhere, this is the place to export it. | ✅ | ✅ | -| `./unstable` | `@grafana/ui/unstable` | The public API entrypoint for all experimental code. If you want to iterate and test code from Grafana and plugins, this is the place to export it. | ✅ | ✅ | -| `./internal` | `@grafana/ui/internal` | The private API entrypoint for internal code shared with Grafana. If you need to import code in Grafana but don't want to expose it to plugins, this is the place to export it. | ✅ | ❌ | +Package authors are free to create as many exports as they like but should consider the following points: + +1. Resolution of source code within this repo is handled by the [customCondition](https://www.typescriptlang.org/tsconfig/#customConditions) `@grafana-app/source`. This allows the frontend tooling in this repo to resolve to the source code preventing the need to build all the packages up front. When adding exports it is important to add an entry for the custom condition as the first item. All other entries should point to the built, bundled files. For example: + + ```json + "exports": { + ".": { + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" + } + } + ``` + +2. If you add exports to your package you must export the `package.json` file. + +3. Before exposing anything in these packages please consider the table below to better understand the conventions we have put in place for most of the packages in this repository. + +| Export Name | Import Path | Description | Available to Grafana | Available to plugins | +| ------------ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | -------------------- | +| `./` | `@grafana/ui` | The public API entrypoint. If the code is stable and you want to share it everywhere, this is the place to export it. | ✅ | ✅ | +| `./unstable` | `@grafana/ui/unstable` | The public API entrypoint for all experimental code. If you want to iterate and test code from Grafana and plugins, this is the place to export it. | ✅ | ✅ | +| `./internal` | `@grafana/ui/internal` | The private API entrypoint for internal code shared with Grafana. If you want to co-locate code in a package with it's public API but only want the Grafana application to access it, this is the place to export it. | ✅ | ❌ | ## Versioning diff --git a/packages/grafana-alerting/package.json b/packages/grafana-alerting/package.json index 1c3ab2bf9b4..d64f1c01893 100644 --- a/packages/grafana-alerting/package.json +++ b/packages/grafana-alerting/package.json @@ -17,32 +17,34 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-alerting" }, - "main": "src/index.ts", - "types": "src/index.ts", - "module": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", "exports": { "./package.json": "./package.json", ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" - }, - "./internal": { - "import": "./src/internal.ts", - "require": "./src/internal.ts" + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" }, "./unstable": { - "import": "./src/unstable.ts", - "require": "./src/unstable.ts" + "@grafana-app/source": "./src/unstable.ts", + "types": "./dist/types/unstable.d.ts", + "import": "./dist/esm/unstable.mjs", + "require": "./dist/cjs/unstable.cjs" + }, + "./internal": { + "@grafana-app/source": "./src/internal.ts" }, "./testing": { - "import": "./src/testing.ts", - "require": "./src/testing.ts" + "@grafana-app/source": "./src/testing.ts", + "types": "./dist/types/testing.d.ts", + "import": "./dist/esm/testing.mjs", + "require": "./dist/cjs/testing.cjs" } }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ @@ -57,8 +59,8 @@ "clean": "rimraf ./dist ./compiled ./unstable ./testing ./package.tgz", "typecheck": "tsc --emitDeclarationOnly false --noEmit", "codegen": "rtk-query-codegen-openapi ./scripts/codegen.ts", - "prepack": "cp package.json package.json.bak && ALIAS_PACKAGE_NAME=testing,unstable node ../../scripts/prepare-npm-package.js", - "postpack": "mv package.json.bak package.json && rimraf ./unstable ./testing", + "prepack": "cp package.json package.json.bak && node ../../scripts/prepare-npm-package.js", + "postpack": "mv package.json.bak package.json", "i18n-extract": "i18next-cli extract --sync-primary" }, "devDependencies": { diff --git a/packages/grafana-alerting/rollup.config.ts b/packages/grafana-alerting/rollup.config.ts index f8f41e3ad2c..43914b47b70 100644 --- a/packages/grafana-alerting/rollup.config.ts +++ b/packages/grafana-alerting/rollup.config.ts @@ -9,19 +9,19 @@ export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-alerting')], + output: [cjsOutput(pkg, 'grafana-alerting'), esmOutput(pkg, 'grafana-alerting')], treeshake: false, }, { input: 'src/unstable.ts', plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-alerting')], + output: [cjsOutput(pkg, 'grafana-alerting'), esmOutput(pkg, 'grafana-alerting')], treeshake: false, }, { input: 'src/testing.ts', plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-alerting')], + output: [cjsOutput(pkg, 'grafana-alerting'), esmOutput(pkg, 'grafana-alerting')], treeshake: false, }, ]; diff --git a/packages/grafana-api-clients/package.json b/packages/grafana-api-clients/package.json index 2d976b3a890..39accb04535 100644 --- a/packages/grafana-api-clients/package.json +++ b/packages/grafana-api-clients/package.json @@ -15,88 +15,121 @@ "url": "https://github.com/grafana/grafana.git", "directory": "packages/grafana-api-clients" }, - "main": "src/index.ts", - "module": "src/index.ts", - "types": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", "exports": { "./package.json": "./package.json", ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" }, "./rtkq": { - "import": "./src/clients/rtkq/index.ts", - "require": "./src/clients/rtkq/index.ts" + "@grafana-app/source": "./src/clients/rtkq/index.ts", + "types": "./dist/types/clients/rtkq/index.d.ts", + "import": "./dist/esm/clients/rtkq/index.mjs", + "require": "./dist/cjs/clients/rtkq/index.cjs" }, "./rtkq/advisor/v0alpha1": { - "import": "./src/clients/rtkq/advisor/v0alpha1/index.ts", - "require": "./src/clients/rtkq/advisor/v0alpha1/index.ts" - }, - "./rtkq/correlations/v0alpha1": { - "import": "./src/clients/rtkq/correlations/v0alpha1/index.ts", - "require": "./src/clients/rtkq/correlations/v0alpha1/index.ts" - }, - "./rtkq/dashboard/v0alpha1": { - "import": "./src/clients/rtkq/dashboard/v0alpha1/index.ts", - "require": "./src/clients/rtkq/dashboard/v0alpha1/index.ts" - }, - "./rtkq/folder/v1beta1": { - "import": "./src/clients/rtkq/folder/v1beta1/index.ts", - "require": "./src/clients/rtkq/folder/v1beta1/index.ts" - }, - "./rtkq/iam/v0alpha1": { - "import": "./src/clients/rtkq/iam/v0alpha1/index.ts", - "require": "./src/clients/rtkq/iam/v0alpha1/index.ts" - }, - "./rtkq/legacy": { - "import": "./src/clients/rtkq/legacy/index.ts", - "require": "./src/clients/rtkq/legacy/index.ts" - }, - "./rtkq/legacy/migrate-to-cloud": { - "import": "./src/clients/rtkq/migrate-to-cloud/index.ts", - "require": "./src/clients/rtkq/migrate-to-cloud/index.ts" - }, - "./rtkq/legacy/preferences": { - "import": "./src/clients/rtkq/preferences/user/index.ts", - "require": "./src/clients/rtkq/preferences/user/index.ts" - }, - "./rtkq/legacy/user": { - "import": "./src/clients/rtkq/user/index.ts", - "require": "./src/clients/rtkq/user/index.ts" - }, - "./rtkq/playlist/v0alpha1": { - "import": "./src/clients/rtkq/playlist/v0alpha1/index.ts", - "require": "./src/clients/rtkq/playlist/v0alpha1/index.ts" - }, - "./rtkq/preferences/v1alpha1": { - "import": "./src/clients/rtkq/preferences/v1alpha1/index.ts", - "require": "./src/clients/rtkq/preferences/v1alpha1/index.ts" + "@grafana-app/source": "./src/clients/rtkq/advisor/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/advisor/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/advisor/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/advisor/v0alpha1/index.cjs" }, "./rtkq/collections/v1alpha1": { - "import": "./src/clients/rtkq/collections/v1alpha1/index.ts", - "require": "./src/clients/rtkq/collections/v1alpha1/index.ts" + "@grafana-app/source": "./src/clients/rtkq/collections/v1alpha1/index.ts", + "types": "./dist/types/clients/rtkq/collections/v1alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/collections/v1alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/collections/v1alpha1/index.cjs" + }, + "./rtkq/correlations/v0alpha1": { + "@grafana-app/source": "./src/clients/rtkq/correlations/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/correlations/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/correlations/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/correlations/v0alpha1/index.cjs" + }, + "./rtkq/dashboard/v0alpha1": { + "@grafana-app/source": "./src/clients/rtkq/dashboard/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/dashboard/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/dashboard/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/dashboard/v0alpha1/index.cjs" + }, + "./rtkq/folder/v1beta1": { + "@grafana-app/source": "./src/clients/rtkq/folder/v1beta1/index.ts", + "types": "./dist/types/clients/rtkq/folder/v1beta1/index.d.ts", + "import": "./dist/esm/clients/rtkq/folder/v1beta1/index.mjs", + "require": "./dist/cjs/clients/rtkq/folder/v1beta1/index.cjs" + }, + "./rtkq/iam/v0alpha1": { + "@grafana-app/source": "./src/clients/rtkq/iam/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/iam/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/iam/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/iam/v0alpha1/index.cjs" + }, + "./rtkq/legacy": { + "@grafana-app/source": "./src/clients/rtkq/legacy/index.ts", + "types": "./dist/types/clients/rtkq/legacy/index.d.ts", + "import": "./dist/esm/clients/rtkq/legacy/index.mjs", + "require": "./dist/cjs/clients/rtkq/legacy/index.cjs" + }, + "./rtkq/legacy/migrate-to-cloud": { + "@grafana-app/source": "./src/clients/rtkq/migrate-to-cloud/index.ts", + "types": "./dist/types/clients/rtkq/migrate-to-cloud/index.d.ts", + "import": "./dist/esm/clients/rtkq/migrate-to-cloud/index.mjs", + "require": "./dist/cjs/clients/rtkq/migrate-to-cloud/index.cjs" + }, + "./rtkq/legacy/preferences": { + "@grafana-app/source": "./src/clients/rtkq/preferences/user/index.ts", + "types": "./dist/types/clients/rtkq/preferences/user/index.d.ts", + "import": "./dist/esm/clients/rtkq/preferences/user/index.mjs", + "require": "./dist/cjs/clients/rtkq/preferences/user/index.cjs" + }, + "./rtkq/legacy/user": { + "@grafana-app/source": "./src/clients/rtkq/user/index.ts", + "types": "./dist/types/clients/rtkq/user/index.d.ts", + "import": "./dist/esm/clients/rtkq/user/index.mjs", + "require": "./dist/cjs/clients/rtkq/user/index.cjs" + }, + "./rtkq/playlist/v0alpha1": { + "@grafana-app/source": "./src/clients/rtkq/playlist/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/playlist/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/playlist/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/playlist/v0alpha1/index.cjs" + }, + "./rtkq/preferences/v1alpha1": { + "@grafana-app/source": "./src/clients/rtkq/preferences/v1alpha1/index.ts", + "types": "./dist/types/clients/rtkq/preferences/v1alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/preferences/v1alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/preferences/v1alpha1/index.cjs" }, "./rtkq/provisioning/v0alpha1": { - "import": "./src/clients/rtkq/provisioning/v0alpha1/index.ts", - "require": "./src/clients/rtkq/provisioning/v0alpha1/index.ts" + "@grafana-app/source": "./src/clients/rtkq/provisioning/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/provisioning/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/provisioning/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/provisioning/v0alpha1/index.cjs" }, "./rtkq/shorturl/v1beta1": { - "import": "./src/clients/rtkq/shorturl/v1beta1/index.ts", - "require": "./src/clients/rtkq/shorturl/v1beta1/index.ts" + "@grafana-app/source": "./src/clients/rtkq/shorturl/v1beta1/index.ts", + "types": "./dist/types/clients/rtkq/shorturl/v1beta1/index.d.ts", + "import": "./dist/esm/clients/rtkq/shorturl/v1beta1/index.mjs", + "require": "./dist/cjs/clients/rtkq/shorturl/v1beta1/index.cjs" }, "./rtkq/historian.alerting/v0alpha1": { - "import": "./src/clients/rtkq/historian.alerting/v0alpha1/index.ts", - "require": "./src/clients/rtkq/historian.alerting/v0alpha1/index.ts" + "@grafana-app/source": "./src/clients/rtkq/historian.alerting/v0alpha1/index.ts", + "types": "./dist/types/clients/rtkq/historian.alerting/v0alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/historian.alerting/v0alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/historian.alerting/v0alpha1/index.cjs" }, "./rtkq/logsdrilldown/v1alpha1": { - "import": "./src/clients/rtkq/logsdrilldown/v1alpha1/index.ts", - "require": "./src/clients/rtkq/logsdrilldown/v1alpha1/index.ts" + "@grafana-app/source": "./src/clients/rtkq/logsdrilldown/v1alpha1/index.ts", + "types": "./dist/types/clients/rtkq/logsdrilldown/v1alpha1/index.d.ts", + "import": "./dist/esm/clients/rtkq/logsdrilldown/v1alpha1/index.mjs", + "require": "./dist/cjs/clients/rtkq/logsdrilldown/v1alpha1/index.cjs" } }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ diff --git a/packages/grafana-api-clients/rollup.config.ts b/packages/grafana-api-clients/rollup.config.ts index b36d59278fc..976a0c000fa 100644 --- a/packages/grafana-api-clients/rollup.config.ts +++ b/packages/grafana-api-clients/rollup.config.ts @@ -5,35 +5,17 @@ import { cjsOutput, entryPoint, esmOutput, plugins } from '../rollup.config.part const rq = createRequire(import.meta.url); const pkg = rq('./package.json'); -const apiClients = Object.entries<{ import: string; require: string }>(pkg.exports).filter(([key]) => - key.startsWith('./rtkq/') -); - -const apiClientConfigs = apiClients.map(([name, { import: importPath }]) => { - const baseCjsOutput = cjsOutput(pkg); - const entryFileNames = name.replace('./', '') + '.cjs'; - const cjsOutputConfig = { ...baseCjsOutput, entryFileNames }; - return { - input: importPath.replace('./', ''), - - plugins, - output: [cjsOutputConfig, esmOutput(pkg, 'grafana-api-clients')], - treeshake: false, - }; -}); - export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-api-clients')], + output: [cjsOutput(pkg, 'grafana-api-clients'), esmOutput(pkg, 'grafana-api-clients')], treeshake: false, }, { input: 'src/clients/rtkq/index.ts', plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-api-clients')], + output: [cjsOutput(pkg, 'grafana-api-clients'), esmOutput(pkg, 'grafana-api-clients')], treeshake: false, }, - ...apiClientConfigs, ]; diff --git a/packages/grafana-api-clients/src/generator/helpers.ts b/packages/grafana-api-clients/src/generator/helpers.ts index 2ac2ce01389..daba285787c 100644 --- a/packages/grafana-api-clients/src/generator/helpers.ts +++ b/packages/grafana-api-clients/src/generator/helpers.ts @@ -143,8 +143,10 @@ export const updatePackageJsonExports = // Create the new export entry const newExportKey = `./rtkq/${groupName}/${version}`; const newExportValue = { - import: `./src/clients/rtkq/${groupName}/${version}/index.ts`, - require: `./src/clients/rtkq/${groupName}/${version}/index.ts`, + '@grafana-app/source': `./src/clients/rtkq/${groupName}/${version}/index.ts`, + types: `./dist/types/clients/rtkq/${groupName}/${version}/index.d.ts`, + import: `./dist/esm/clients/rtkq/${groupName}/${version}/index.mjs`, + require: `./dist/cjs/clients/rtkq/${groupName}/${version}/index.cjs`, }; // Check if export already exists diff --git a/packages/grafana-api-clients/tsconfig.json b/packages/grafana-api-clients/tsconfig.json index ed1c294703e..e75b58104b0 100644 --- a/packages/grafana-api-clients/tsconfig.json +++ b/packages/grafana-api-clients/tsconfig.json @@ -8,7 +8,8 @@ "emitDeclarationOnly": true, "isolatedModules": true, "rootDirs": ["."], - "allowImportingTsExtensions": true + "allowImportingTsExtensions": true, + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": [ @@ -17,5 +18,12 @@ "../grafana-ui/src/types/*.d.ts", "../grafana-i18n/src/types/*.d.ts", "src/**/*.ts*" - ] + ], + "ts-node": { + "swc": true, + "compilerOptions": { + "module": "es2020", + "moduleResolution": "Bundler" + } + } } diff --git a/packages/grafana-data/package.json b/packages/grafana-data/package.json index ff90b2c295d..df595973cca 100644 --- a/packages/grafana-data/package.json +++ b/packages/grafana-data/package.json @@ -13,32 +13,31 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-data" }, - "main": "src/index.ts", - "types": "src/index.ts", - "module": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", "exports": { "./package.json": "./package.json", ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" - }, - "./internal": { - "import": "./src/internal/index.ts", - "require": "./src/internal/index.ts" + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" }, "./unstable": { - "import": "./src/unstable.ts", - "require": "./src/unstable.ts" + "@grafana-app/source": "./src/unstable.ts", + "types": "./dist/types/unstable.d.ts", + "import": "./dist/esm/unstable.mjs", + "require": "./dist/cjs/unstable.cjs" + }, + "./internal": { + "@grafana-app/source": "./src/internal/index.ts" }, "./test": { - "import": "./test/index.ts", - "require": "./test/index.ts" + "@grafana-app/source": "./test/index.ts" } }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ @@ -51,8 +50,8 @@ "build": "tsc -p ./tsconfig.build.json && rollup -c rollup.config.ts --configPlugin esbuild", "clean": "rimraf ./dist ./compiled ./unstable ./package.tgz", "typecheck": "tsc --emitDeclarationOnly false --noEmit", - "prepack": "cp package.json package.json.bak && ALIAS_PACKAGE_NAME=unstable node ../../scripts/prepare-npm-package.js", - "postpack": "mv package.json.bak package.json && rimraf ./unstable" + "prepack": "cp package.json package.json.bak && node ../../scripts/prepare-npm-package.js", + "postpack": "mv package.json.bak package.json" }, "dependencies": { "@braintree/sanitize-url": "7.0.1", diff --git a/packages/grafana-data/rollup.config.ts b/packages/grafana-data/rollup.config.ts index 378ab225769..87008ddc45f 100644 --- a/packages/grafana-data/rollup.config.ts +++ b/packages/grafana-data/rollup.config.ts @@ -9,13 +9,13 @@ export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-data')], + output: [cjsOutput(pkg, 'grafana-data'), esmOutput(pkg, 'grafana-data')], treeshake: false, }, { input: 'src/unstable.ts', plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-data')], + output: [cjsOutput(pkg, 'grafana-data'), esmOutput(pkg, 'grafana-data')], treeshake: false, }, ]; diff --git a/packages/grafana-data/tsconfig.json b/packages/grafana-data/tsconfig.json index d13025d3115..8e6013e32d9 100644 --- a/packages/grafana-data/tsconfig.json +++ b/packages/grafana-data/tsconfig.json @@ -3,10 +3,12 @@ "compilerOptions": { "declaration": true, "jsx": "react-jsx", + "baseUrl": "./", "declarationDir": "./dist/types", "emitDeclarationOnly": true, "isolatedModules": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": [ diff --git a/packages/grafana-e2e-selectors/package.json b/packages/grafana-e2e-selectors/package.json index 0dd5c5a9925..5527f4c0ca6 100644 --- a/packages/grafana-e2e-selectors/package.json +++ b/packages/grafana-e2e-selectors/package.json @@ -16,12 +16,19 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-e2e-selectors" }, - "main": "src/index.ts", - "types": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" + } + }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ diff --git a/packages/grafana-e2e-selectors/rollup.config.ts b/packages/grafana-e2e-selectors/rollup.config.ts index 1d47540a42a..a17799cc9a7 100644 --- a/packages/grafana-e2e-selectors/rollup.config.ts +++ b/packages/grafana-e2e-selectors/rollup.config.ts @@ -9,7 +9,7 @@ export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-e2e-selectors')], + output: [cjsOutput(pkg, 'grafana-e2e-selectors'), esmOutput(pkg, 'grafana-e2e-selectors')], treeshake: false, }, ]; diff --git a/packages/grafana-e2e-selectors/src/selectors/components.ts b/packages/grafana-e2e-selectors/src/selectors/components.ts index 0755477f93b..de04398a3e1 100644 --- a/packages/grafana-e2e-selectors/src/selectors/components.ts +++ b/packages/grafana-e2e-selectors/src/selectors/components.ts @@ -1332,6 +1332,7 @@ export const versionedComponents = { }, DebugOverlay: { wrapper: { + '12.3.0': 'data-testid debug-overlay-wrapper', '9.2.0': 'debug-overlay', }, }, diff --git a/packages/grafana-e2e-selectors/tsconfig.json b/packages/grafana-e2e-selectors/tsconfig.json index 41f1fb8efb0..b3fd8756461 100644 --- a/packages/grafana-e2e-selectors/tsconfig.json +++ b/packages/grafana-e2e-selectors/tsconfig.json @@ -5,7 +5,8 @@ "declarationDir": "./dist/types", "emitDeclarationOnly": true, "isolatedModules": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": ["src/**/*.ts"] diff --git a/packages/grafana-flamegraph/package.json b/packages/grafana-flamegraph/package.json index f4ec11c7cfa..b1c16ed68d1 100644 --- a/packages/grafana-flamegraph/package.json +++ b/packages/grafana-flamegraph/package.json @@ -16,12 +16,19 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-flamegraph" }, - "main": "src/index.ts", - "types": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" + } + }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ diff --git a/packages/grafana-flamegraph/rollup.config.ts b/packages/grafana-flamegraph/rollup.config.ts index 967916710d6..190cd7a6922 100644 --- a/packages/grafana-flamegraph/rollup.config.ts +++ b/packages/grafana-flamegraph/rollup.config.ts @@ -9,7 +9,7 @@ export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-flamegraph')], + output: [cjsOutput(pkg, 'grafana-flamegraph'), esmOutput(pkg, 'grafana-flamegraph')], treeshake: false, }, ]; diff --git a/packages/grafana-flamegraph/tsconfig.json b/packages/grafana-flamegraph/tsconfig.json index 0a1330e2114..7d4e07d6534 100644 --- a/packages/grafana-flamegraph/tsconfig.json +++ b/packages/grafana-flamegraph/tsconfig.json @@ -7,7 +7,8 @@ "declarationDir": "./dist/types", "emitDeclarationOnly": true, "isolatedModules": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": ["src/**/*.ts*", "../../public/app/types/*.d.ts", "../grafana-ui/src/types/*.d.ts"] diff --git a/packages/grafana-i18n/package.json b/packages/grafana-i18n/package.json index 824f594f8e6..36a9faa541b 100644 --- a/packages/grafana-i18n/package.json +++ b/packages/grafana-i18n/package.json @@ -14,33 +14,32 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-i18n" }, - "main": "src/index.ts", - "types": "src/index.ts", - "module": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", "exports": { "./package.json": "./package.json", ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" }, "./internal": { - "import": "./src/internal/index.ts", - "require": "./src/internal/index.ts" + "@grafana-app/source": "./src/internal/index.ts" }, "./eslint-plugin": { + "@grafana-app/source": "./src/eslint/index.cjs", "types": "./src/eslint/index.d.ts", - "import": "./src/eslint/index.cjs", - "require": "./src/eslint/index.cjs" + "default": "./src/eslint/index.cjs" } }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ "dist", + "src/eslint/**/*", "./README.md", "./CHANGELOG.md", "LICENSE_APACHE2" diff --git a/packages/grafana-i18n/rollup.config.ts b/packages/grafana-i18n/rollup.config.ts index 1b1115f65c9..913791e7d69 100644 --- a/packages/grafana-i18n/rollup.config.ts +++ b/packages/grafana-i18n/rollup.config.ts @@ -1,5 +1,4 @@ import { createRequire } from 'node:module'; -import copy from 'rollup-plugin-copy'; import { entryPoint, plugins, esmOutput, cjsOutput } from '../rollup.config.parts'; @@ -9,13 +8,8 @@ const pkg = rq('./package.json'); export default [ { input: entryPoint, - plugins: [ - ...plugins, - copy({ - targets: [{ src: 'src/eslint', dest: 'dist' }], - }), - ], - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-i18n')], + plugins, + output: [cjsOutput(pkg, 'grafana-i18n'), esmOutput(pkg, 'grafana-i18n')], treeshake: false, }, ]; diff --git a/packages/grafana-i18n/tsconfig.json b/packages/grafana-i18n/tsconfig.json index 2c83128f0f1..b1340cd69d0 100644 --- a/packages/grafana-i18n/tsconfig.json +++ b/packages/grafana-i18n/tsconfig.json @@ -6,7 +6,8 @@ "declarationDir": "./dist/types", "emitDeclarationOnly": true, "isolatedModules": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": ["src/**/*.ts*"] diff --git a/packages/grafana-o11y-ds-frontend/tsconfig.json b/packages/grafana-o11y-ds-frontend/tsconfig.json index c77d4f035c9..1817cc219ce 100644 --- a/packages/grafana-o11y-ds-frontend/tsconfig.json +++ b/packages/grafana-o11y-ds-frontend/tsconfig.json @@ -8,7 +8,8 @@ "emitDeclarationOnly": true, "isolatedModules": true, "allowJs": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": [ diff --git a/packages/grafana-plugin-configs/jest/jest.config.js b/packages/grafana-plugin-configs/jest/jest.config.js index 1f87fd10556..05e5a701226 100644 --- a/packages/grafana-plugin-configs/jest/jest.config.js +++ b/packages/grafana-plugin-configs/jest/jest.config.js @@ -17,6 +17,9 @@ export default { setupFiles: ['jest-canvas-mock'], setupFilesAfterEnv: ['/jest-setup.js'], testEnvironment: 'jsdom', + testEnvironmentOptions: { + customExportConditions: ['@grafana-app/source', 'browser'], + }, testMatch: ['/**/__tests__/**/*.{js,jsx,ts,tsx}', '/**/*.{spec,test,jest}.{js,jsx,ts,tsx}'], transform: { '^.+\\.(t|j)sx?$': [ diff --git a/packages/grafana-plugin-configs/tsconfig.json b/packages/grafana-plugin-configs/tsconfig.json index b7a0dd239e8..db619d2b1c2 100644 --- a/packages/grafana-plugin-configs/tsconfig.json +++ b/packages/grafana-plugin-configs/tsconfig.json @@ -1,12 +1,13 @@ { "compilerOptions": { - "jsx": "react-jsx", + "allowImportingTsExtensions": true, "alwaysStrict": true, + "customConditions": ["@grafana-app/source"], "declaration": false, - "resolveJsonModule": true, + "jsx": "react-jsx", "moduleResolution": "bundler", "noEmit": true, - "allowImportingTsExtensions": true + "resolveJsonModule": true }, "extends": "@grafana/tsconfig", "exclude": ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"], diff --git a/packages/grafana-plugin-configs/webpack.config.ts b/packages/grafana-plugin-configs/webpack.config.ts index 6f2846b5a97..8bfcdcec69a 100644 --- a/packages/grafana-plugin-configs/webpack.config.ts +++ b/packages/grafana-plugin-configs/webpack.config.ts @@ -312,6 +312,7 @@ const config = async (env: Env): Promise => { resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], + conditionNames: ['@grafana-app/source', '...'], unsafeCache: true, }, diff --git a/packages/grafana-prometheus/package.json b/packages/grafana-prometheus/package.json index 8ed4bd95d5a..6d6fa062635 100644 --- a/packages/grafana-prometheus/package.json +++ b/packages/grafana-prometheus/package.json @@ -15,8 +15,18 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-prometheus" }, - "main": "src/index.ts", - "types": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" + } + }, "files": [ "./dist", "./README.md", @@ -24,9 +34,6 @@ "./LICENSE_AGPL" ], "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "scripts": { diff --git a/packages/grafana-prometheus/rollup.config.ts b/packages/grafana-prometheus/rollup.config.ts index 8dbc60c8935..28083b2d26f 100644 --- a/packages/grafana-prometheus/rollup.config.ts +++ b/packages/grafana-prometheus/rollup.config.ts @@ -12,7 +12,7 @@ export default [ { input: entryPoint, plugins: [...plugins, image(), json(), dynamicImportVars()], - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-prometheus')], + output: [cjsOutput(pkg, 'grafana-prometheus'), esmOutput(pkg, 'grafana-prometheus')], treeshake: false, }, ]; diff --git a/packages/grafana-runtime/package.json b/packages/grafana-runtime/package.json index a46d08d4623..acf3f60bbc3 100644 --- a/packages/grafana-runtime/package.json +++ b/packages/grafana-runtime/package.json @@ -14,28 +14,28 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-runtime" }, - "main": "src/index.ts", - "types": "src/index.ts", - "module": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", "exports": { "./package.json": "./package.json", ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" - }, - "./internal": { - "import": "./src/internal/index.ts", - "require": "./src/internal/index.ts" + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" }, "./unstable": { - "import": "./src/unstable.ts", - "require": "./src/unstable.ts" + "@grafana-app/source": "./src/unstable.ts", + "types": "./dist/types/unstable.d.ts", + "import": "./dist/esm/unstable.mjs", + "require": "./dist/cjs/unstable.cjs" + }, + "./internal": { + "@grafana-app/source": "./src/internal/index.ts" } }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ @@ -49,8 +49,8 @@ "bundle": "rollup -c rollup.config.ts --configPlugin esbuild", "clean": "rimraf ./dist ./compiled ./unstable ./package.tgz", "typecheck": "tsc --emitDeclarationOnly false --noEmit", - "prepack": "cp package.json package.json.bak && ALIAS_PACKAGE_NAME=unstable node ../../scripts/prepare-npm-package.js", - "postpack": "mv package.json.bak package.json && rimraf ./unstable" + "prepack": "cp package.json package.json.bak && node ../../scripts/prepare-npm-package.js", + "postpack": "mv package.json.bak package.json" }, "dependencies": { "@grafana/data": "12.4.0-pre", diff --git a/packages/grafana-runtime/rollup.config.ts b/packages/grafana-runtime/rollup.config.ts index 5807c919136..120ad98645d 100644 --- a/packages/grafana-runtime/rollup.config.ts +++ b/packages/grafana-runtime/rollup.config.ts @@ -9,13 +9,13 @@ export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-runtime')], + output: [cjsOutput(pkg, 'grafana-runtime'), esmOutput(pkg, 'grafana-runtime')], treeshake: false, }, { input: 'src/unstable.ts', plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-runtime')], + output: [cjsOutput(pkg, 'grafana-runtime'), esmOutput(pkg, 'grafana-runtime')], treeshake: false, }, ]; diff --git a/packages/grafana-runtime/src/index.ts b/packages/grafana-runtime/src/index.ts index 489f9157700..58b30be8542 100644 --- a/packages/grafana-runtime/src/index.ts +++ b/packages/grafana-runtime/src/index.ts @@ -9,7 +9,15 @@ export * from './analytics/types'; export { loadPluginCss, type PluginCssOptions, setPluginImportUtils, getPluginImportUtils } from './utils/plugin'; export { reportMetaAnalytics, reportInteraction, reportPageview, reportExperimentView } from './analytics/utils'; export { featureEnabled } from './utils/licensing'; -export { logInfo, logDebug, logWarning, logError, createMonitoringLogger, logMeasurement } from './utils/logging'; +export { + logInfo, + logDebug, + logWarning, + logError, + createMonitoringLogger, + logMeasurement, + type MonitoringLogger, +} from './utils/logging'; export { DataSourceWithBackend, HealthCheckError, diff --git a/packages/grafana-runtime/tsconfig.json b/packages/grafana-runtime/tsconfig.json index 9dec8dd53ed..bbfc33b77ed 100644 --- a/packages/grafana-runtime/tsconfig.json +++ b/packages/grafana-runtime/tsconfig.json @@ -8,7 +8,8 @@ "emitDeclarationOnly": true, "isolatedModules": true, "allowJs": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": [ diff --git a/packages/grafana-schema/package.json b/packages/grafana-schema/package.json index 067475cd209..4f48e1511b2 100644 --- a/packages/grafana-schema/package.json +++ b/packages/grafana-schema/package.json @@ -13,13 +13,14 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-schema" }, - "main": "src/index.ts", - "types": "src/index.ts", + "main": "./src/index.ts", + "module": "./src/index.ts", + "types": "./src/index.ts", "publishConfig": { + "access": "public", "main": "./dist/cjs/index.cjs", "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", - "access": "public" + "types": "./dist/types/index.d.ts" }, "files": [ "dist", diff --git a/packages/grafana-schema/rollup.config.ts b/packages/grafana-schema/rollup.config.ts index 04928f75c47..4e5f77b3deb 100644 --- a/packages/grafana-schema/rollup.config.ts +++ b/packages/grafana-schema/rollup.config.ts @@ -15,7 +15,12 @@ export default [ { input: entryPoint, plugins, - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-schema')], + output: [ + // Schema still uses publishConfig to define output directory. + // TODO: Migrate this package to use exports. + cjsOutput(pkg, 'grafana-schema', { dir: path.dirname(pkg.publishConfig.main) }), + esmOutput(pkg, 'grafana-schema', { dir: path.dirname(pkg.publishConfig.module) }), + ], treeshake: false, }, { diff --git a/packages/grafana-schema/tsconfig.json b/packages/grafana-schema/tsconfig.json index 2c83128f0f1..8012f3267e6 100644 --- a/packages/grafana-schema/tsconfig.json +++ b/packages/grafana-schema/tsconfig.json @@ -3,10 +3,12 @@ "compilerOptions": { "declaration": true, "jsx": "react-jsx", + "baseUrl": "./", "declarationDir": "./dist/types", "emitDeclarationOnly": true, "isolatedModules": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": ["src/**/*.ts*"] diff --git a/packages/grafana-sql/src/utils/logging.ts b/packages/grafana-sql/src/utils/logging.ts index 95900184359..2d481dc4b8a 100644 --- a/packages/grafana-sql/src/utils/logging.ts +++ b/packages/grafana-sql/src/utils/logging.ts @@ -1,3 +1,3 @@ -import { createMonitoringLogger } from '@grafana/runtime'; +import { createMonitoringLogger, MonitoringLogger } from '@grafana/runtime'; -export const sqlPluginLogger = createMonitoringLogger('features.plugins.sql'); +export const sqlPluginLogger: MonitoringLogger = createMonitoringLogger('features.plugins.sql'); diff --git a/packages/grafana-sql/tsconfig.json b/packages/grafana-sql/tsconfig.json index 4bd2161f0e0..87f6db544ad 100644 --- a/packages/grafana-sql/tsconfig.json +++ b/packages/grafana-sql/tsconfig.json @@ -8,7 +8,8 @@ "emitDeclarationOnly": true, "isolatedModules": true, "strict": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": ["src/**/*.ts*", "../../public/app/types/*.d.ts", "../grafana-ui/src/types/*.d.ts"] diff --git a/packages/grafana-ui/.storybook/main.ts b/packages/grafana-ui/.storybook/main.ts index 29258c4a228..9bbf711b5c2 100644 --- a/packages/grafana-ui/.storybook/main.ts +++ b/packages/grafana-ui/.storybook/main.ts @@ -95,6 +95,16 @@ const mainConfig: StorybookConfig = { }, }); + // Tell storybook to resolve imports with the @grafana-app/source condition for + // the packages in this repo. + if (config && config.resolve) { + if (Array.isArray(config.resolve.conditionNames)) { + config.resolve.conditionNames.unshift('@grafana-app/source'); + } else { + config.resolve.conditionNames = ['@grafana-app/source', '...']; + } + } + return config; }, }; diff --git a/packages/grafana-ui/.storybook/tsconfig.json b/packages/grafana-ui/.storybook/tsconfig.json index cbcee5966e1..9d5c974f558 100644 --- a/packages/grafana-ui/.storybook/tsconfig.json +++ b/packages/grafana-ui/.storybook/tsconfig.json @@ -1,8 +1,7 @@ { "compilerOptions": { "declarationDir": "dist", - "noUnusedLocals": false, - "outDir": "compiled" + "noUnusedLocals": false }, "extends": "../tsconfig.json", "include": ["../src/**/*.ts*", "../../../public/app/types/svg.d.ts"] diff --git a/packages/grafana-ui/package.json b/packages/grafana-ui/package.json index f4a358d1654..478c44704ed 100644 --- a/packages/grafana-ui/package.json +++ b/packages/grafana-ui/package.json @@ -16,28 +16,28 @@ "url": "http://github.com/grafana/grafana.git", "directory": "packages/grafana-ui" }, - "main": "src/index.ts", - "types": "src/index.ts", - "module": "src/index.ts", + "main": "./dist/cjs/index.cjs", + "module": "./dist/esm/index.mjs", + "types": "./dist/types/index.d.ts", "exports": { "./package.json": "./package.json", ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" - }, - "./internal": { - "import": "./src/internal/index.ts", - "require": "./src/internal/index.ts" + "@grafana-app/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.mjs", + "require": "./dist/cjs/index.cjs" }, "./unstable": { - "import": "./src/unstable.ts", - "require": "./src/unstable.ts" + "@grafana-app/source": "./src/unstable.ts", + "types": "./dist/types/unstable.d.ts", + "import": "./dist/esm/unstable.mjs", + "require": "./dist/cjs/unstable.cjs" + }, + "./internal": { + "@grafana-app/source": "./src/internal/index.ts" } }, "publishConfig": { - "main": "./dist/cjs/index.cjs", - "module": "./dist/esm/index.mjs", - "types": "./dist/types/index.d.ts", "access": "public" }, "files": [ @@ -55,8 +55,8 @@ "storybook:build": "storybook build -o ./dist/storybook -c .storybook", "storybook:test": "test-storybook --url http://localhost:9001", "typecheck": "tsc --emitDeclarationOnly false --noEmit", - "prepack": "cp package.json package.json.bak && ALIAS_PACKAGE_NAME=unstable node ../../scripts/prepare-npm-package.js", - "postpack": "mv package.json.bak package.json && rimraf ./unstable" + "prepack": "cp package.json package.json.bak && node ../../scripts/prepare-npm-package.js", + "postpack": "mv package.json.bak package.json" }, "browserslist": [ "defaults", diff --git a/packages/grafana-ui/rollup.config.ts b/packages/grafana-ui/rollup.config.ts index 16c81ca4af8..14ff11d279b 100644 --- a/packages/grafana-ui/rollup.config.ts +++ b/packages/grafana-ui/rollup.config.ts @@ -24,7 +24,7 @@ export default [ flatten: false, }), ], - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-ui')], + output: [cjsOutput(pkg, 'grafana-ui'), esmOutput(pkg, 'grafana-ui')], treeshake: false, }, { @@ -37,7 +37,7 @@ export default [ flatten: false, }), ], - output: [cjsOutput(pkg), esmOutput(pkg, 'grafana-ui')], + output: [cjsOutput(pkg, 'grafana-ui'), esmOutput(pkg, 'grafana-ui')], treeshake: false, }, ]; diff --git a/packages/grafana-ui/src/components/Forms/Legacy/Select/SelectOptionGroup.tsx b/packages/grafana-ui/src/components/Forms/Legacy/Select/SelectOptionGroup.tsx index aecc7bf4514..a249db3eb2e 100644 --- a/packages/grafana-ui/src/components/Forms/Legacy/Select/SelectOptionGroup.tsx +++ b/packages/grafana-ui/src/components/Forms/Legacy/Select/SelectOptionGroup.tsx @@ -94,4 +94,5 @@ class UnthemedSelectOptionGroup extends PureComponent } } -export const SelectOptionGroup = withTheme2(UnthemedSelectOptionGroup); +// TODO: type this properly +export const SelectOptionGroup: React.FC = withTheme2(UnthemedSelectOptionGroup); diff --git a/packages/grafana-ui/src/components/Select/ValueContainer.tsx b/packages/grafana-ui/src/components/Select/ValueContainer.tsx index 6eb8326ae5d..f39666c8c5f 100644 --- a/packages/grafana-ui/src/components/Select/ValueContainer.tsx +++ b/packages/grafana-ui/src/components/Select/ValueContainer.tsx @@ -76,4 +76,5 @@ class UnthemedValueContainer>> = + withTheme2(UnthemedValueContainer); diff --git a/packages/grafana-ui/tsconfig.json b/packages/grafana-ui/tsconfig.json index 502d1958513..95871844f67 100644 --- a/packages/grafana-ui/tsconfig.json +++ b/packages/grafana-ui/tsconfig.json @@ -8,7 +8,8 @@ "emitDeclarationOnly": true, "isolatedModules": true, "allowJs": true, - "rootDirs": ["."] + "rootDirs": ["."], + "moduleResolution": "bundler" }, "exclude": ["dist/**/*"], "include": ["../../public/test/setupTests.ts", "../../public/app/types/*.d.ts", "src/**/*.ts*"], diff --git a/packages/rollup.config.parts.ts b/packages/rollup.config.parts.ts index 31116f56bdb..534b8cd7d25 100644 --- a/packages/rollup.config.parts.ts +++ b/packages/rollup.config.parts.ts @@ -23,25 +23,29 @@ export const plugins = [ ]; // Generates a rollup configuration for commonjs output. -export function cjsOutput(pkg) { +export function cjsOutput(pkg, pkgName, overrides = {}) { return { format: 'cjs', sourcemap: true, - dir: dirname(pkg.publishConfig.main), + dir: dirname(pkg.main), entryFileNames: '[name].cjs', + preserveModules: true, + preserveModulesRoot: resolve(projectCwd, `packages/${pkgName}/src`), esModule: true, interop: 'compat', + ...overrides, }; } // Generate a rollup configuration for es module output. -export function esmOutput(pkg, pkgName) { +export function esmOutput(pkg, pkgName, overrides = {}) { return { format: 'esm', sourcemap: true, - dir: dirname(pkg.publishConfig.module), + dir: dirname(pkg.module), entryFileNames: '[name].mjs', preserveModules: true, preserveModulesRoot: resolve(projectCwd, `packages/${pkgName}/src`), + ...overrides, }; } diff --git a/project.json b/project.json index a4a3fa81c09..702efba58af 100644 --- a/project.json +++ b/project.json @@ -39,7 +39,8 @@ "inputs": [ "{workspaceRoot}/scripts/cli/generateSassVariableFiles.ts", "{workspaceRoot}/packages/grafana-data/src/themes/**", - "{workspaceRoot}/packages/grafana-ui/src/themes/**" + "{workspaceRoot}/packages/grafana-ui/src/themes/**", + "{workspaceRoot}/package.json" ], "outputs": [ "{workspaceRoot}/public/sass/_variables.generated.scss", diff --git a/public/app/features/admin/UserListAdminPage.tsx b/public/app/features/admin/UserListAdminPage.tsx index cd7695b1db8..feebb6b98e1 100644 --- a/public/app/features/admin/UserListAdminPage.tsx +++ b/public/app/features/admin/UserListAdminPage.tsx @@ -3,7 +3,7 @@ import { ComponentType, useEffect } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { LinkButton, RadioButtonGroup, useStyles2, FilterInput, EmptyState } from '@grafana/ui'; import { Page } from 'app/core/components/Page/Page'; diff --git a/public/app/features/admin/UserListAnonymousPage.tsx b/public/app/features/admin/UserListAnonymousPage.tsx index eec26483830..bfb1f6f9125 100644 --- a/public/app/features/admin/UserListAnonymousPage.tsx +++ b/public/app/features/admin/UserListAnonymousPage.tsx @@ -3,7 +3,7 @@ import { useEffect } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { t } from '@grafana/i18n'; import { RadioButtonGroup, useStyles2, FilterInput } from '@grafana/ui'; import { Page } from 'app/core/components/Page/Page'; diff --git a/public/app/features/admin/UserListPage.test.tsx b/public/app/features/admin/UserListPage.test.tsx index 6601c06827d..4df8161b70c 100644 --- a/public/app/features/admin/UserListPage.test.tsx +++ b/public/app/features/admin/UserListPage.test.tsx @@ -1,7 +1,7 @@ import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { GrafanaBootConfig } from '@grafana/runtime'; import config from 'app/core/config'; diff --git a/public/app/features/admin/UserListPublicDashboardPage/DashboardsListModalButton.tsx b/public/app/features/admin/UserListPublicDashboardPage/DashboardsListModalButton.tsx index af1eda1f2fd..bf384a83bbc 100644 --- a/public/app/features/admin/UserListPublicDashboardPage/DashboardsListModalButton.tsx +++ b/public/app/features/admin/UserListPublicDashboardPage/DashboardsListModalButton.tsx @@ -1,7 +1,7 @@ import { css, cx } from '@emotion/css'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Button, LoadingPlaceholder, Modal, ModalsController, useStyles2 } from '@grafana/ui'; import { diff --git a/public/app/features/admin/UserListPublicDashboardPage/UserListPublicDashboardPage.tsx b/public/app/features/admin/UserListPublicDashboardPage/UserListPublicDashboardPage.tsx index c3618ba9b67..c18cb9c5c15 100644 --- a/public/app/features/admin/UserListPublicDashboardPage/UserListPublicDashboardPage.tsx +++ b/public/app/features/admin/UserListPublicDashboardPage/UserListPublicDashboardPage.tsx @@ -1,4 +1,4 @@ -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Icon, Stack, Tag, Tooltip } from '@grafana/ui'; import { Page } from 'app/core/components/Page/Page'; diff --git a/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx b/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx index 648f6de57ef..4fd9bc8b9a6 100644 --- a/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx +++ b/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx @@ -16,7 +16,7 @@ import { sceneUtils, VizPanel, } from '@grafana/scenes'; -import { LibraryPanel } from '@grafana/schema/'; +import { LibraryPanel } from '@grafana/schema'; import { Alert, Button, CodeEditor, Field, Select, useStyles2 } from '@grafana/ui'; import { isDashboardV2Spec } from 'app/features/dashboard/api/utils'; import { getPanelDataFrames } from 'app/features/dashboard/components/HelpWizard/utils'; diff --git a/public/app/features/dashboard-scene/scene/layout-auto-grid/AutoGridItemRenderer.tsx b/public/app/features/dashboard-scene/scene/layout-auto-grid/AutoGridItemRenderer.tsx index ee7fd012add..15b7e82ae36 100644 --- a/public/app/features/dashboard-scene/scene/layout-auto-grid/AutoGridItemRenderer.tsx +++ b/public/app/features/dashboard-scene/scene/layout-auto-grid/AutoGridItemRenderer.tsx @@ -1,7 +1,7 @@ import { css, cx } from '@emotion/css'; import { memo, useMemo } from 'react'; -import { GrafanaTheme2 } from '@grafana/data/'; +import { GrafanaTheme2 } from '@grafana/data'; import { LazyLoader, SceneComponentProps, VizPanel } from '@grafana/scenes'; import { useStyles2 } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/DashNav/ShareButton.tsx b/public/app/features/dashboard/components/DashNav/ShareButton.tsx index 1908ea1612a..a0e5200f47a 100644 --- a/public/app/features/dashboard/components/DashNav/ShareButton.tsx +++ b/public/app/features/dashboard/components/DashNav/ShareButton.tsx @@ -1,4 +1,4 @@ -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans } from '@grafana/i18n'; import { locationService } from '@grafana/runtime'; import { Button } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/PublicDashboardNotAvailable/PublicDashboardNotAvailable.tsx b/public/app/features/dashboard/components/PublicDashboardNotAvailable/PublicDashboardNotAvailable.tsx index 1ab0b57a937..ffa019d20d3 100644 --- a/public/app/features/dashboard/components/PublicDashboardNotAvailable/PublicDashboardNotAvailable.tsx +++ b/public/app/features/dashboard/components/PublicDashboardNotAvailable/PublicDashboardNotAvailable.tsx @@ -1,7 +1,7 @@ import { css, cx } from '@emotion/css'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { useStyles2 } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/ConfigPublicDashboard.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/ConfigPublicDashboard.tsx index be257dc5042..9d3dcb4a78b 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/ConfigPublicDashboard.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/ConfigPublicDashboard.tsx @@ -2,7 +2,7 @@ import { css } from '@emotion/css'; import { useForm } from 'react-hook-form'; import { GrafanaTheme2, TimeRange } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Button, ClipboardButton, Field, Input, Stack, Label, ModalsController, Switch, useStyles2 } from '@grafana/ui'; import { diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/Configuration.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/Configuration.tsx index 6cb97b9ac47..c0018735f4b 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/Configuration.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/Configuration.tsx @@ -1,7 +1,7 @@ import { UseFormRegister } from 'react-hook-form'; import { TimeRange } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { FieldSet, Label, Switch, TimeRangeInput, Stack } from '@grafana/ui'; import { DashboardInteractions } from 'app/features/dashboard-scene/utils/interactions'; diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/CreatePublicDashboard/AcknowledgeCheckboxes.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/CreatePublicDashboard/AcknowledgeCheckboxes.tsx index 76bed8c8d94..c875e3a7d90 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/CreatePublicDashboard/AcknowledgeCheckboxes.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/CreatePublicDashboard/AcknowledgeCheckboxes.tsx @@ -2,7 +2,7 @@ import { css } from '@emotion/css'; import { UseFormRegister } from 'react-hook-form'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Checkbox, FieldSet, LinkButton, useStyles2, Stack } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/NoUpsertPermissionsAlert.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/NoUpsertPermissionsAlert.tsx index a480fdd918f..4af3ade3397 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/NoUpsertPermissionsAlert.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/NoUpsertPermissionsAlert.tsx @@ -1,4 +1,4 @@ -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Alert } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedDataSourcesAlert.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedDataSourcesAlert.tsx index cc000e869ab..d0ac5015bfe 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedDataSourcesAlert.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedDataSourcesAlert.tsx @@ -2,7 +2,7 @@ import { css } from '@emotion/css'; import cx from 'classnames'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Alert, useStyles2 } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedTemplateVariablesAlert.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedTemplateVariablesAlert.tsx index 3eb2c3d0904..6ce2607fb13 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedTemplateVariablesAlert.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ModalAlerts/UnsupportedTemplateVariablesAlert.tsx @@ -1,4 +1,4 @@ -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { Alert } from '@grafana/ui'; diff --git a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/SharePublicDashboard.test.tsx b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/SharePublicDashboard.test.tsx index 9a0357f0626..99da08f24f8 100644 --- a/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/SharePublicDashboard.test.tsx +++ b/public/app/features/dashboard/components/ShareModal/SharePublicDashboard/SharePublicDashboard.test.tsx @@ -4,7 +4,7 @@ import { http, HttpResponse } from 'msw'; import { setupServer } from 'msw/node'; import { BootData, DataQuery } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { reportInteraction, setEchoSrv } from '@grafana/runtime'; import { Panel } from '@grafana/schema'; import config from 'app/core/config'; diff --git a/public/app/features/dashboard/containers/PublicDashboardPage.test.tsx b/public/app/features/dashboard/containers/PublicDashboardPage.test.tsx index 4500526802a..222f334ee4d 100644 --- a/public/app/features/dashboard/containers/PublicDashboardPage.test.tsx +++ b/public/app/features/dashboard/containers/PublicDashboardPage.test.tsx @@ -5,7 +5,7 @@ import { useEffectOnce } from 'react-use'; import { Props as AutoSizerProps } from 'react-virtualized-auto-sizer'; import { render } from 'test/test-utils'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Dashboard, DashboardCursorSync, FieldConfigSource, Panel, ThresholdsMode } from '@grafana/schema/src'; import { getRouteComponentProps } from 'app/core/navigation/mocks/routeProps'; import { DashboardInitPhase, DashboardMeta, DashboardRoutes } from 'app/types/dashboard'; diff --git a/public/app/features/dashboard/containers/PublicDashboardPage.tsx b/public/app/features/dashboard/containers/PublicDashboardPage.tsx index b6f74800a76..98553e46bc1 100644 --- a/public/app/features/dashboard/containers/PublicDashboardPage.tsx +++ b/public/app/features/dashboard/containers/PublicDashboardPage.tsx @@ -4,7 +4,7 @@ import { useLocation, useParams } from 'react-router-dom-v5-compat'; import { usePrevious } from 'react-use'; import { GrafanaTheme2, PageLayoutType, TimeZone } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { PageToolbar, useStyles2 } from '@grafana/ui'; import { Page } from 'app/core/components/Page/Page'; import { useGrafana } from 'app/core/context/GrafanaContext'; diff --git a/public/app/features/explore/PrometheusListView/RawListItem.tsx b/public/app/features/explore/PrometheusListView/RawListItem.tsx index 4da433e89ce..d192b5da3e9 100644 --- a/public/app/features/explore/PrometheusListView/RawListItem.tsx +++ b/public/app/features/explore/PrometheusListView/RawListItem.tsx @@ -3,7 +3,7 @@ import { useCopyToClipboard } from 'react-use'; import { Field, GrafanaTheme2 } from '@grafana/data'; import { t } from '@grafana/i18n'; -import { isValidLegacyName, utf8Support } from '@grafana/prometheus/src/utf8_support'; +import { isValidLegacyName, utf8Support } from '@grafana/prometheus'; import { reportInteraction } from '@grafana/runtime'; import { IconButton, useStyles2 } from '@grafana/ui'; diff --git a/public/app/features/logs/components/panel/LogListControls.tsx b/public/app/features/logs/components/panel/LogListControls.tsx index 5b482af2aad..a5deb524d66 100644 --- a/public/app/features/logs/components/panel/LogListControls.tsx +++ b/public/app/features/logs/components/panel/LogListControls.tsx @@ -5,13 +5,13 @@ import { MouseEvent, useCallback, useMemo } from 'react'; import { CoreApp, EventBus, + GrafanaTheme2, LogLevel, LogsDedupDescription, LogsDedupStrategy, LogsSortOrder, store, } from '@grafana/data'; -import { GrafanaTheme2 } from '@grafana/data/'; import { t } from '@grafana/i18n'; import { config, reportInteraction } from '@grafana/runtime'; import { Dropdown, Menu, useStyles2 } from '@grafana/ui'; diff --git a/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.test.tsx b/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.test.tsx index f5d3ad028b0..0014f107004 100644 --- a/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.test.tsx +++ b/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.test.tsx @@ -3,7 +3,7 @@ import { http, HttpResponse } from 'msw'; import { setupServer } from 'msw/node'; import { render } from 'test/test-utils'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { backendSrv } from 'app/core/services/backend_srv'; import { contextSrv } from 'app/core/services/context_srv'; diff --git a/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.tsx b/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.tsx index d14fd970d1d..a1bcedb5e70 100644 --- a/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.tsx +++ b/public/app/features/manage-dashboards/components/PublicDashboardListTable/PublicDashboardListTable.tsx @@ -3,7 +3,7 @@ import { useMemo, useState } from 'react'; import { useMedia } from 'react-use'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors as e2eSelectors } from '@grafana/e2e-selectors/src'; +import { selectors as e2eSelectors } from '@grafana/e2e-selectors'; import { Trans, t } from '@grafana/i18n'; import { reportInteraction } from '@grafana/runtime'; import { diff --git a/public/app/plugins/panel/geomap/components/DebugOverlay.tsx b/public/app/plugins/panel/geomap/components/DebugOverlay.tsx index de267de908f..d08d2042f05 100644 --- a/public/app/plugins/panel/geomap/components/DebugOverlay.tsx +++ b/public/app/plugins/panel/geomap/components/DebugOverlay.tsx @@ -6,7 +6,7 @@ import { PureComponent } from 'react'; import tinycolor from 'tinycolor2'; import { GrafanaTheme2 } from '@grafana/data'; -import { selectors } from '@grafana/e2e-selectors/src'; +import { selectors } from '@grafana/e2e-selectors'; import { Trans } from '@grafana/i18n'; import { config } from 'app/core/config'; @@ -44,7 +44,7 @@ export class DebugOverlay extends PureComponent { const { zoom, center } = this.state; return ( -
+
diff --git a/scripts/cli/tsconfig.json b/scripts/cli/tsconfig.json index 468d9938751..057344a363c 100644 --- a/scripts/cli/tsconfig.json +++ b/scripts/cli/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { - "moduleResolution": "node", - "module": "commonjs" + "moduleResolution": "nodenext", + "module": "NodeNext" }, "extends": "../../tsconfig.json", "ts-node": { diff --git a/scripts/prepare-npm-package.js b/scripts/prepare-npm-package.js index 054b3d12609..7a11a2eca4a 100644 --- a/scripts/prepare-npm-package.js +++ b/scripts/prepare-npm-package.js @@ -1,108 +1,35 @@ +//@ts-check import PackageJson from '@npmcli/package-json'; -import { mkdir } from 'node:fs/promises'; const cwd = process.cwd(); try { const pkgJson = await PackageJson.load(cwd); - const cjsIndex = pkgJson.content.publishConfig?.main ?? pkgJson.content.main; - const esmIndex = pkgJson.content.publishConfig?.module ?? pkgJson.content.module; - const typesIndex = pkgJson.content.publishConfig?.types ?? pkgJson.content.types; + const pkgJsonExports = pkgJson.content.exports; - const exports = { - './package.json': './package.json', - '.': { - import: { - types: typesIndex, - default: esmIndex, - }, - require: { - types: typesIndex, - default: cjsIndex, - }, - }, - }; - // Fix so scenes can access `@grafana/schema` nested dist import paths e.g. - // import {} from '@grafana/schema/dist/esm/raw/composable/bargauge/panelcfg/x/BarGaugePanelCfg_types.gen' - if (pkgJson.content.name === '@grafana/schema') { - exports['./dist/*'] = { - types: './dist/*', - default: './dist/*', - }; - } - - // Fix for @grafana/i18n so eslint-plugin can be imported by consumers - if (pkgJson.content.name === '@grafana/i18n') { - exports['./eslint-plugin'] = { - types: './dist/eslint/index.d.ts', - import: './dist/eslint/index.cjs', - require: './dist/eslint/index.cjs', - }; - } - - pkgJson.update({ - main: cjsIndex, - types: typesIndex, - module: esmIndex, - exports, - }); - - await pkgJson.save(); - - // If an alias package name is provided we add an exports entry for the alias - // then generate an additional "nested" package.json for typescript resolution that - // doesn't use the exports property in package.json. - if (process.env.ALIAS_PACKAGE_NAME) { - const aliasNames = process.env.ALIAS_PACKAGE_NAME.split(','); - - const additionalExports = aliasNames.reduce((acc, alias) => { - acc[`./${alias}`] = { - import: { - types: typesIndex.replace('index', alias), - default: esmIndex.replace('index', alias), - }, - require: { - types: typesIndex.replace('index', alias), - default: cjsIndex.replace('index', alias), - }, - }; - return acc; - }, {}); + // skip packages without exports otherwise consumers cannot import anything from the package + if (pkgJsonExports && typeof pkgJsonExports === 'object') { + // Remove all exports that only contain a single key '@grafana-app/source' + // as these will not resolve when validating packages with attw because the + // source code is not available in the tarball. + for (const [key, val] of Object.entries(pkgJsonExports)) { + if ( + val !== null && + typeof val === 'object' && + Object.keys(val).length === 1 && + Object.keys(val)[0] === '@grafana-app/source' + ) { + delete pkgJsonExports[key]; + } + } pkgJson.update({ - exports: { - ...pkgJson.content.exports, - ...additionalExports, - }, - files: [...pkgJson.content.files, ...aliasNames], + exports: pkgJsonExports, }); - await pkgJson.save(); - for await (const aliasName of aliasNames) { - await createAliasPackageJsonFiles(pkgJson.content, aliasName); - } + await pkgJson.save(); } } catch (e) { console.error(e); process.exit(1); } - -async function createAliasPackageJsonFiles(packageJsonContent, aliasName) { - const pkgName = `${packageJsonContent.name}/${aliasName}`; - try { - console.log(`📦 Writing alias package.json for ${pkgName}.`); - const pkgJsonPath = `${cwd}/${aliasName}`; - await mkdir(pkgJsonPath, { recursive: true }); - const pkgJson = await PackageJson.create(pkgJsonPath, { - data: { - name: pkgName, - types: `../dist/types/${aliasName}.d.ts`, - main: `../dist/cjs/${aliasName}.cjs`, - module: `../dist/esm/${aliasName}.mjs`, - }, - }); - await pkgJson.save(); - } catch (error) { - throw new Error(`Error generating package.json for ${pkgName}`, error); - } -} diff --git a/scripts/tsconfig.base.json b/scripts/tsconfig.base.json index 55eacdf4b61..152674b91e7 100644 --- a/scripts/tsconfig.base.json +++ b/scripts/tsconfig.base.json @@ -4,6 +4,7 @@ "alwaysStrict": true, "strict": true, "allowSyntheticDefaultImports": true, + "customConditions": ["@grafana-app/source"], "downlevelIteration": true, "esModuleInterop": true, "experimentalDecorators": true, diff --git a/scripts/validate-npm-packages.sh b/scripts/validate-npm-packages.sh index 92e871b6899..99474041107 100755 --- a/scripts/validate-npm-packages.sh +++ b/scripts/validate-npm-packages.sh @@ -17,7 +17,7 @@ for file in "$ARTIFACTS_DIR"/*.tgz; do fi # shellcheck disable=SC2086 - if ! yarn attw "$file" --ignore-rules "false-cjs" $ATTW_FLAGS; then + if ! NODE_OPTIONS="-C @grafana-app/source" yarn attw "$file" --ignore-rules "false-cjs" $ATTW_FLAGS; then echo "attw check failed for $file" echo "" failed_checks+=("$file - yarn attw") diff --git a/scripts/webpack/webpack.common.js b/scripts/webpack/webpack.common.js index e694b812100..f81c279d6a3 100644 --- a/scripts/webpack/webpack.common.js +++ b/scripts/webpack/webpack.common.js @@ -22,6 +22,7 @@ module.exports = { publicPath: 'public/build/', }, resolve: { + conditionNames: ['@grafana-app/source', '...'], extensions: ['.ts', '.tsx', '.es6', '.js', '.json', '.svg'], alias: { // some of data source plugins use global Prism object to add the language definition diff --git a/tsconfig.json b/tsconfig.json index 963aa84555c..46f7b630cb2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,9 +18,10 @@ } }, "ts-node": { + "swc": true, "compilerOptions": { "module": "ESNext", - "moduleResolution": "Node" + "moduleResolution": "Bundler" } }, "include": [ diff --git a/yarn.lock b/yarn.lock index 1c4d07dbb6e..e20676b04f0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8290,6 +8290,30 @@ __metadata: languageName: node linkType: hard +"@storybook/core@patch:@storybook/core@npm%3A8.6.2#~/.yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch": + version: 8.6.2 + resolution: "@storybook/core@patch:@storybook/core@npm%3A8.6.2#~/.yarn/patches/@storybook-core-npm-8.6.2-8c752112c0.patch::version=8.6.2&hash=f4cc1f" + dependencies: + "@storybook/theming": "npm:8.6.2" + better-opn: "npm:^3.0.2" + browser-assert: "npm:^1.2.1" + esbuild: "npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0" + esbuild-register: "npm:^3.5.0" + jsdoc-type-pratt-parser: "npm:^4.0.0" + process: "npm:^0.11.10" + recast: "npm:^0.23.5" + semver: "npm:^7.6.2" + util: "npm:^0.12.5" + ws: "npm:^8.2.3" + peerDependencies: + prettier: ^2 || ^3 + peerDependenciesMeta: + prettier: + optional: true + checksum: 10/cd95a51437135dd3c4333b14acefd528d8064b2cea7789f859ba80783c115c92ed4be51d4a7bd6236888fdd5f46f488a379e0c71bc1a712ffe6dc1353fb4e648 + languageName: node + linkType: hard + "@storybook/csf-plugin@npm:8.6.2": version: 8.6.2 resolution: "@storybook/csf-plugin@npm:8.6.2" From e29bb47e95006886b512792901a21c2e60536d2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Jim=C3=A9nez=20S=C3=A1nchez?= Date: Thu, 18 Dec 2025 13:16:57 +0100 Subject: [PATCH 04/10] Provisioning: Add Git Sync limitations warning and migrate resources checkbox (#115532) * Provisioning: Add Git Sync limitations warning and migrate resources checkbox - Update SynchronizeStep alert to use warning severity with comprehensive Git Sync limitations - Add conditional warnings for instance sync (permissions loss, alerts/library panels loss) - Add conditional warnings for folder sync (folder structure changes, manual cleanup needed) - Add "Migrate existing resources" checkbox for folder sync mode - Update useCreateSyncJob hook to handle migrateResources option for folder sync - Extract i18n translations for new strings * Simplify createSyncJob: calculate requiresMigration in caller - Remove syncTarget and migrateResources parameters from useCreateSyncJob hook - Calculate requiresMigration in SynchronizeStep based on sync target and checkbox value - Pass requiresMigration as parameter to createSyncJob function * Revert: Pass requiresMigration as hook parameter - Calculate requiresMigration in SynchronizeStep using useMemo - Pass requiresMigration to useCreateSyncJob hook - Remove parameter from createSyncJob function call * Revert "Revert: Pass requiresMigration as hook parameter" This reverts commit 97e3b7107d282d10a1be487d9186daaaf62f41aa. * Fix TypeScript errors in ProvisioningWizard - Remove requiresMigration from useCreateSyncJob call - Pass requiresMigration parameter to createSyncJob call - Remove unused Target import from SynchronizeStep * Show migrate resources checkbox for instance sync (checked and disabled) - Display checkbox for both instance and folder sync - For instance sync: checkbox is checked and disabled with explanation - For instance sync: automatically set migrateResources to true via useEffect - Update description to explain instance sync requires all resources to be managed * Extract i18n translations for instance-migrate-resources-description * Rename 'Synchronization options' to 'Options' * Update i18n translations: rename synchronization-options to options * Remove unnecessary conditional check for sync target * Add bodySmall variant to announcement banner TextLink * Move requiresMigration calculation logic into useResourceStats hook - Add migrateResources parameter to useResourceStats hook - Calculate final requiresMigration in hook based on sync target and checkbox value - Use watch instead of getValues to reactively get migrateResources value - Simplify startSynchronization to use requiresMigration from hook --- .../Wizard/ProvisioningWizard.tsx | 11 +- .../provisioning/Wizard/SynchronizeStep.tsx | 131 ++++++++++++++---- .../Wizard/hooks/useCreateSyncJob.ts | 5 +- .../Wizard/hooks/useResourceStats.ts | 19 ++- .../app/features/provisioning/Wizard/types.ts | 1 + public/locales/en-US/grafana.json | 13 +- 6 files changed, 135 insertions(+), 45 deletions(-) diff --git a/public/app/features/provisioning/Wizard/ProvisioningWizard.tsx b/public/app/features/provisioning/Wizard/ProvisioningWizard.tsx index 32829dba4c0..0950500a378 100644 --- a/public/app/features/provisioning/Wizard/ProvisioningWizard.tsx +++ b/public/app/features/provisioning/Wizard/ProvisioningWizard.tsx @@ -117,14 +117,9 @@ export const ProvisioningWizard = memo(function ProvisioningWizard({ const [repoName = '', repoType, syncTarget] = watch(['repositoryName', 'repository.type', 'repository.sync.target']); const [submitData] = useCreateOrUpdateRepository(repoName); const [deleteRepository] = useDeleteRepositoryMutation(); - const { - shouldSkipSync, - requiresMigration, - isLoading: isResourceStatsLoading, - } = useResourceStats(repoName, syncTarget); + const { shouldSkipSync, isLoading: isResourceStatsLoading } = useResourceStats(repoName, syncTarget); const { createSyncJob, isLoading: isCreatingSkipJob } = useCreateSyncJob({ repoName: repoName, - requiresMigration, setStepStatusInfo, }); @@ -274,8 +269,8 @@ export const ProvisioningWizard = memo(function ProvisioningWizard({ if (activeStep === 'bootstrap' && canSkipSync) { nextStepIndex = currentStepIndex + 2; // Skip to finish step - // Create a pull job to initialize the repository - const job = await createSyncJob(); + // No migration needed when skipping sync + const job = await createSyncJob(false); if (!job) { return; // Don't proceed if job creation fails } diff --git a/public/app/features/provisioning/Wizard/SynchronizeStep.tsx b/public/app/features/provisioning/Wizard/SynchronizeStep.tsx index 5842b313060..299fe775a0e 100644 --- a/public/app/features/provisioning/Wizard/SynchronizeStep.tsx +++ b/public/app/features/provisioning/Wizard/SynchronizeStep.tsx @@ -3,7 +3,7 @@ import { memo, useEffect, useState } from 'react'; import { useFormContext } from 'react-hook-form'; import { Trans, t } from '@grafana/i18n'; -import { Alert, Button, Field, Spinner, Stack, Text, TextLink } from '@grafana/ui'; +import { Alert, Button, Checkbox, Field, Spinner, Stack, Text, TextLink } from '@grafana/ui'; import { Job, useGetRepositoryStatusQuery } from 'app/api/clients/provisioning/v0alpha1'; import { JobStatus } from '../Job/JobStatus'; @@ -20,13 +20,17 @@ export interface SynchronizeStepProps { } export const SynchronizeStep = memo(function SynchronizeStep({ onCancel, isCancelling }: SynchronizeStepProps) { - const { watch } = useFormContext(); + const { watch, register } = useFormContext(); const { setStepStatusInfo } = useStepStatus(); - const [repoName = '', syncTarget] = watch(['repositoryName', 'repository.sync.target']); - const { requiresMigration } = useResourceStats(repoName, syncTarget); + const [repoName = '', syncTarget, migrateResources] = watch([ + 'repositoryName', + 'repository.sync.target', + 'migrate.migrateResources', + ]); + const { requiresMigration } = useResourceStats(repoName, syncTarget, migrateResources); + const { createSyncJob } = useCreateSyncJob({ repoName, - requiresMigration, setStepStatusInfo, }); const [job, setJob] = useState(); @@ -63,7 +67,7 @@ export const SynchronizeStep = memo(function SynchronizeStep({ onCancel, isCance const isButtonDisabled = hasError || (checked !== undefined && isRepositoryHealthy === false) || healthStatusNotReady; const startSynchronization = async () => { - const response = await createSyncJob(); + const response = await createSyncJob(requiresMigration); if (response) { setJob(response); } @@ -108,41 +112,108 @@ export const SynchronizeStep = memo(function SynchronizeStep({ onCancel, isCance )} {isRepositoryHealthy && ( -
    -
  • - - Resources can still be created, edited, or deleted during this process, but changes may not be exported. + + + + Please be aware of the following limitations. For more details, see the{' '} + + Git Sync documentation + + . -
  • -
  • - - Once provisioning is complete, resources will be marked as managed through external storage. - -
  • -
  • - - The duration of this process depends on the number of resources involved. - -
  • -
  • + +
      +
    • + + Resources can still be created, edited, or deleted during this process, but changes may not be + exported. + +
    • +
    • + + Alerts and library panels are not supported in provisioned folders. + +
    • +
    • + + Fine-grained permissions are not supported. Default permissions apply: Admin, Editor, and Viewer roles + are preserved with their standard access levels. + +
    • +
    • + + The duration of this process depends on the number of resources involved. + +
    • + {syncTarget === 'instance' && ( +
    • + + Existing alerts and library panels will be lost and will not be usable after migration. + +
    • + )} + {syncTarget === 'folder' && ( + <> +
    • + + When migrating existing dashboards, the folder structure will be replicated in the repository. + Original folders will be emptied of dashboards but may still contain alerts or library panels. + +
    • +
    • + + You may need to manually remove or manage original folders after migration. + +
    • + + )} +
    + Enterprise instance administrators can display an announcement banner to notify users that migration is in progress. See{' '} - + this guide {' '} for step-by-step instructions. -
  • -
+ +
)} + + Options + + + + Instance sync requires all resources to be managed. Existing resources will be migrated automatically. + + ) : ( + + Import existing dashboards from all folders into the new provisioned folder + + ) + } + /> + {healthStatusNotReady ? ( <> diff --git a/public/app/features/provisioning/Wizard/hooks/useCreateSyncJob.ts b/public/app/features/provisioning/Wizard/hooks/useCreateSyncJob.ts index 7e3c0c30874..1aaa7a250f0 100644 --- a/public/app/features/provisioning/Wizard/hooks/useCreateSyncJob.ts +++ b/public/app/features/provisioning/Wizard/hooks/useCreateSyncJob.ts @@ -5,14 +5,13 @@ import { StepStatusInfo } from '../types'; export interface UseCreateSyncJobParams { repoName: string; - requiresMigration: boolean; setStepStatusInfo?: (info: StepStatusInfo) => void; } -export function useCreateSyncJob({ repoName, requiresMigration, setStepStatusInfo }: UseCreateSyncJobParams) { +export function useCreateSyncJob({ repoName, setStepStatusInfo }: UseCreateSyncJobParams) { const [createJob, { isLoading }] = useCreateRepositoryJobsMutation(); - const createSyncJob = async () => { + const createSyncJob = async (requiresMigration: boolean) => { if (!repoName) { setStepStatusInfo?.({ status: 'error', diff --git a/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts b/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts index 7e2ffef178b..dd4b222cb19 100644 --- a/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts +++ b/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts @@ -100,7 +100,7 @@ function getResourceStats(files?: GetRepositoryFilesApiResponse, stats?: GetReso /** * Hook that provides resource statistics and sync logic */ -export function useResourceStats(repoName?: string, syncTarget?: RepositoryView['target']) { +export function useResourceStats(repoName?: string, syncTarget?: RepositoryView['target'], migrateResources?: boolean) { const resourceStatsQuery = useGetResourceStatsQuery(repoName ? undefined : skipToken); const filesQuery = useGetRepositoryFilesQuery(repoName ? { name: repoName } : skipToken); @@ -121,7 +121,22 @@ export function useResourceStats(repoName?: string, syncTarget?: RepositoryView[ }; }, [resourceStatsQuery.data]); - const requiresMigration = resourceCount > 0 && syncTarget === 'instance'; + // Calculate base requiresMigration: true if there are resources to migrate + const baseRequiresMigration = resourceCount > 0; + + // Calculate final requiresMigration based on sync target and user selection + // For instance sync: always use baseRequiresMigration (checkbox is disabled and always true) + // For folder sync: only migrate if user explicitly opts in via checkbox + const requiresMigration = useMemo(() => { + if (syncTarget === 'instance') { + return baseRequiresMigration; + } + if (syncTarget === 'folder') { + return migrateResources ?? false; + } + return baseRequiresMigration; + }, [syncTarget, baseRequiresMigration, migrateResources]); + const shouldSkipSync = (resourceCount === 0 || syncTarget === 'folder') && fileCount === 0; // Format display strings diff --git a/public/app/features/provisioning/Wizard/types.ts b/public/app/features/provisioning/Wizard/types.ts index 0dc2f001a43..34ee246da04 100644 --- a/public/app/features/provisioning/Wizard/types.ts +++ b/public/app/features/provisioning/Wizard/types.ts @@ -9,6 +9,7 @@ export type RepoType = RepositorySpec['type']; export interface MigrateFormData { history: boolean; identifier: boolean; + migrateResources?: boolean; } export interface WizardFormData { diff --git a/public/locales/en-US/grafana.json b/public/locales/en-US/grafana.json index 79b1f20b8e0..8c7bc95d901 100644 --- a/public/locales/en-US/grafana.json +++ b/public/locales/en-US/grafana.json @@ -12182,6 +12182,9 @@ "tooltip-unhealthy-repository": "Unable to pull an unhealthy repository" }, "synchronize-step": { + "instance-migrate-resources-description": "Instance sync requires all resources to be managed. Existing resources will be migrated automatically.", + "migrate-resources-description": "Import existing dashboards from all folders into the new provisioned folder", + "options": "Options", "repository-error": "Repository error", "repository-error-message": "Unable to check repository status. Please verify the repository configuration and try again.", "repository-unhealthy": "The repository cannot be synchronized. Cancel provisioning and try again once the issue has been resolved. See details below." @@ -12201,11 +12204,16 @@ }, "warning-title-default": "Warning", "wizard": { + "alert-intro": "Please be aware of the following limitations. For more details, see the <2>Git Sync documentation.", "alert-point-1": "Resources can still be created, edited, or deleted during this process, but changes may not be exported.", - "alert-point-2": "Once provisioning is complete, resources will be marked as managed through external storage.", "alert-point-3": "The duration of this process depends on the number of resources involved.", "alert-point-4": "Enterprise instance administrators can display an announcement banner to notify users that migration is in progress. See <2>this guide for step-by-step instructions.", - "alert-title": "Important: No data or configuration will be lost. Dashboards remain accessible during migration, but changes made during this process may not be exported.", + "alert-point-folder-cleanup": "You may need to manually remove or manage original folders after migration.", + "alert-point-folder-structure": "When migrating existing dashboards, the folder structure will be replicated in the repository. Original folders will be emptied of dashboards but may still contain alerts or library panels.", + "alert-point-instance-alerts": "Existing alerts and library panels will be lost and will not be usable after migration.", + "alert-point-permissions": "Fine-grained permissions are not supported. Default permissions apply: Admin, Editor, and Viewer roles are preserved with their standard access levels.", + "alert-point-unsupported": "Alerts and library panels are not supported in provisioned folders.", + "alert-title": "Important: Review Git Sync limitations before proceeding", "button-cancel": "Cancel", "button-cancelling": "Cancelling...", "button-next": "Finish", @@ -12223,6 +12231,7 @@ "step-finish": "Choose additional settings", "step-synchronize": "Synchronize with external storage", "sync-description": "Sync resources with external storage. After this one-time step, all future updates will be automatically saved to the repository and provisioned back into the instance.", + "sync-option-migrate-resources": "Migrate existing resources", "title-bootstrap": "Choose what to synchronize", "title-connect": "Connect to external storage", "title-finish": "Choose additional settings", From 241fd69e028f922bb38de6b46dd1388304b9e62e Mon Sep 17 00:00:00 2001 From: Andre Pereira Date: Thu, 18 Dec 2025 12:38:50 +0000 Subject: [PATCH 05/10] Trace View: Correctly handle span and service name in span filters (#115215) * Correctly handle span name and service name in trace view span filters * Consistency and fix test * i18n extract --- .../SpanFilters/SpanFilters.test.tsx | 262 -------------- .../SpanFilters/SpanFilters.tsx | 319 ------------------ .../SpanFilters/SpanFiltersTags.tsx | 202 ----------- .../useTraceAdHocFiltersController.ts | 15 - .../TraceView/components/constants/span.ts | 2 + .../components/utils/filter-spans.tsx | 20 +- .../explore/TraceView/useSearch.test.ts | 14 +- .../features/explore/TraceView/useSearch.ts | 5 +- .../features/explore/TraceView/utils/tags.ts | 15 + public/locales/en-US/grafana.json | 33 -- 10 files changed, 42 insertions(+), 845 deletions(-) delete mode 100644 public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.test.tsx delete mode 100644 public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.tsx delete mode 100644 public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFiltersTags.tsx diff --git a/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.test.tsx b/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.test.tsx deleted file mode 100644 index eba49425afb..00000000000 --- a/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.test.tsx +++ /dev/null @@ -1,262 +0,0 @@ -import { render, screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { useState } from 'react'; - -import { DEFAULT_SPAN_FILTERS } from 'app/features/explore/state/constants'; - -import { Trace } from '../../types/trace'; - -import { SpanFilters } from './SpanFilters'; - -const trace: Trace = { - traceID: '1ed38015486087ca', - spans: [ - { - traceID: '1ed38015486087ca', - spanID: '1ed38015486087ca', - operationName: 'Span0', - tags: [{ key: 'TagKey0', type: 'string', value: 'TagValue0' }], - kind: 'server', - statusCode: 2, - statusMessage: 'message', - instrumentationLibraryName: 'name', - instrumentationLibraryVersion: 'version', - traceState: 'state', - process: { - serviceName: 'Service0', - tags: [{ key: 'ProcessKey0', type: 'string', value: 'ProcessValue0' }], - }, - logs: [{ fields: [{ key: 'LogKey0', type: 'string', value: 'LogValue0' }] }], - }, - { - traceID: '1ed38015486087ca', - spanID: '2ed38015486087ca', - operationName: 'Span1', - tags: [{ key: 'TagKey1', type: 'string', value: 'TagValue1' }], - process: { - serviceName: 'Service1', - tags: [{ key: 'ProcessKey1', type: 'string', value: 'ProcessValue1' }], - }, - logs: [{ fields: [{ key: 'LogKey1', type: 'string', value: 'LogValue1' }] }], - }, - ], - processes: { - '1ed38015486087ca': { - serviceName: 'Service0', - tags: [], - }, - }, -} as unknown as Trace; - -describe('SpanFilters', () => { - let user: ReturnType; - const SpanFiltersWithProps = ({ showFilters = true, matches }: { showFilters?: boolean; matches?: Set }) => { - const [search, setSearch] = useState(DEFAULT_SPAN_FILTERS); - const props = { - trace: trace, - showSpanFilters: showFilters, - setShowSpanFilters: jest.fn(), - search, - setSearch, - spanFilterMatches: matches, - setFocusedSpanIdForSearch: jest.fn(), - datasourceType: 'tempo', - }; - - return ; - }; - - beforeEach(() => { - jest.useFakeTimers(); - // Need to use delay: null here to work with fakeTimers - // see https://github.com/testing-library/user-event/issues/833 - user = userEvent.setup({ delay: null }); - }); - - afterEach(() => { - jest.useRealTimers(); - }); - - it('should render', () => { - expect(() => render()).not.toThrow(); - }); - - it('should render filters', async () => { - render(); - - const serviceOperator = screen.getByLabelText('Select service name operator'); - const serviceValue = screen.getByLabelText('Select service name'); - const spanOperator = screen.getByLabelText('Select span name operator'); - const spanValue = screen.getByLabelText('Select span name'); - const fromOperator = screen.getByLabelText('Select min span operator'); - const fromValue = screen.getByLabelText('Select min span duration'); - const toOperator = screen.getByLabelText('Select max span operator'); - const toValue = screen.getByLabelText('Select max span duration'); - const tagKey = screen.getByLabelText('Select tag key'); - const tagOperator = screen.getByLabelText('Select tag operator'); - const tagSelectValue = screen.getByLabelText('Select tag value'); - - expect(serviceOperator).toBeInTheDocument(); - expect(getElemText(serviceOperator)).toBe('='); - expect(serviceValue).toBeInTheDocument(); - expect(spanOperator).toBeInTheDocument(); - expect(getElemText(spanOperator)).toBe('='); - expect(spanValue).toBeInTheDocument(); - expect(fromOperator).toBeInTheDocument(); - expect(getElemText(fromOperator)).toBe('>'); - expect(fromValue).toBeInTheDocument(); - expect(toOperator).toBeInTheDocument(); - expect(getElemText(toOperator)).toBe('<'); - expect(toValue).toBeInTheDocument(); - expect(tagKey).toBeInTheDocument(); - expect(tagOperator).toBeInTheDocument(); - expect(getElemText(tagOperator)).toBe('='); - expect(tagSelectValue).toBeInTheDocument(); - - await user.click(serviceValue); - jest.advanceTimersByTime(1000); - await waitFor(() => { - expect(screen.getByText('Service0')).toBeInTheDocument(); - expect(screen.getByText('Service1')).toBeInTheDocument(); - }); - await user.click(spanValue); - jest.advanceTimersByTime(1000); - await waitFor(() => { - expect(screen.getByText('Span0')).toBeInTheDocument(); - expect(screen.getByText('Span1')).toBeInTheDocument(); - }); - await user.click(tagOperator); - jest.advanceTimersByTime(1000); - await waitFor(() => { - expect(screen.getByText('!~')).toBeInTheDocument(); - expect(screen.getByText('=~')).toBeInTheDocument(); - expect(screen.getByText('!~')).toBeInTheDocument(); - }); - await user.click(tagKey); - jest.advanceTimersByTime(1000); - await waitFor(() => { - expect(screen.getByText('TagKey0')).toBeInTheDocument(); - expect(screen.getByText('TagKey1')).toBeInTheDocument(); - expect(screen.getByText('kind')).toBeInTheDocument(); - expect(screen.getByText('ProcessKey0')).toBeInTheDocument(); - expect(screen.getByText('ProcessKey1')).toBeInTheDocument(); - expect(screen.getByText('LogKey0')).toBeInTheDocument(); - expect(screen.getByText('LogKey1')).toBeInTheDocument(); - expect(screen.getByPlaceholderText('Find...')).toBeInTheDocument(); - }); - }); - - it('should update filters', async () => { - render(); - const serviceValue = screen.getByLabelText('Select service name'); - const spanValue = screen.getByLabelText('Select span name'); - const tagKey = screen.getByLabelText('Select tag key'); - const tagOperator = screen.getByLabelText('Select tag operator'); - const tagValue = screen.getByLabelText('Select tag value'); - - expect(getElemText(serviceValue)).toBe('All service names'); - await selectAndCheckValue(user, serviceValue, 'Service0'); - expect(getElemText(spanValue)).toBe('All span names'); - await selectAndCheckValue(user, spanValue, 'Span0'); - - await user.click(tagValue); - jest.advanceTimersByTime(1000); - await waitFor(() => expect(screen.getByText('No options found')).toBeInTheDocument()); - - expect(getElemText(tagKey)).toBe('Select tag'); - await selectAndCheckValue(user, tagKey, 'TagKey0'); - expect(getElemText(tagValue)).toBe('Select value'); - await selectAndCheckValue(user, tagValue, 'TagValue0'); - expect(screen.queryByLabelText('Input tag value')).toBeNull(); - await selectAndCheckValue(user, tagOperator, '=~'); - expect(screen.getByLabelText('Input tag value')).toBeInTheDocument(); - }); - - it('should order tag filters', async () => { - render(); - const tagKey = screen.getByLabelText('Select tag key'); - - await user.click(tagKey); - jest.advanceTimersByTime(1000); - await waitFor(() => { - const container = screen.getByText('TagKey0').parentElement?.parentElement?.parentElement; - expect(container?.childNodes[1].textContent).toBe('ProcessKey0'); - expect(container?.childNodes[2].textContent).toBe('ProcessKey1'); - expect(container?.childNodes[3].textContent).toBe('TagKey0'); - expect(container?.childNodes[4].textContent).toBe('TagKey1'); - expect(container?.childNodes[5].textContent).toBe('id'); - expect(container?.childNodes[6].textContent).toBe('kind'); - expect(container?.childNodes[7].textContent).toBe('library.name'); - expect(container?.childNodes[8].textContent).toBe('library.version'); - expect(container?.childNodes[9].textContent).toBe('status'); - expect(container?.childNodes[10].textContent).toBe('status.message'); - expect(container?.childNodes[11].textContent).toBe('trace.state'); - expect(container?.childNodes[12].textContent).toBe('LogKey0'); - expect(container?.childNodes[13].textContent).toBe('LogKey1'); - }); - }); - - it('should only show add/remove tag when necessary', async () => { - render(); - expect(screen.queryAllByLabelText('Add tag').length).toBe(0); // not filled in the default tag, so no need to add another one - expect(screen.queryAllByLabelText('Remove tag').length).toBe(0); // mot filled in the default tag, so no values to remove - expect(screen.getAllByLabelText('Select tag key').length).toBe(1); - - await selectAndCheckValue(user, screen.getByLabelText('Select tag key'), 'TagKey0'); - expect(screen.getAllByLabelText('Add tag').length).toBe(1); - expect(screen.getAllByLabelText('Remove tag').length).toBe(1); - - await user.click(screen.getByLabelText('Add tag')); - jest.advanceTimersByTime(1000); - expect(screen.queryAllByLabelText('Add tag').length).toBe(0); // not filled in the new tag, so no need to add another one - expect(screen.getAllByLabelText('Remove tag').length).toBe(2); // one for each tag - expect(screen.getAllByLabelText('Select tag key').length).toBe(2); - - await user.click(screen.getAllByLabelText('Remove tag')[1]); - jest.advanceTimersByTime(1000); - expect(screen.queryAllByLabelText('Add tag').length).toBe(1); // filled in the default tag, so can add another one - expect(screen.queryAllByLabelText('Remove tag').length).toBe(1); // filled in the default tag, so can remove values - expect(screen.getAllByLabelText('Select tag key').length).toBe(1); - - await user.click(screen.getAllByLabelText('Remove tag')[0]); - jest.advanceTimersByTime(1000); - expect(screen.queryAllByLabelText('Add tag').length).toBe(0); // not filled in the default tag, so no need to add another one - expect(screen.queryAllByLabelText('Remove tag').length).toBe(0); // mot filled in the default tag, so no values to remove - expect(screen.getAllByLabelText('Select tag key').length).toBe(1); - }); - - it('should allow adding/removing tags', async () => { - render(); - expect(screen.getAllByLabelText('Select tag key').length).toBe(1); - const tagKey = screen.getByLabelText('Select tag key'); - await selectAndCheckValue(user, tagKey, 'TagKey0'); - - await user.click(screen.getByLabelText('Add tag')); - jest.advanceTimersByTime(1000); - expect(screen.getAllByLabelText('Select tag key').length).toBe(2); - - await user.click(screen.getAllByLabelText('Remove tag')[0]); - jest.advanceTimersByTime(1000); - expect(screen.getAllByLabelText('Select tag key').length).toBe(1); - }); - - it('renders buttons when span filters is collapsed', async () => { - render(); - expect(screen.queryByRole('button', { name: 'Next result button' })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Prev result button' })).toBeInTheDocument(); - }); -}); - -const selectAndCheckValue = async (user: ReturnType, elem: HTMLElement, text: string) => { - await user.click(elem); - jest.advanceTimersByTime(1000); - await waitFor(() => expect(screen.getByText(text)).toBeInTheDocument()); - - await user.click(screen.getByText(text)); - jest.advanceTimersByTime(1000); - expect(screen.getByText(text)).toBeInTheDocument(); -}; - -const getElemText = (elem: HTMLElement) => { - return elem.parentElement?.previousSibling?.textContent; -}; diff --git a/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.tsx b/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.tsx deleted file mode 100644 index eda085bc412..00000000000 --- a/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFilters.tsx +++ /dev/null @@ -1,319 +0,0 @@ -// Copyright (c) 2017 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import { css } from '@emotion/css'; -import React, { useState, useEffect, memo, useCallback, useRef } from 'react'; - -import { GrafanaTheme2, TraceSearchProps, SelectableValue, toOption } from '@grafana/data'; -import { Trans, t } from '@grafana/i18n'; -import { IntervalInput } from '@grafana/o11y-ds-frontend'; -import { Collapse, Icon, InlineField, InlineFieldRow, Select, Stack, Tooltip, useStyles2 } from '@grafana/ui'; - -import { DEFAULT_SPAN_FILTERS } from '../../../../state/constants'; -import { getTraceServiceNames, getTraceSpanNames } from '../../../utils/tags'; -import SearchBarInput from '../../common/SearchBarInput'; -import { Trace } from '../../types/trace'; -import NextPrevResult from '../SearchBar/NextPrevResult'; -import TracePageSearchBar from '../SearchBar/TracePageSearchBar'; - -import { SpanFiltersTags } from './SpanFiltersTags'; - -export type SpanFilterProps = { - trace: Trace; - search: TraceSearchProps; - setSearch: (newSearch: TraceSearchProps) => void; - showSpanFilters: boolean; - setShowSpanFilters: (isOpen: boolean) => void; - setFocusedSpanIdForSearch: React.Dispatch>; - spanFilterMatches: Set | undefined; - datasourceType: string; -}; - -export const SpanFilters = memo((props: SpanFilterProps) => { - const { - trace, - search, - setSearch, - showSpanFilters, - setShowSpanFilters, - setFocusedSpanIdForSearch, - spanFilterMatches, - datasourceType, - } = props; - const styles = { ...useStyles2(getStyles) }; - const [serviceNames, setServiceNames] = useState>>(); - const [spanNames, setSpanNames] = useState>>(); - const [focusedSpanIndexForSearch, setFocusedSpanIndexForSearch] = useState(-1); - const [tagKeys, setTagKeys] = useState>>(); - const [tagValues, setTagValues] = useState<{ [key: string]: Array> }>({}); - const prevTraceIdRef = useRef(); - - const durationRegex = /^\d+(?:\.\d)?\d*(?:ns|us|µs|ms|s|m|h)$/; - - const clear = useCallback(() => { - setServiceNames(undefined); - setSpanNames(undefined); - setTagKeys(undefined); - setTagValues({}); - setSearch(DEFAULT_SPAN_FILTERS); - }, [setSearch]); - - useEffect(() => { - // Only clear filters when trace ID actually changes (not on initial mount) - const currentTraceId = trace?.traceID; - - const traceHasChanged = prevTraceIdRef.current && prevTraceIdRef.current !== currentTraceId; - - if (traceHasChanged) { - clear(); - } - - prevTraceIdRef.current = currentTraceId; - }, [clear, trace]); - - const setShowSpanFilterMatchesOnly = useCallback( - (showMatchesOnly: boolean) => { - setSearch({ ...search, matchesOnly: showMatchesOnly }); - }, - [search, setSearch] - ); - - if (!trace) { - return null; - } - - const setSpanFiltersSearch = (spanSearch: TraceSearchProps) => { - setFocusedSpanIndexForSearch(-1); - setFocusedSpanIdForSearch(''); - setSearch(spanSearch); - }; - - const getServiceNames = () => { - if (!serviceNames) { - setServiceNames(getTraceServiceNames(trace).map(toOption)); - } - }; - - const getSpanNames = () => { - if (!spanNames) { - setSpanNames(getTraceSpanNames(trace).map(toOption)); - } - }; - - const collapseLabel = ( - <> - - - Span Filters - - - - - {!showSpanFilters && ( -
- -
- )} - - ); - - return ( -
- - - - - setSpanFiltersSearch({ ...search, serviceName: v?.value || '' })} - onOpenMenu={getServiceNames} - options={serviceNames || (search.serviceName ? [search.serviceName].map(toOption) : [])} - placeholder={t('explore.span-filters.placeholder-all-service-names', 'All service names')} - value={search.serviceName || null} - defaultValue={search.serviceName || null} - /> - - - { - setSpanFiltersSearch({ ...search, query: v, matchesOnly: v !== '' }); - }} - value={search.query || ''} - /> - - - - - setSpanFiltersSearch({ ...search, spanName: v?.value || '' })} - onOpenMenu={getSpanNames} - options={spanNames || (search.spanName ? [search.spanName].map(toOption) : [])} - placeholder={t('explore.span-filters.placeholder-all-span-names', 'All span names')} - value={search.spanName || null} - /> - - - - - - - setSpanFiltersSearch({ ...search, toOperator: v.value! })} - options={[toOption('<'), toOption('<=')]} - value={search.toOperator} - /> - setSpanFiltersSearch({ ...search, to: val })} - isInvalidError="Invalid duration" - // eslint-disable-next-line @grafana/i18n/no-untranslated-strings - placeholder="e.g. 100ms, 1.2s" - width={18} - value={search.to || ''} - validationRegex={durationRegex} - /> - - - - - - - - - - - -
- ); -}); - -SpanFilters.displayName = 'SpanFilters'; - -const getStyles = (theme: GrafanaTheme2) => ({ - container: css({ - label: 'SpanFilters', - margin: `0.5em 0 -${theme.spacing(1)} 0`, - zIndex: 5, - - '& > div': { - borderLeft: 'none', - borderRight: 'none', - }, - }), - collapseLabel: css({ - svg: { - color: '#aaa', - margin: '-2px 0 0 10px', - }, - }), - flexContainer: css({ - display: 'flex', - justifyContent: 'space-between', - }), - intervalInput: css({ - margin: '0 -4px 0 0', - }), - tagsRow: css({ - margin: '-4px 0 0 0', - }), - nextPrevResult: css({ - flex: 1, - alignItems: 'center', - display: 'flex', - justifyContent: 'flex-end', - marginRight: theme.spacing(1), - }), -}); diff --git a/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFiltersTags.tsx b/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFiltersTags.tsx deleted file mode 100644 index 3cf2d5f8488..00000000000 --- a/public/app/features/explore/TraceView/components/TracePageHeader/SpanFilters/SpanFiltersTags.tsx +++ /dev/null @@ -1,202 +0,0 @@ -import { css } from '@emotion/css'; -import React from 'react'; -import { useMount } from 'react-use'; - -import { GrafanaTheme2, SelectableValue, toOption, TraceSearchProps, TraceSearchTag } from '@grafana/data'; -import { t } from '@grafana/i18n'; -import { AccessoryButton } from '@grafana/plugin-ui'; -import { Input, Select, Stack, useStyles2 } from '@grafana/ui'; - -import { randomId } from '../../../../state/constants'; -import { getTraceTagKeys, getTraceTagValues } from '../../../utils/tags'; -import { Trace } from '../../types/trace'; - -interface Props { - search: TraceSearchProps; - setSearch: (search: TraceSearchProps) => void; - trace: Trace; - tagKeys?: Array>; - setTagKeys: React.Dispatch> | undefined>>; - tagValues: Record>>; - setTagValues: React.Dispatch> }>>; -} - -export const SpanFiltersTags = ({ search, trace, setSearch, tagKeys, setTagKeys, tagValues, setTagValues }: Props) => { - const styles = { ...useStyles2(getStyles) }; - - const getTagKeys = () => { - if (!tagKeys) { - setTagKeys(getTraceTagKeys(trace).map(toOption)); - } - }; - - const getTagValues = (key: string) => { - return getTraceTagValues(trace, key).map(toOption); - }; - - useMount(() => { - if (search.tags) { - search.tags.forEach((tag) => { - if (tag.key) { - setTagValues({ - ...tagValues, - [tag.id]: getTagValues(tag.key), - }); - } - }); - } - }); - - const onTagChange = (tag: TraceSearchTag, v: SelectableValue) => { - setSearch({ - ...search, - tags: search.tags?.map((x) => { - return x.id === tag.id ? { ...x, key: v?.value || '', value: undefined } : x; - }), - }); - - const loadTagValues = async () => { - if (v?.value) { - setTagValues({ - ...tagValues, - [tag.id]: getTagValues(v.value), - }); - } else { - // removed value - const updatedValues = { ...tagValues }; - if (updatedValues[tag.id]) { - delete updatedValues[tag.id]; - } - setTagValues(updatedValues); - } - }; - loadTagValues(); - }; - - const addTag = () => { - const tag = { - id: randomId(), - operator: '=', - }; - setSearch({ ...search, tags: [...search.tags, tag] }); - }; - - const removeTag = (id: string) => { - let tags = search.tags.filter((tag) => { - return tag.id !== id; - }); - if (tags.length === 0) { - tags = [ - { - id: randomId(), - operator: '=', - }, - ]; - } - setSearch({ ...search, tags: tags }); - }; - - return ( -
- {search.tags?.map((tag, i) => ( -
- -
- { - setSearch({ - ...search, - tags: search.tags?.map((x) => { - return x.id === tag.id ? { ...x, operator: v.value! } : x; - }), - }); - }} - options={[toOption('='), toOption('!='), toOption('=~'), toOption('!~')]} - value={tag.operator} - /> -
- - - {(tag.operator === '=' || tag.operator === '!=') && ( - { - setSearch({ - ...search, - tags: search.tags?.map((x) => { - return x.id === tag.id ? { ...x, value: v?.currentTarget?.value || '' } : x; - }), - }); - }} - placeholder={t('explore.span-filters-tags.placeholder-tag-value', 'Tag value')} - width={18} - value={tag.value || ''} - /> - )} - - {(tag.key || tag.value || search.tags.length > 1) && ( - removeTag(tag.id)} - tooltip={t('explore.span-filters-tags.tooltip-remove-tag', 'Remove tag')} - /> - )} - {(tag.key || tag.value) && i === search.tags.length - 1 && ( - - - - )} -
-
- ))} -
- ); -}; - -const getStyles = (theme: GrafanaTheme2) => ({ - addTag: css({ - marginLeft: theme.spacing(1), - }), - tagValues: css({ - maxWidth: '200px', - }), -}); diff --git a/public/app/features/explore/TraceView/components/TracePageHeader/useTraceAdHocFiltersController.ts b/public/app/features/explore/TraceView/components/TracePageHeader/useTraceAdHocFiltersController.ts index 8615c446294..c5286297087 100644 --- a/public/app/features/explore/TraceView/components/TracePageHeader/useTraceAdHocFiltersController.ts +++ b/public/app/features/explore/TraceView/components/TracePageHeader/useTraceAdHocFiltersController.ts @@ -1,18 +1,3 @@ -// Copyright (c) 2025 Grafana Labs -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - import { useMemo, useState } from 'react'; import { TraceSearchProps } from '@grafana/data'; diff --git a/public/app/features/explore/TraceView/components/constants/span.ts b/public/app/features/explore/TraceView/components/constants/span.ts index 8d2fb1e5052..2e4d04be71b 100644 --- a/public/app/features/explore/TraceView/components/constants/span.ts +++ b/public/app/features/explore/TraceView/components/constants/span.ts @@ -5,3 +5,5 @@ export const LIBRARY_NAME = 'library.name'; export const LIBRARY_VERSION = 'library.version'; export const TRACE_STATE = 'trace.state'; export const ID = 'id'; +export const SPAN_NAME = 'span.name'; +export const SERVICE_NAME = 'service.name'; diff --git a/public/app/features/explore/TraceView/components/utils/filter-spans.tsx b/public/app/features/explore/TraceView/components/utils/filter-spans.tsx index d03016dab78..69c42ee2e8f 100644 --- a/public/app/features/explore/TraceView/components/utils/filter-spans.tsx +++ b/public/app/features/explore/TraceView/components/utils/filter-spans.tsx @@ -16,7 +16,17 @@ import { SpanStatusCode } from '@opentelemetry/api'; import { SelectableValue, TraceKeyValuePair, TraceSearchProps, TraceSearchTag } from '@grafana/data'; -import { KIND, LIBRARY_NAME, LIBRARY_VERSION, STATUS, STATUS_MESSAGE, TRACE_STATE, ID } from '../constants/span'; +import { + KIND, + LIBRARY_NAME, + LIBRARY_VERSION, + STATUS, + STATUS_MESSAGE, + TRACE_STATE, + ID, + SPAN_NAME, + SERVICE_NAME, +} from '../constants/span'; import TNil from '../types/TNil'; import { TraceSpan, CriticalPathSection } from '../types/trace'; @@ -46,13 +56,13 @@ const getAdhocFilterMatches = (spans: TraceSpan[], adhocFilters: Array { // Check that adhoc filter was created expect(result.current.search.adhocFilters).toHaveLength(1); expect(result.current.search.adhocFilters?.[0]).toMatchObject({ - key: 'serviceName', + key: 'service.name', operator: '=', value: 'my-service', }); @@ -120,7 +120,7 @@ describe('useSearch', () => { // Check that adhoc filter was created expect(result.current.search.adhocFilters).toHaveLength(1); expect(result.current.search.adhocFilters?.[0]).toMatchObject({ - key: 'spanName', + key: 'span.name', operator: '!=', value: 'my-operation', }); @@ -195,13 +195,13 @@ describe('useSearch', () => { // Verify each filter const filters = result.current.search.adhocFilters || []; - expect(filters.find((f) => f.key === 'serviceName')).toMatchObject({ - key: 'serviceName', + expect(filters.find((f) => f.key === 'service.name')).toMatchObject({ + key: 'service.name', operator: '=', value: 'my-service', }); - expect(filters.find((f) => f.key === 'spanName')).toMatchObject({ - key: 'spanName', + expect(filters.find((f) => f.key === 'span.name')).toMatchObject({ + key: 'span.name', operator: '!=', value: 'my-operation', }); @@ -306,7 +306,7 @@ describe('useSearch', () => { expect(result.current.search.adhocFilters).toHaveLength(5); const filters = result.current.search.adhocFilters || []; - expect(filters.find((f) => f.key === 'serviceName')?.operator).toBe('!='); + expect(filters.find((f) => f.key === 'service.name')?.operator).toBe('!='); expect(filters.find((f) => f.key === 'tag1')?.operator).toBe('='); expect(filters.find((f) => f.key === 'tag2')?.operator).toBe('!='); expect(filters.find((f) => f.key === 'tag3')?.operator).toBe('=~'); diff --git a/public/app/features/explore/TraceView/useSearch.ts b/public/app/features/explore/TraceView/useSearch.ts index 9deb191a8d3..086866b87fb 100644 --- a/public/app/features/explore/TraceView/useSearch.ts +++ b/public/app/features/explore/TraceView/useSearch.ts @@ -7,6 +7,7 @@ import { useDispatch, useSelector } from 'app/types/store'; import { DEFAULT_SPAN_FILTERS, randomId } from '../state/constants'; import { changePanelState } from '../state/explorePane'; +import { SPAN_NAME, SERVICE_NAME } from './components/constants/span'; import { TraceSpan, CriticalPathSection } from './components/types/trace'; import { filterSpans } from './components/utils/filter-spans'; @@ -25,7 +26,7 @@ export function migrateToAdhocFilters(search: TraceSearchProps): TraceSearchProp // Migrate serviceName if (search.serviceName && search.serviceName.trim() !== '') { adhocFilters.push({ - key: 'serviceName', + key: SERVICE_NAME, operator: search.serviceNameOperator || '=', value: search.serviceName, }); @@ -34,7 +35,7 @@ export function migrateToAdhocFilters(search: TraceSearchProps): TraceSearchProp // Migrate spanName if (search.spanName && search.spanName.trim() !== '') { adhocFilters.push({ - key: 'spanName', + key: SPAN_NAME, operator: search.spanNameOperator || '=', value: search.spanName, }); diff --git a/public/app/features/explore/TraceView/utils/tags.ts b/public/app/features/explore/TraceView/utils/tags.ts index 293326e359e..38ae3c92148 100644 --- a/public/app/features/explore/TraceView/utils/tags.ts +++ b/public/app/features/explore/TraceView/utils/tags.ts @@ -9,6 +9,8 @@ import { STATUS, STATUS_MESSAGE, TRACE_STATE, + SPAN_NAME, + SERVICE_NAME, } from '../components/constants/span'; import { Trace } from '../components/types/trace'; @@ -37,6 +39,11 @@ export const getTraceTagKeys = (trace: Trace) => { span.process.tags.forEach((tag) => { keys.push(tag.key); }); + + if (span.process.serviceName) { + keys.push(SERVICE_NAME); + } + if (span.logs !== null) { span.logs.forEach((log) => { log.fields.forEach((field) => { @@ -63,6 +70,9 @@ export const getTraceTagKeys = (trace: Trace) => { if (span.traceState) { keys.push(TRACE_STATE); } + if (span.operationName) { + keys.push(SPAN_NAME); + } keys.push(ID); }); keys = uniq(keys).sort(); @@ -93,6 +103,11 @@ export const getTraceTagValues = (trace: Trace, key: string) => { } switch (key) { + case SPAN_NAME: + if (span.operationName) { + values.push(span.operationName); + } + break; case KIND: if (span.kind) { values.push(span.kind); diff --git a/public/locales/en-US/grafana.json b/public/locales/en-US/grafana.json index 8c7bc95d901..25ad73abe1a 100644 --- a/public/locales/en-US/grafana.json +++ b/public/locales/en-US/grafana.json @@ -7641,39 +7641,6 @@ }, "share-span": "Share" }, - "span-filters": { - "aria-label-select-max-span-operator": "Select max span operator", - "aria-label-select-min-span-operator": "Select min span operator", - "aria-label-select-service-name": "Select service name", - "aria-label-select-service-name-operator": "Select service name operator", - "aria-label-select-span-name": "Select span name", - "aria-label-select-span-name-operator": "Select span name operator", - "ariaLabel-select-max-span-duration": "Select max span duration", - "ariaLabel-select-min-span-duration": "Select min span duration", - "label-collapse": "Span Filters", - "label-duration": "Duration", - "label-service-name": "Service name", - "label-span-name": "Span name", - "label-tags": "Tags", - "placeholder-all-service-names": "All service names", - "placeholder-all-span-names": "All span names", - "tooltip-collapse": "Filter your spans below. You can continue to apply filters until you have narrowed down your resulting spans to the select few you are most interested in.", - "tooltip-duration": "Filter by duration. Accepted units are {{units}}", - "tooltip-tags": "Filter by tags, process tags or log fields in your spans." - }, - "span-filters-tags": { - "aria-label-add-tag": "Add tag", - "aria-label-input-tag-value": "Input tag value", - "aria-label-remove-tag": "Remove tag", - "aria-label-select-tag-key": "Select tag key", - "aria-label-select-tag-operator": "Select tag operator", - "aria-label-select-tag-value": "Select tag value", - "placeholder-select-tag": "Select tag", - "placeholder-select-value": "Select value", - "placeholder-tag-value": "Tag value", - "tooltip-add-tag": "Add tag", - "tooltip-remove-tag": "Remove tag" - }, "span-flame-graph": { "flame-graph": "Flame graph" }, From 90af2c3c3b6c28e66506e0e67f7acd77959efbe9 Mon Sep 17 00:00:00 2001 From: Rafael Bortolon Paulovic Date: Thu, 18 Dec 2025 14:11:47 +0100 Subject: [PATCH 06/10] fix(dashboard): panic on nil logger on dashboard accessor (#115545) fix(dashboard): fix panic on log --- pkg/registry/apis/dashboard/legacy/sql_dashboards.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/registry/apis/dashboard/legacy/sql_dashboards.go b/pkg/registry/apis/dashboard/legacy/sql_dashboards.go index 0a496e4667b..0b7ffa04ea4 100644 --- a/pkg/registry/apis/dashboard/legacy/sql_dashboards.go +++ b/pkg/registry/apis/dashboard/legacy/sql_dashboards.go @@ -113,6 +113,7 @@ func ProvideMigratorDashboardAccessor( dashboardPermissionSvc: nil, // not needed for migration libraryPanelSvc: nil, // not needed for migration accessControl: accessControl, + log: log.New("legacy.dashboard.migrator.accessor"), } } @@ -136,6 +137,7 @@ func NewDashboardSQLAccess(sql legacysql.LegacyDatabaseProvider, dashboardPermissionSvc: dashboardPermissionSvc, libraryPanelSvc: libraryPanelSvc, accessControl: accessControl, + log: log.New("legacy.dashboard.accessor"), } } From 14ef6ca4eb265bf19fddf669ab5d7c982116b00d Mon Sep 17 00:00:00 2001 From: Mariell Hoversholm Date: Thu, 18 Dec 2025 14:23:07 +0100 Subject: [PATCH 07/10] docs: remove SECURITY.md (#115549) --- .github/CODEOWNERS | 1 - SECURITY.md | 29 ----------------------------- 2 files changed, 30 deletions(-) delete mode 100644 SECURITY.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7ef6be6644c..4cac8f6dd81 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -24,7 +24,6 @@ /NOTICE.md @torkelo /README.md @grafana/docs-grafana /ROADMAP.md @torkelo -/SECURITY.md @grafana/security-team /SUPPORT.md @torkelo /WORKFLOW.md @torkelo /contribute/ @grafana/grafana-community-support diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 42c58f9cd67..00000000000 --- a/SECURITY.md +++ /dev/null @@ -1,29 +0,0 @@ -# Reporting security issues - -If you think you have found a security vulnerability, we have two routes for reporting security issues. - -Important: Whichever route you choose, we ask you to not disclose the vulnerability before it has been fixed and announced, unless you received a response from the Grafana Labs security team that you can do so. - -[Full guidance on reporting a security issue can be found here](https://grafana.com/legal/report-a-security-issue/). - -This product is in scope for our Bug Bounty Program. To submit a vulnerability report, please visit [Grafana Labs Bug Bounty page](https://app.intigriti.com/programs/grafanalabs/grafanaossbbp/detail) and follow the instructions provided. Our security team will review your submission and get back to you as soon as possible. - ---- - -For products and services outside the scope of our bug bounty program, or if you do not wish to receive a bounty, you can report issues directly to us via email at security@grafana.com. This address can be used for all of Grafana Labs’ open source and commercial products (including but not limited to Grafana, Grafana Cloud, Grafana Enterprise, and grafana.com). - -Please encrypt your message to us; please use our PGP key. The key fingerprint is: - -225E 6A9B BB15 A37E 95EB 6312 C66A 51CC B44C 27E0 - -The key is available from [keyserver.ubuntu.com](https://keyserver.ubuntu.com/pks/lookup?search=0x225E6A9BBB15A37E95EB6312C66A51CCB44C27E0&fingerprint=on&op=index). - -Grafana Labs will send you a response indicating the next steps in handling your report. After the initial reply to your report, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance. - -**Important:** We ask you to not disclose the vulnerability before it have been fixed and announced, unless you received a response from the Grafana Labs security team that you can do so. - -## Security announcements - -We will post a summary, remediation, and mitigation details for any patch containing security fixes on the Grafana blog. The security announcement blog posts will be tagged with the [security tag](https://grafana.com/tags/security/). - -You can also track security announcements via the [RSS feed](https://grafana.com/tags/security/index.xml). From 39fa6559ee01a5250b9fbc15c63ba63215af9bf3 Mon Sep 17 00:00:00 2001 From: Kevin Minehart <5140827+kminehart@users.noreply.github.com> Date: Thu, 18 Dec 2025 14:46:24 +0100 Subject: [PATCH 08/10] CI: Remove the default alpine & ubuntu versions so that the ones in Dockerfile (#115544) * Remove the default alpine & ubuntu versions so that the ones in Dockerfile are used * set default to just 'alpine' or 'ubuntu' * use defaults instead --- .github/actions/build-package/action.yml | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/.github/actions/build-package/action.yml b/.github/actions/build-package/action.yml index dd5aaa13650..978c6645240 100644 --- a/.github/actions/build-package/action.yml +++ b/.github/actions/build-package/action.yml @@ -82,14 +82,6 @@ inputs: description: Docker registry of produced images default: docker.io required: false - ubuntu-base: - type: string - default: 'ubuntu:22.04' - required: false - alpine-base: - type: string - default: 'alpine:3.22' - required: false outputs: dist-dir: description: Directory where artifacts are placed @@ -134,13 +126,11 @@ runs: UBUNTU_TAG_FORMAT: ${{ inputs.docker-tag-format-ubuntu }} CHECKSUM: ${{ inputs.checksum }} VERIFY: ${{ inputs.verify }} - ALPINE_BASE: ${{ inputs.alpine-base }} - UBUNTU_BASE: ${{ inputs.ubuntu-base }} with: verb: run dagger-flags: --verbose=0 version: 0.18.8 - args: go run -C ${GRAFANA_PATH} ./pkg/build/cmd artifacts --artifacts ${ARTIFACTS} --grafana-dir=${GRAFANA_PATH} --alpine-base=${ALPINE_BASE} --ubuntu-base=${UBUNTU_BASE} --enterprise-dir=${ENTERPRISE_PATH} --version=${VERSION} --patches-repo=${PATCHES_REPO} --patches-ref=${PATCHES_REF} --patches-path=${PATCHES_PATH} --build-id=${BUILD_ID} --tag-format="${TAG_FORMAT}" --ubuntu-tag-format="${UBUNTU_TAG_FORMAT}" --org=${DOCKER_ORG} --registry=${DOCKER_REGISTRY} --checksum=${CHECKSUM} --verify=${VERIFY} > $OUTFILE + args: go run -C ${GRAFANA_PATH} ./pkg/build/cmd artifacts --artifacts ${ARTIFACTS} --grafana-dir=${GRAFANA_PATH} --enterprise-dir=${ENTERPRISE_PATH} --version=${VERSION} --patches-repo=${PATCHES_REPO} --patches-ref=${PATCHES_REF} --patches-path=${PATCHES_PATH} --build-id=${BUILD_ID} --tag-format="${TAG_FORMAT}" --ubuntu-tag-format="${UBUNTU_TAG_FORMAT}" --org=${DOCKER_ORG} --registry=${DOCKER_REGISTRY} --checksum=${CHECKSUM} --verify=${VERIFY} > $OUTFILE - id: output shell: bash env: From 5c7cdabaa39c26b4024d114f565d05077f72fa39 Mon Sep 17 00:00:00 2001 From: Alexander Akhmetov Date: Thu, 18 Dec 2025 14:58:39 +0100 Subject: [PATCH 09/10] Alerting: Improve performance of rule list view with limit_alerts=0 (#115548) Alerting: Improve performance of rule list view --- .../ngalert/api/prometheus/api_prometheus.go | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/pkg/services/ngalert/api/prometheus/api_prometheus.go b/pkg/services/ngalert/api/prometheus/api_prometheus.go index 934805d74f4..b4e14a66cfe 100644 --- a/pkg/services/ngalert/api/prometheus/api_prometheus.go +++ b/pkg/services/ngalert/api/prometheus/api_prometheus.go @@ -357,7 +357,7 @@ func (srv PrometheusSrv) RouteGetRuleStatuses(c *contextmodel.ReqContext) respon type RuleStatusMutator func(source *ngmodels.AlertRule, toMutate *apimodels.AlertingRule) // mutator function used to attach alert states to the rule and returns the totals and filtered totals -type RuleAlertStateMutator func(source *ngmodels.AlertRule, toMutate *apimodels.AlertingRule, stateFilterSet map[eval.State]struct{}, matchers labels.Matchers, labelOptions []ngmodels.LabelOption) (total map[string]int64, filteredTotal map[string]int64) +type RuleAlertStateMutator func(source *ngmodels.AlertRule, toMutate *apimodels.AlertingRule, stateFilterSet map[eval.State]struct{}, matchers labels.Matchers, labelOptions []ngmodels.LabelOption, limitAlerts int64) (total map[string]int64, filteredTotal map[string]int64) func RuleStatusMutatorGenerator(statusReader StatusReader) RuleStatusMutator { return func(source *ngmodels.AlertRule, toMutate *apimodels.AlertingRule) { @@ -377,32 +377,18 @@ func RuleStatusMutatorGenerator(statusReader StatusReader) RuleStatusMutator { } func RuleAlertStateMutatorGenerator(manager state.AlertInstanceManager) RuleAlertStateMutator { - return func(source *ngmodels.AlertRule, toMutate *apimodels.AlertingRule, stateFilterSet map[eval.State]struct{}, matchers labels.Matchers, labelOptions []ngmodels.LabelOption) (map[string]int64, map[string]int64) { + return func(source *ngmodels.AlertRule, toMutate *apimodels.AlertingRule, stateFilterSet map[eval.State]struct{}, matchers labels.Matchers, labelOptions []ngmodels.LabelOption, limitAlerts int64) (map[string]int64, map[string]int64) { states := manager.GetStatesForRuleUID(source.OrgID, source.UID) totals := make(map[string]int64) totalsFiltered := make(map[string]int64) for _, alertState := range states { activeAt := alertState.StartsAt - valString := "" - if alertState.State == eval.Alerting || alertState.State == eval.Pending || alertState.State == eval.Recovering { - valString = FormatValues(alertState) - } stateKey := strings.ToLower(alertState.State.String()) totals[stateKey] += 1 // Do not add error twice when execution error state is Error if alertState.Error != nil && source.ExecErrState != ngmodels.ErrorErrState { totals["error"] += 1 } - alert := apimodels.Alert{ - Labels: apimodels.LabelsFromMap(alertState.GetLabels(labelOptions...)), - Annotations: apimodels.LabelsFromMap(alertState.Annotations), - - // TODO: or should we make this two fields? Using one field lets the - // frontend use the same logic for parsing text on annotations and this. - State: state.FormatStateAndReason(alertState.State, alertState.StateReason), - ActiveAt: &activeAt, - Value: valString, - } // Set the state of the rule based on the state of its alerts. // Only update the rule state with 'pending' or 'recovering' if the current state is 'inactive'. @@ -442,7 +428,23 @@ func RuleAlertStateMutatorGenerator(manager state.AlertInstanceManager) RuleAler totalsFiltered["error"] += 1 } - toMutate.Alerts = append(toMutate.Alerts, alert) + if limitAlerts != 0 { + valString := "" + if alertState.State == eval.Alerting || alertState.State == eval.Pending || alertState.State == eval.Recovering { + valString = FormatValues(alertState) + } + + toMutate.Alerts = append(toMutate.Alerts, apimodels.Alert{ + Labels: apimodels.LabelsFromMap(alertState.GetLabels(labelOptions...)), + Annotations: apimodels.LabelsFromMap(alertState.Annotations), + + // TODO: or should we make this two fields? Using one field lets the + // frontend use the same logic for parsing text on annotations and this. + State: state.FormatStateAndReason(alertState.State, alertState.StateReason), + ActiveAt: &activeAt, + Value: valString, + }) + } } return totals, totalsFiltered } @@ -1227,7 +1229,7 @@ func toRuleGroup(log log.Logger, groupKey ngmodels.AlertRuleGroupKey, folderFull } // mutate rule for alert states - totals, totalsFiltered := ruleAlertStateMutator(rule, &alertingRule, stateFilterSet, matchers, labelOptions) + totals, totalsFiltered := ruleAlertStateMutator(rule, &alertingRule, stateFilterSet, matchers, labelOptions, limitAlerts) if alertingRule.State != "" { rulesTotals[alertingRule.State] += 1 From 4fbcebac2c78c48b4338881b42b5c39db7c8b9c5 Mon Sep 17 00:00:00 2001 From: "Marc M." <146180665+grafakus@users.noreply.github.com> Date: Thu, 18 Dec 2025 15:01:04 +0100 Subject: [PATCH 10/10] Deps: Upgrade Scenes to v6.51.0 (#115547) Scenes: Upgrade to v6.51.0 --- package.json | 4 ++-- yarn.lock | 22 +++++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index f2300869740..37dc6ff745c 100644 --- a/package.json +++ b/package.json @@ -295,8 +295,8 @@ "@grafana/plugin-ui": "^0.11.1", "@grafana/prometheus": "workspace:*", "@grafana/runtime": "workspace:*", - "@grafana/scenes": "6.50.0", - "@grafana/scenes-react": "6.50.0", + "@grafana/scenes": "^6.51.0", + "@grafana/scenes-react": "^6.51.0", "@grafana/schema": "workspace:*", "@grafana/sql": "workspace:*", "@grafana/ui": "workspace:*", diff --git a/yarn.lock b/yarn.lock index e20676b04f0..a60a9c08912 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3604,11 +3604,11 @@ __metadata: languageName: unknown linkType: soft -"@grafana/scenes-react@npm:6.50.0": - version: 6.50.0 - resolution: "@grafana/scenes-react@npm:6.50.0" +"@grafana/scenes-react@npm:^6.51.0": + version: 6.51.0 + resolution: "@grafana/scenes-react@npm:6.51.0" dependencies: - "@grafana/scenes": "npm:6.50.0" + "@grafana/scenes": "npm:6.51.0" lru-cache: "npm:^10.2.2" react-use: "npm:^17.4.0" peerDependencies: @@ -3620,7 +3620,7 @@ __metadata: react: ^18.0.0 react-dom: ^18.0.0 react-router-dom: ^6.28.0 - checksum: 10/9ac9f8a32699f447c7b67dd2aef4e3ca5bc9fc98e94e0dc139e7824274ffa005b7fb3fc42ca5e55bdf89b91e3af0d3807b03e1a261db91c65717ee1763e5e807 + checksum: 10/14acdfe5220e67e7450780320b779e2e4a255995d55f0c82eb0d25933e72598e54826df0a8beee05591efe01a91ddab840483fea3bb828bd5925c3f0b44b8d17 languageName: node linkType: hard @@ -3650,9 +3650,9 @@ __metadata: languageName: node linkType: hard -"@grafana/scenes@npm:6.50.0": - version: 6.50.0 - resolution: "@grafana/scenes@npm:6.50.0" +"@grafana/scenes@npm:6.51.0, @grafana/scenes@npm:^6.51.0": + version: 6.51.0 + resolution: "@grafana/scenes@npm:6.51.0" dependencies: "@floating-ui/react": "npm:^0.26.16" "@leeoniya/ufuzzy": "npm:^1.0.16" @@ -3672,7 +3672,7 @@ __metadata: react: ^18.0.0 react-dom: ^18.0.0 react-router-dom: ^6.28.0 - checksum: 10/7bc6280ff065bbba37f010e2a1f0a7dc998fe43721ddc0121e27a754c41e824b82a44222100282a69143a52061cf0dce39e6bc8b95292ca444a59c114d4b5a41 + checksum: 10/4e4f43babe786ff729d58b7636182df57c58ce40c13b56036f725c070e0cf597cbe52aaa0f811184b8d42d8d1f9a32679695471d410f883051b09da44f8bf36a languageName: node linkType: hard @@ -19508,8 +19508,8 @@ __metadata: "@grafana/plugin-ui": "npm:^0.11.1" "@grafana/prometheus": "workspace:*" "@grafana/runtime": "workspace:*" - "@grafana/scenes": "npm:6.50.0" - "@grafana/scenes-react": "npm:6.50.0" + "@grafana/scenes": "npm:^6.51.0" + "@grafana/scenes-react": "npm:^6.51.0" "@grafana/schema": "workspace:*" "@grafana/sql": "workspace:*" "@grafana/test-utils": "workspace:*"