Compare commits

...

11 Commits

Author SHA1 Message Date
Naman Verma
2a96645af6 fix(rules): keep rule labels from overriding engine labels (#13612)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

A rule label named threshold.name or severity replaced the value the
evaluator stamped. Rule Labels aren't supposed to be treated in a
special way like this.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

Part of https://github.com/SigNoz/pulse-pod/issues/653
2026-11-17 10:33:44 +00:00
hardik-signoz
900796a573 test(e2e): cover users FGA on the members page (#13615)
#### Description

- Adds `members.spec.ts` TC-04 to TC-07, each running as a member
holding only a custom role:
  - TC-04: `list:user` without `create:user`, invite button denied
- TC-05: no `list:user`, list shows "not authorized" and search is
denied
- TC-06: invited member without `factor-password:list`, "Invite Link
Unavailable"
- TC-07: self edit, adds then removes a role (needs `attach` and
`detach` on user and role)
- Drivers: `guestSettings` fixture (settings pages on the signed-in
guest page), `createGrantedUser` seed, members locators, `addRole` and
`removeRole`.
- Unit, story and integration tests already cover the rest of Users FGA,
see the plan on the issue.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#212

#### Additional Information

- Each spec was checked by granting the missing permission and
confirming it fails.
- Run locally against hosted staging backend with the local frontend
(`--no-deps`). Not run on the pytest bootstrap stack.
2026-11-17 06:54:50 +00:00
Swapnil Nakade
2175611902 feat(authz): enable FGA for org preference routes (#13590)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- Adds resource defs to the three `/api/v1/org/preferences` routes so
org preference updates emit audit events.
- Moves them from `AdminAccess` to `CheckResources`, scoped to
`org-preference:list`, `org-preference:read` and
`org-preference:update`. Admin keeps sole access.
- Migration 150 backfills the admin `org-preference` tuples for orgs
created before the grant existed. The registry and stored roles already
carry the grant, so it writes tuples only.
- The preference name is recorded as the resource ID with a wildcard
selector, since names are not UUIDs.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/10
contributes to https://github.com/SigNoz/keystone-pod/issues/43
2026-11-17 05:35:50 +00:00
hardik-signoz
29d4f7fb8d chore(sentry): exclude anonymous sentry errors (#13599)
#### Description

- Drop Sentry events whose throwing frame is `<anonymous>` (code loaded
without a script URL, such as extension or automation scripts).
- The existing `hasNoAppFrames` filter missed them: Sentry's bundled
`setTimeout` wrapper counts as an app frame.
- Matching the top frame instead of the error message keeps real bugs
reportable.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#218
2026-11-17 05:34:07 +00:00
Swapnil Nakade
b2991101af test(fileauditor): cover the audit file write path end to end (#13611)
#### Description

- New `fileauditor` suite: starts SigNoz with the file auditor and reads
`/tmp/audit.log` from the container.
- One test per audited verb (create, update, delete, attach, detach),
plus a failed request that writes a failure event.
2026-11-17 05:21:18 +00:00
Vinicius Lourenço
7a52290c0c chore(deps): patch frontend pnpm audit findings (#13562)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

Clears every high finding from `pnpm audit` in the frontend (zod,
follow-redirects, markdown-it, joi) and most of the moderate and low
ones.

- Bumped axios, zod and i18next-http-backend directly.
- Raised or added override floors for fast-uri, joi, markdown-it, moment
and uuid. The uuid floor moves `@storybook/test-runner` from uuid 8 to
11, which still exports the `v4` it imports.

Left alone on purpose: react-router (the fix needs React 19), glob and
minimatch (the fix only exists in new majors that drop APIs jest and
eslint use), and deepmerge (no patched release). The e2e package only
has the minimatch finding, so it is unchanged.

To verify: `pnpm audit` in `frontend` shows 0 high, down from 7.

Closes https://github.com/SigNoz/uforge-pod/issues/6454
2026-11-16 21:25:50 +00:00
Vinicius Lourenço
d5a8c64f1f feat(router): upgrade to react-router v7 on a data router (#13335)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

> TLDR: You can take a look at
https://claude.ai/artifact/LbFG6NcXyeRCm5MSnCKANc

- Upgrades react-router v5 (plus `react-router-dom-v5-compat` 6.30 and
`history@4`) to `react-router` 7.18.4. Follows #13173: pages and
components keep calling `src/lib/router`, so outside the router code the
only changes are render-order and nuqs write-order fixes.
- The app mounts a data router (`createBrowserRouter`) under a pathless
root route that renders `AppProviders`. The base path becomes the
router's `basename`. `lib/history`, `history`, `@types/history` and
`@types/react-router-dom` are removed.
- nuqs moves to its `react-router/v7` adapter, and the `react-router <7`
override goes, which held nuqs's copy below the fix for
GHSA-wrjc-x8rr-h8h6.
- The route table is static. A `RouteGate` renders `NotFound` for routes
the plan, license or flags turn off, which is what the old dynamic
`<Switch>` fell through to. `exact` is dropped (v7 matches exactly) and
the 4 prefix routes become `nested` (`pattern/*`).
- `useNavigationBlocker` moves to v7 `useBlocker` through a new
`useAppBlocker`, which deletes the history@4 replay code from #13173.

What replaced what:

| Before | After |
| --- | --- |
| `<Router history>` + `<CompatRouter>` in `AppShell` |
`createAppRouter` + `RouterProvider` in `index.tsx` |
| `<Switch>` over the enabled routes | static table in
`AppRoutes/routeTable.tsx`, `<Outlet context={enabledRouteKeys}>` |
| `lib/history` singleton behind `navigate()` | `attachRouter`:
`navigate()` drives the data router attached last |
| `blockNavigation` + `retryTransition` | `useAppBlocker` (`proceed` /
`reset`) |
| `nuqs/adapters/react` | `nuqs/adapters/react-router/v7` |
| `MemoryRouter` / history-backed `TestRouter` | browser data router
over jsdom's history, `HostRouter` |
| `lib/history` alias in Storybook | memory data router per story with a
guarded `navigate` |

#### Issues closed by this PR

Closes https://github.com/SigNoz/uforge-pod/issues/2544

#### Additional Information

Reviewing: read by commit. Only the tip builds, since the package swap
cannot land halfway.

- Read closely: `feat(router): back the facade with react-router v7`
(`navigation.ts`, `matchRoute`, `buildRoutePath`, `AppLink` /
`Redirect`), `feat(router): mount the app on a data router`
(`app/AppRouter.tsx`, `AppRoutes/routeTable.tsx`, `Private.tsx`), the
blocker commit and the test router commit (`tests/router.tsx`,
`router-utils.ts`, `lib/router/HostRouter.tsx`).
- Read closely: the 8 `fix(router)` commits. `useShareBuilderUrl` and
`QuerySearchV2Provider` published their query onto the next route while
a route-driven tab was leaving, and the provider then wiped an
expression a child runs on mount (the K8s drawer's Overview tab); two
lazy routes of one module (logs explorer, pipelines) reused the previous
page until the gate was keyed by route entry; `stripBasePath` now
matches case-insensitively, as the router does.
- Three fix nuqs writes that a navigation dropped or overwrote.
`nuqs/adapters/react-router/v7` patches `history.pushState` and
`replaceState`, and any write it did not make clears the writes it still
has queued. On K8s a row needed two clicks to open its drawer (a no-op
`replace` from `useSafeNavigate`), a category switch with a filter kept
the old category, run query kept the old page, and a stored page size
was lost on mount. Alert history rebuilt URLs from the router's stale
location, and the adapter adopted them, dropping the search expression.
Fixed at the call sites; the tests run the real adapter, and
`routing/url-state.spec.ts` TC-05 to TC-08 cover K8s. #13336 has the 2
K8s commits, not the alert history one. The FAQ below has the full nuqs
picture.
- Skim: deps, jest environment, Storybook and lint commits.

Behavior to know:

- Route transitions run with `useTransitions={false}`. Under a
transition React keeps the old screen, so a route whose chunk is not
cached would show no loader.
- The post-login hop to the stashed route still pushes
(`replace={false}`). Back from it now ends on `/home` instead of the
stashed route, because the stash is already cleared; TC-15 asserts it.
- `navigate()` and `getCurrentLocation()` throw when no router is
attached. Tests render first or call `attachTestRouter`.

Testing:

- The 2 K8s nuqs commits came after those runs: `tsgo`, lint and `pnpm
build` clean on the tip, and the 46 related jest suites pass. With the
fixed files reverted, 5 of their 7 new tests fail.
- E2E chromium, run before the rebase onto main, routing specs from
#13078 included: 415 passed, 4 failed. The 4 (alert history expression
filter TC-10 to TC-12, token highlight dark theme) are load flakes:
repeated 3 times at 6 workers, those specs fail 15 of 50 runs on the
#13173 build and 12 of 50 here.
- Bundle, against the #13173 build: the entry chunk grows by 20 KB gzip
(+0.78%). Router libraries in it go from 33 KB minified (v5, v6 compat,
history) to 95 KB (`react-router` 7). CSS unchanged, one lazy chunk
fewer.

FAQ:

<details>
<summary>Why a data router and not declarative mode
(<code>&lt;BrowserRouter&gt;</code> +
<code>&lt;Routes&gt;</code>)?</summary>

`<BrowserRouter>` creates its history inside the component and gives
nothing outside React a handle on it. 88 files navigate through
`lib/router/navigation`, some from plain modules (`api/utils.ts`,
`utils/app.ts`). In declarative mode the only way to reach them is
`unstable_HistoryRouter` over a `history@5` object we own, which is what
#13336 does. A data router is an object created before the first render,
so `navigation.ts` calls `router.navigate` on it directly. `useBlocker`
needs one too: in 7.18.4 it throws under `<Routes>` or
`unstable_HistoryRouter`.

</details>

<details>
<summary>Why remove <code>history</code> and
<code>lib/history</code>?</summary>

A data router creates and owns its history; v7 has no prop that accepts
one. Keeping the `lib/history` singleton would leave a second writer to
`window.history` that the router never hears: the router only listens to
`popstate`, so a `history.push` from the singleton moves the address bar
and renders nothing. What the singleton did (navigate from anywhere,
`listen`, `hasInAppHistory`) now lives in `navigation.ts` on top of the
attached router.

</details>

<details>
<summary>Why a new React context in <code>HostRouter</code>?</summary>

It is for tests and stories only; the app does not use it. A data
router's routes, elements included, are fixed when the router is
created. `TestRouter` creates its router once per mount, so a `rerender`
with new children would keep showing the first ones. `HostRouter` puts
the children in a context and the route element (`HostedTreeOutlet`)
reads it, so a re-render shows the new tree.

</details>

<details>
<summary>Why do routes read the enabled set from outlet
context?</summary>

The route table is built once, at module load, before any hook runs, so
it cannot ask the plan, license or flags which routes are on. `App`
still computes that set the way it did and passes it down as `<Outlet
context>`. `RouteGate` reads it and renders the page or `NotFound`,
where the old dynamic `<Switch>` fell through. Flags loading later never
recreates the router.

</details>

<details>
<summary>Why do the providers render inside the router now?</summary>

A data router renders everything under `RouterProvider`, and the only
place for a layout above the pages is the root route's element. The nuqs
adapter calls `useNavigate` and `useSearchParams`, so it has to be
inside a router. `AppProviders` and `App` became that root element.

</details>

<details>
<summary>Why does <code>navigate()</code> keep a stack of routers, and
throw without one?</summary>

Tests and stories mount their own data router. `attachRouter` pushes it
and its detach pops it, so `navigate()` moves whichever router is on
screen and hands back to the one below. With nothing attached there is
no router to hear the navigation, so it throws instead of silently
writing the URL.

</details>

<details>
<summary>Why is <code>RouteGate</code> keyed by route entry?</summary>

`<Outlet>` renders the matched element without a key. The logs explorer
and pipelines routes lazy-load the same module, so React reused the old
instance and showed the previous page. The key remounts the page when
the route entry changes.

</details>

<details>
<summary>Does any page load data through a loader now?</summary>

No. No route has a `loader` or `lazy`, so every page fetches through
react-query as before and navigations commit synchronously. The first
`loader` makes navigations through that route asynchronous:
`getCurrentLocation()` right after `navigate()` would then return the
old location.

</details>

<details>
<summary>Why did query builder files change if pages only call the
facade?</summary>

A route-driven tab keeps the leaving pane mounted until its animation
ends. On v7 that pane saw the new location and published onto it:
`useShareBuilderUrl` wrote the old tab's `compositeQuery`, and
`QuerySearchV2Provider` restored a dropped `expression`. Both now
publish only for their own page, and the URL owns the expression. That
last change wiped an expression a child runs on mount (the K8s drawer's
Overview tab starts from the list filter), so the provider skips its
first run when the URL has none.

</details>

<details>
<summary>Is the nuqs de-sync fixed?</summary>

It is two problems, and only one is fixed.

The router still lags nuqs, as on main. A nuqs write is shallow: it
calls `history.replaceState` or `pushState` itself and does not tell the
router, so `useLocation().search` stays behind the address bar until the
next router navigation. Event handlers read the real URL through
`getUnstableCurrentSearchParams()`. Removing that lag means `shallow:
false` writes, a separate change with known regressions (the role editor
blocker, AI assistant chips, Back behavior, a re-render per write).

The adapter swap is new. `nuqs/adapters/react-router/v7` patches
`pushState` and `replaceState`. A write it did not make, which means
every router navigation, does two things: it aborts the nuqs writes
still queued (they wait up to 50 ms), and it becomes nuqs's state.
Main's `nuqs/adapters/react` does neither, so router writes to a nuqs
param do not reach its hooks there. That gave two kinds of bug:

| Kind | Example | Status |
| --- | --- | --- |
| A navigation drops a queued write | K8s: two clicks to open a drawer,
category switch keeps the old category, run query keeps the old page,
stored page size lost | fixed: navigate before the nuqs setters,
`useSafeNavigate` skips a no-op target, the default query redirect
renders before the list |
| A URL rebuilt from the stale router location is adopted back | alert
history: a state tab, the top contributors drawer or a graph zoom
dropped the search expression | fixed: build from
`getUnstableCurrentSearchParams()` |
| Same, not confirmed | members `?invite=true`, dashboard `variables`
(`useViewPanel`, `usePanelInteractions`), planned downtime, routing
policies | open: needs a contrast test against main's adapter |

Jest tests run the real adapter, and `routing/url-state.spec.ts` TC-05
to TC-08 check the K8s first clicks. For new code: navigate first and
call nuqs setters after, and build a URL from
`getUnstableCurrentSearchParams()`, not from the router location.

</details>
2026-11-16 20:41:05 +00:00
Swapnil Nakade
f0cde4f37d feat(authz): enable FGA for org routes (#13586)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- Adds resource defs to `GET`/`PUT /api/v2/orgs/me` so org updates emit
audit events.
- Moves both routes from `AdminAccess` to `CheckResources`, scoped to
`organization:read` and `organization:update`. Admin gets both; editor
and viewer stay blocked.
- Migration 149 backfills the admin grants and refreshes managed roles
for existing orgs.
- The org ID comes from the caller's claims, since the update handler
ignores the body `id`.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/10
contributes to https://github.com/SigNoz/keystone-pod/issues/43

<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information
- The organization object has no org prefix, so the managed `*` grant
(`organization:organization/*`) covers every org. Safe here because both
routes take the org from claims. A route that takes an org ID from the
request needs an org-scoped grant first.
2026-11-16 18:03:21 +00:00
Swapnil Nakade
1efbbcfc5e feat: adding integration tests for audit querier (#13550)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- adding integration tests for audit querier
- adds tests for querying ingested audit logs

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/13
2026-11-16 14:21:04 +00:00
Aditya Singh
7cef7e48ea feat(pipelines): move the filter preview to query_range v5 (#13608)
#### Description
- The pipeline filter preview read its sample logs and its match count
from the v3 `query_range` API. The backend plans to remove the v3 APIs.
- The sample logs and the match count now come from v5 `query_range`.
The preview sends the filter as a v5 filter expression.
- On `use_json_body` tenants, v5 returns the log body as an object. The
pipelines preview API accepts only a string body, so "Simulate
Processing" failed with a 400. The preview now sends an object body as a
JSON string, as v3 did.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/274

#### Screen recording


https://github.com/user-attachments/assets/229ded0a-fc40-4f79-b593-d9387a43f3c7

#### Additional Information
- Part of https://github.com/SigNoz/events-pod/issues/156. This is the
`query_range` follow-up that https://github.com/SigNoz/signoz/pull/13207
mentioned.
- The preview calls v5 through the existing `useGetQueryRange` wrapper,
like the other v5 migrations.
- reproduced the 400 on a staging tenant with `use_json_body`. With the
fix, the simulation returns the processed logs.
- Stories: the Pipelines story serves v5 `query_range` for the sample
logs and the count. The story no longer serves the v3 suggestion APIs,
because the filter uses the v5 fields APIs since #13207. The simulation
fix renders nothing new, so the story is unchanged for it.
2026-11-16 13:32:18 +00:00
hardik-signoz
7189736cea feat(authz): add users fine-grained access control (#13506)
#### Description

- Add `user` and `factor-password` to the role permission schema and
panels, and teach the `generate authz` command to emit both.
- Gate the Members page on `user:list` (list, filter, search) and Invite
member, including the modal's submit, on `user:create`. Attach failures
show as the inline API error after click.
- Gate the member drawer: details on `user:read`, name and save on
`user:update`, delete/revoke on `user:delete`, and the password reset
link on `factor-password:create` + `user:attach`.
- Show the Members settings entry to every user; permissions decide what
it renders.
- Update unit tests, Members stories (new `Authz` folder, one story per
permission) and the e2e settings smoke spec for the new gating.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#202

#### Screenshots
[Before/after diff, dark and
light](https://claude.ai/artifact/XXY1xvkAMZoR6GS2cMmDdZ?sk=Yz4QIeLw8gEJ2ia5Ti5nbA):
110 pairs, 48 identical, 18 new, 44 changed (30 Roles permission cards,
6 settings nav, 8 sub-0.1% Members noise).

---------

Co-authored-by: vikrantgupta25 <vikrant@signoz.io>
2026-11-16 13:08:12 +00:00
186 changed files with 6429 additions and 2969 deletions

View File

@@ -40,11 +40,11 @@ jobs:
suite:
- alertmanager
- alertmanagerrotation
- auditquerier
- basepath
- callbackauthn
- cloudintegrations
- dashboard
- fileauditor
- ingestionkeys
- inframonitoring
- llmpricingrules
@@ -58,6 +58,7 @@ jobs:
- querierscalar
- queriercommon
- querierai
- querieraudit
- rawexportdata
- promqlconformance
- promapiconformance

View File

@@ -30,7 +30,7 @@ export default {
],
relations: {
{{- range .Relations }}
{{ .Verb }}: [{{ range $i, $t := .Types }}{{ if $i }}, {{ end }}'{{ $t }}'{{ end }}],
{{ .FormattedTypes }}
{{- end }}
},
},
@@ -38,8 +38,8 @@ export default {
`))
type permissionsTypeRelation struct {
Verb string
Types []string
Verb string
FormattedTypes string
}
type permissionsTypeResource struct {
@@ -77,6 +77,29 @@ func formatAllowedVerbs(verbs []string, indentLevel int, printWidth int) string
return b.String()
}
// formatRelationTypes returns a prettier-compatible formatted `verb: [...]` line, wrapping
// one type per line when it exceeds printWidth (tabWidth assumed to be 1).
func formatRelationTypes(verb string, types []string, indentLevel int, printWidth int) string {
quoted := make([]string, len(types))
for i, t := range types {
quoted[i] = "'" + t + "'"
}
indent := strings.Repeat("\t", indentLevel)
oneLine := indent + verb + ": [" + strings.Join(quoted, ", ") + "],"
if len(oneLine) <= printWidth {
return oneLine
}
var b strings.Builder
b.WriteString(indent + verb + ": [\n")
for _, q := range quoted {
b.WriteString(indent + "\t" + q + ",\n")
}
b.WriteString(indent + "],")
return b.String()
}
func registerGenerateAuthz(parentCmd *cobra.Command) {
authzCmd := &cobra.Command{
Use: "authz",
@@ -106,6 +129,8 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceMetaResourceQuickFilter).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceSavedView).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
}
allowedTypes := map[string]bool{}
@@ -154,8 +179,8 @@ func runGenerateAuthz(_ context.Context) error {
types = append(types, t.StringValue())
}
relations = append(relations, permissionsTypeRelation{
Verb: verb.StringValue(),
Types: types,
Verb: verb.StringValue(),
FormattedTypes: formatRelationTypes(verb.StringValue(), types, 3, 80),
})
}

View File

@@ -11992,8 +11992,9 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
type: object
notificationSettings:
allOf:
@@ -12110,8 +12111,9 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
type: object
notificationSettings:
allOf:
@@ -16567,9 +16569,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- org-preference:list
- tokenizer:
- ADMIN
- org-preference:list
summary: List org preferences
tags:
- preferences
@@ -16632,9 +16634,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- org-preference:read
- tokenizer:
- ADMIN
- org-preference:read
summary: Get org preference
tags:
- preferences
@@ -16689,9 +16691,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- org-preference:update
- tokenizer:
- ADMIN
- org-preference:update
summary: Update org preference
tags:
- preferences
@@ -24950,9 +24952,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- organization:read
- tokenizer:
- ADMIN
- organization:read
summary: Get my organization
tags:
- orgs
@@ -25001,9 +25003,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- organization:update
- tokenizer:
- ADMIN
- organization:update
summary: Update my organization
tags:
- orgs

View File

@@ -124,11 +124,11 @@ tests/
│ ├── alerts/
│ │ ├── 01_*.py # numbered suite files
│ │ └── conftest.py # optional suite-local fixtures
│ ├── auditquerier/
│ ├── cloudintegrations/
│ ├── dashboard/
│ ├── passwordauthn/
│ ├── querier/
│ ├── querieraudit/
│ └── ...
└── e2e/ # Playwright suite (see docs/contributing/tests/e2e.md)
```

View File

@@ -267,9 +267,7 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
for name, value := range r.Labels().Map() {
lb.Set(name, expand(value))
}
lb.SetRuleLabels(r.Labels().Map(), expand)
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -593,16 +593,19 @@
}
},
{
// The react-router allowlist: the facade itself, the route table, `useSafeNavigate`,
// the history singleton and the test and story router mounts. Test files are
// The react-router allowlist: the facade itself, the route table, the router mount,
// `useSafeNavigate` and the test and story router mounts. Test files are
// deliberately absent: they render at a route or use tests/router-mocks.
"files": [
"src/lib/router/**",
"src/AppRoutes/**",
"src/app/AppRouterProvider.tsx",
"src/app/createAppRouter.ts",
"src/hooks/useSafeNavigate.ts",
"src/lib/history.ts",
"src/tests/router.tsx",
"src/storybook/providers/StorybookProviders.tsx",
"src/tests/router-utils.ts",
"src/storybook/navigation/containment.ts",
"src/storybook/navigation/pageScope.ts",
"src/storybook/renderAtRoute.tsx"
],
"rules": {

View File

@@ -8,8 +8,8 @@ const srcPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
/**
* Modules replaced for every story. Same idea as `moduleNameMapper` in
* `jest.config.ts`: the app keeps importing its own paths, Storybook resolves
* them to a mock. Regexes so only exact specifiers match: `lib/history` must
* not catch `lib/historyUtils`.
* them to a mock. Regexes so only exact specifiers match: `store` must not
* catch `store/actions`.
*
* Each replacement is typed as the module it stands in for, so drift is a
* compile error rather than a story that fails at render. The `jest` note on
@@ -17,11 +17,6 @@ const srcPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
* only diverge where the runner needs them to.
*/
const mockAliases = [
{
// jest: not replaced, jsdom drives a real browser history.
find: /^(?:src\/)?lib\/history$/,
replacement: `${srcPath}/storybook/navigation/history.alias.ts`,
},
{
// jest: src/__tests__/logEventMock.ts
find: /^(?:src\/)?api\/common\/logEvent$/,

View File

@@ -192,6 +192,7 @@ const preview: Preview = {
'Role Details',
'Role Editor',
'Members',
['Overview', 'Authz'],
'Service Accounts',
'Ingestion',
'Single Sign-on',

View File

@@ -64,7 +64,7 @@ const config: Config.InitialOptions = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testPathIgnorePatterns: ['/node_modules/', '/public/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: 'jest-environment-jsdom',
testEnvironment: '<rootDir>/jest.environment.cjs',
coverageThreshold: {
global: {
statements: 80,

View File

@@ -0,0 +1,22 @@
const { TestEnvironment } = require('jest-environment-jsdom');
/**
* jsdom plus the fetch `Request` a data router builds for every navigation,
* which jsdom does not ship. Node's own class is used, except that it keeps the
* `signal` it is handed: the router passes jsdom's `AbortSignal`, and Node's
* `Request` rejects one from another realm.
*/
class JSDOMWithRequestEnvironment extends TestEnvironment {
constructor(config, context) {
super(config, context);
this.global.Request = class extends Request {
constructor(input, { signal, ...init } = {}) {
super(input, init);
Object.defineProperty(this, 'signal', { value: signal ?? super.signal });
}
};
}
}
module.exports = JSDOMWithRequestEnvironment;

View File

@@ -5,6 +5,8 @@
/**
* Adds custom matchers from the react testing library to all tests
*/
import { TextDecoder, TextEncoder } from 'node:util';
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
import 'jest-styled-components';
@@ -14,6 +16,14 @@ import { server } from './src/mocks-server/server';
import './src/styles.scss';
// Establish API mocking before all tests.
// react-router@7's entry point pulls in its server-runtime cookie signing,
// which builds a TextEncoder at module scope. jsdom ships neither encoder, so
// importing anything from the router throws before a test starts.
Object.assign(globalThis, {
TextEncoder: globalThis.TextEncoder ?? TextEncoder,
TextDecoder: globalThis.TextDecoder ?? TextDecoder,
});
// Mock window.matchMedia
window.matchMedia =
window.matchMedia ||

View File

@@ -71,7 +71,7 @@
"antd": "5.11.0",
"antd-table-saveas-excel": "2.2.1",
"antlr4": "4.13.2",
"axios": "1.21.0",
"axios": "1.21.1",
"babel-jest": "^29.6.4",
"chart.js": "3.9.1",
"chartjs-adapter-date-fns": "^2.0.0",
@@ -85,12 +85,11 @@
"dompurify": "3.4.17",
"event-source-polyfill": "1.0.31",
"eventemitter3": "5.0.1",
"history": "4.10.1",
"html-to-image": "1.11.13",
"http-status-codes": "2.3.0",
"i18next": "^21.6.12",
"i18next-browser-languagedetector": "^6.1.3",
"i18next-http-backend": "^4.0.0",
"i18next-http-backend": "^4.0.4",
"immer": "11.1.3",
"jest": "30.2.0",
"js-base64": "^3.7.2",
@@ -120,8 +119,7 @@
"react-query": "3.39.3",
"react-redux": "^7.2.2",
"react-rnd": "^10.5.3",
"react-router-dom": "^5.2.0",
"react-router-dom-v5-compat": "6.30.6",
"react-router": "7.18.4",
"react-syntax-highlighter": "15.5.0",
"react-use": "^17.3.2",
"react-virtuoso": "4.0.3",
@@ -139,7 +137,7 @@
"uplot": "1.6.31",
"uuid": "14.0.1",
"vite": "npm:rolldown-vite@7.3.1",
"zod": "4.3.6",
"zod": "4.6.7",
"zustand": "5.0.11"
},
"browserslist": {
@@ -178,7 +176,6 @@
"@types/d3-hierarchy": "1.1.11",
"@types/event-source-polyfill": "^1.0.0",
"@types/geojson": "7946.0.16",
"@types/history": "4.7.11",
"@types/jest": "30.0.0",
"@types/lodash-es": "^4.17.4",
"@types/node": "^22.20.5",
@@ -189,7 +186,6 @@
"@types/react-grid-layout": "^1.1.2",
"@types/react-redux": "^7.1.11",
"@types/react-resizable": "3.0.3",
"@types/react-router-dom": "^5.1.6",
"@types/react-syntax-highlighter": "15.5.13",
"@types/redux-mock-store": "1.0.4",
"@types/styled-components": "^5.1.4",

View File

@@ -1,7 +1,6 @@
import { ruleTester } from './rule-tester.mjs';
const FACADE = 'src/lib/router facade';
const HISTORY = 'lib/history singleton';
const MOCK = 'tests/router-mocks helpers';
await ruleTester({
@@ -11,11 +10,6 @@ await ruleTester({
name: 'facade import',
code: "import { useAppNavigate } from 'lib/router/useAppNavigate';",
},
{
name:
'the history package itself is a version-bump concern, not a facade one',
code: "import { createBrowserHistory } from 'history';",
},
{
name: 'unrelated module whose name contains history',
code: "import { useHistoryPanel } from 'container/HistoryPanel';",
@@ -49,13 +43,8 @@ await ruleTester({
errors: [{ message: MOCK }],
},
{
name: 'jest.mock of lib/history',
code: "jest.mock('lib/history');",
errors: [{ message: MOCK }],
},
{
name: 'jest.doMock of react-router-dom-v5-compat',
code: "jest.doMock('react-router-dom-v5-compat');",
name: 'jest.doMock of react-router',
code: "jest.doMock('react-router');",
errors: [{ message: MOCK }],
},
{
@@ -74,29 +63,14 @@ await ruleTester({
errors: [{ message: FACADE }],
},
{
name: 'react-router-dom-v5-compat',
code: "import { useNavigate } from 'react-router-dom-v5-compat';",
errors: [{ message: 'compat package is an implementation detail' }],
name: 'react-router-dom is flagged as the v7 re-export shim',
code: "import { Outlet } from 'react-router-dom';",
errors: [{ message: 'only a re-export shim' }],
},
{
name: 'lib/history default import',
code: "import history from 'lib/history';",
errors: [{ message: HISTORY }],
},
{
name: 'lib/history through the @/ alias',
code: "import history from '@/lib/history';",
errors: [{ message: HISTORY }],
},
{
name: 'jest.mock of lib/history through the @/ alias',
code: "jest.mock('@/lib/history');",
errors: [{ message: MOCK }],
},
{
name: 'lib/history require',
code: "const history = require('lib/history').default;",
errors: [{ message: HISTORY }],
name: 'require',
code: "const router = require('react-router');",
errors: [{ message: FACADE }],
},
{
name: 'dynamic import',
@@ -116,10 +90,10 @@ await ruleTester({
{
name: 'one report per import statement',
code:
"import { Link } from 'react-router-dom';\nimport history from 'lib/history';",
"import { Link } from 'react-router';\nimport { Outlet } from 'react-router';",
errors: [
{ message: FACADE, line: 1 },
{ message: HISTORY, line: 2 },
{ message: FACADE, line: 2 },
],
},
],

View File

@@ -5,18 +5,14 @@
* upgrade is a change to one directory instead of ~300 call sites. This rule
* keeps new call sites, and test mocks, from reaching past it.
*
* `history` (the package) is deliberately not flagged: it is a transitive concern of
* the version bump, not something the facade replaces.
* `react-router-dom` is still flagged even though the package is gone: on v7 it is a
* re-export shim over `react-router`, so reinstalling it would split the tree again.
*
* The allowlist (the facade itself, the route table, `useSafeNavigate`, the history
* singleton and the test and story router mounts) is applied via overrides in
* .oxlintrc.json, not here, so the file list stays visible next to the severity.
* The allowlist (the facade itself, the route table, the router mount,
* `useSafeNavigate` and the test and story router mounts) is applied via overrides
* in .oxlintrc.json, not here, so the file list stays visible next to the severity.
*/
import path from 'node:path';
const HISTORY_MODULE_SUFFIX = path.join('src', 'lib', 'history');
const JEST_MODULE_METHODS = new Set([
'mock',
'doMock',
@@ -29,30 +25,12 @@ const JEST_MODULE_METHODS = new Set([
]);
const MESSAGE_IDS = {
'react-router': 'v5Router',
'react-router-dom': 'v5Router',
'react-router-dom-v5-compat': 'v6Compat',
'lib/history': 'historySingleton',
'@/lib/history': 'historySingleton',
'react-router': 'router',
'react-router-dom': 'routerDom',
};
/** Resolves `./history` / `../history` so files inside src/lib count too. */
function isHistoryModule(specifier, filename) {
if (!specifier.startsWith('.') || !filename) {
return false;
}
const resolved = path.resolve(path.dirname(filename), specifier);
return (
resolved.endsWith(HISTORY_MODULE_SUFFIX) ||
resolved.endsWith(`${HISTORY_MODULE_SUFFIX}.ts`)
);
}
function messageIdFor(specifier, filename) {
if (MESSAGE_IDS[specifier] !== undefined) {
return MESSAGE_IDS[specifier];
}
return isHistoryModule(specifier, filename) ? 'historySingleton' : null;
function messageIdFor(specifier) {
return MESSAGE_IDS[specifier] ?? null;
}
export default {
@@ -60,17 +38,15 @@ export default {
type: 'suggestion',
docs: {
description:
'Disallow direct react-router / lib/history imports; import from src/lib/router instead',
'Disallow direct react-router imports; import from src/lib/router instead',
category: 'React Router migration',
},
schema: [],
messages: {
v5Router:
'Do not import react-router-dom directly. Use the src/lib/router facade (useAppNavigate, useAppLocation, useAppParams, AppLink, Redirect, matchRoute) so a router upgrade stays contained.',
v6Compat:
'Do not import react-router-dom-v5-compat directly. Use the src/lib/router facade instead; the compat package is an implementation detail of the migration and disappears with it.',
historySingleton:
'Do not import the lib/history singleton. Use the helpers in src/lib/router/navigation.ts, or useAppNavigate() to follow the nearest router. history loses basename handling once the router owns it.',
router:
'Do not import react-router directly. Use the src/lib/router facade (useAppNavigate, useAppLocation, useAppParams, AppLink, Redirect, matchRoute) so a router upgrade stays contained.',
routerDom:
'Do not import react-router-dom. The app is on react-router; on v7 react-router-dom is only a re-export shim, and installing it puts two copies of the router in the tree. Use the src/lib/router facade.',
mock:
'Do not mock the router directly. Render at a route with tests/test-utils, or spy on the facade with the tests/router-mocks helpers.',
},
@@ -85,7 +61,7 @@ export default {
) {
return;
}
const messageId = messageIdFor(sourceNode.value, context.filename);
const messageId = messageIdFor(sourceNode.value);
if (messageId !== null) {
context.report({
node: sourceNode,

237
frontend/pnpm-lock.yaml generated
View File

@@ -15,15 +15,18 @@ overrides:
cookie@<0.7.0: '>=0.7.1 <1'
dompurify@<=3.4.16: '>=3.4.17 <4'
esbuild@>=0.27.3 <0.28.1: '>=0.28.1 <0.29.0'
fast-uri@<3.1.6: '>=3.1.6 <4'
fast-uri@<3.1.9: '>=3.1.9 <4'
fflate@<0.4.9: '>=0.4.9 <0.5'
immutable@<5.1.8: '>=5.1.8 <6'
joi@<17.13.9: '>=17.13.9 <18'
js-cookie@<=3.0.5: '>=3.0.7 <4'
js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5'
markdown-it@<14.3.3: '>=14.3.3 <15'
moment@<2.31.0: '>=2.31.0 <3'
prismjs@<1.30.0: '>=1.30.0 <2'
postcss-selector-parser@>=7.1.0 <7.1.3: '>=7.1.3 <8'
react-router@>=6.7.0 <6.30.6: '>=6.30.6 <7'
tmp@<0.2.6: '>=0.2.6 <0.3.0'
uuid@<11.1.1: '>=11.1.1 <12'
yaml@>=1.0.0 <1.10.3: '>=1.10.3 <2'
'@types/node': ^22.20.5
@@ -81,7 +84,7 @@ importers:
version: 0.4.0
'@signozhq/ui':
specifier: 0.2.0
version: 0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)
version: 0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@tanstack/react-table':
specifier: 8.21.3
version: 8.21.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -117,7 +120,7 @@ importers:
version: 0.7.2
antd:
specifier: 5.11.0
version: 5.11.0(date-fns@4.1.0)(moment@2.30.1)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
version: 5.11.0(date-fns@4.1.0)(moment@2.31.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
antd-table-saveas-excel:
specifier: 2.2.1
version: 2.2.1
@@ -125,8 +128,8 @@ importers:
specifier: 4.13.2
version: 4.13.2
axios:
specifier: 1.21.0
version: 1.21.0
specifier: 1.21.1
version: 1.21.1
babel-jest:
specifier: ^29.6.4
version: 29.6.4(@babel/core@7.29.7)
@@ -166,9 +169,6 @@ importers:
eventemitter3:
specifier: 5.0.1
version: 5.0.1
history:
specifier: 4.10.1
version: 4.10.1
html-to-image:
specifier: 1.11.13
version: 1.11.13
@@ -182,8 +182,8 @@ importers:
specifier: ^6.1.3
version: 6.1.8
i18next-http-backend:
specifier: ^4.0.0
version: 4.0.0
specifier: ^4.0.4
version: 4.0.10
immer:
specifier: 11.1.3
version: 11.1.3
@@ -204,7 +204,7 @@ importers:
version: 12.4.13(@emotion/is-prop-valid@1.2.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
nuqs:
specifier: 2.8.8
version: 2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)
version: 2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
ol:
specifier: 10.11.0
version: 10.11.0
@@ -271,12 +271,9 @@ importers:
react-rnd:
specifier: ^10.5.3
version: 10.5.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-router-dom:
specifier: ^5.2.0
version: 5.3.4(react@18.2.0)
react-router-dom-v5-compat:
specifier: 6.30.6
version: 6.30.6(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react@18.2.0)
react-router:
specifier: 7.18.4
version: 7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-syntax-highlighter:
specifier: 15.5.0
version: 15.5.0(react@18.2.0)
@@ -329,8 +326,8 @@ importers:
specifier: npm:rolldown-vite@7.3.1
version: rolldown-vite@7.3.1(@types/node@22.20.5)(esbuild@0.28.1)(jiti@2.6.1)(less@4.9.1)(sass@1.97.3)(stylus@0.62.0)(terser@5.46.2)(yaml@2.9.1)
zod:
specifier: 4.3.6
version: 4.3.6
specifier: 4.6.7
version: 4.6.7
zustand:
specifier: 5.0.11
version: 5.0.11(@types/react@18.0.26)(immer@11.1.3)(react@18.2.0)(use-sync-external-store@1.6.0(react@18.2.0))
@@ -404,9 +401,6 @@ importers:
'@types/geojson':
specifier: 7946.0.16
version: 7946.0.16
'@types/history':
specifier: 4.7.11
version: 4.7.11
'@types/jest':
specifier: 30.0.0
version: 30.0.0
@@ -437,9 +431,6 @@ importers:
'@types/react-resizable':
specifier: 3.0.3
version: 3.0.3
'@types/react-router-dom':
specifier: ^5.1.6
version: 5.3.3
'@types/react-syntax-highlighter':
specifier: 15.5.13
version: 15.5.13
@@ -3353,10 +3344,6 @@ packages:
'@react-dnd/shallowequal@4.0.2':
resolution: {integrity: sha512-/RVXdLvJxLg4QKvMoM5WlwNR9ViO9z8B/qPcc+C0Sa/teJY7QG7kJ441DwzOjMYEY7GmU4dj5EcGHIkKZiQZCA==}
'@remix-run/router@1.23.4':
resolution: {integrity: sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==}
engines: {node: '>=14.0.0'}
'@rolldown/binding-android-arm64@1.0.0-beta.53':
resolution: {integrity: sha512-Ok9V8o7o6YfSdTTYA/uHH30r3YtOxLD6G3wih/U9DO0ucBBFq8WPt/DslU53OgfteLRHITZny9N/qCUxMf9kjQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4041,9 +4028,6 @@ packages:
'@types/hast@3.0.4':
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
'@types/history@4.7.11':
resolution: {integrity: sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA==}
'@types/hoist-non-react-statics@3.3.1':
resolution: {integrity: sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==}
@@ -4128,12 +4112,6 @@ packages:
'@types/react-resizable@3.0.3':
resolution: {integrity: sha512-W/QsUOZoXBAIBQNhNm95A5ohoaiUA874lWQytO2UP9dOjp5JHO9+a0cwYNabea7sA12ZDJnGVUFZxcNaNksAWA==}
'@types/react-router-dom@5.3.3':
resolution: {integrity: sha512-kpqnYK4wcdm5UaWI3fLcELopqLrHgLqNsdpHauzlQktfkHL3npOSwtj1Uz9oKBAzs7lFtVkV8j83voAz2D8fhw==}
'@types/react-router@5.1.20':
resolution: {integrity: sha512-jGjmu/ZqS7FjSH6owMcD5qpq19+1RS9DeVRqfl1FeBMxTDQAGwlMWOcs52NDoXaNKyG3d1cYQFMs9rCrb88o9Q==}
'@types/react-syntax-highlighter@15.5.13':
resolution: {integrity: sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==}
@@ -4633,8 +4611,8 @@ packages:
resolution: {integrity: sha512-UzGt8zg7Ny8djbYMhxl2zuEevVa7r2gJjYY5Lwr1xM7+XU2nd6CkIWFTVcCIbAP63vSz71NaVyyuSk9lHKcy0A==}
engines: {node: '>=4'}
axios@1.21.0:
resolution: {integrity: sha512-YCzXMB53Q9PZBsh7yN7wtapit4WepwcHS2fP8QhGsBxSz5YtgYobV7GGlWlAJi+RxfU77GQTQi2DSLUma42EYA==}
axios@1.21.1:
resolution: {integrity: sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==}
babel-jest@29.6.4:
resolution: {integrity: sha512-meLj23UlSLddj6PC+YTOFRgDAtjnZom8w/ACsrx0gtPtv5cJZk0A5Unk5bV4wixD7XaPCN1fQvpww8czkZURmw==}
@@ -5075,6 +5053,10 @@ packages:
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
cookie@1.1.1:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
copy-anything@3.0.5:
resolution: {integrity: sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==}
engines: {node: '>=12.13'}
@@ -5772,8 +5754,8 @@ packages:
fast-shallow-equal@1.0.0:
resolution: {integrity: sha512-HPtaa38cPgWvaCFmRNhlc6NG7pv6NUHqjPgVAkWGoB9mQMwYB27/K0CvOM5Czy+qpT3e8XJ6Q4aPAnzpNpzNaw==}
fast-uri@3.1.7:
resolution: {integrity: sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==}
fast-uri@3.1.9:
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
fast_array_intersect@1.1.0:
resolution: {integrity: sha512-/DCilZlUdz2XyNDF+ASs0PwY+RKG9Y4Silp/gbS72Cvbg4oibc778xcecg+pnNyiNHYgh/TApsiDTjpdniyShw==}
@@ -5873,8 +5855,8 @@ packages:
resolution: {integrity: sha512-/kXzuDnnBqyyWyhDMH7+PfP8J/oXiAavGzcRxASOMRHFuReDtofizLLJsf7nnDLAfEaMW4pVWaXrAjtnglpEkg==}
engines: {node: '>=12'}
follow-redirects@1.16.0:
resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
follow-redirects@1.16.3:
resolution: {integrity: sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -6172,9 +6154,6 @@ packages:
history@4.10.1:
resolution: {integrity: sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==}
history@5.3.0:
resolution: {integrity: sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==}
hoist-non-react-statics@3.3.2:
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
@@ -6241,8 +6220,8 @@ packages:
i18next-browser-languagedetector@6.1.8:
resolution: {integrity: sha512-Svm+MduCElO0Meqpj1kJAriTC6OhI41VhlT/A0UPjGoPZBhAHIaGE5EfsHlTpgdH09UVX7rcc72pSDDBeKSQQA==}
i18next-http-backend@4.0.0:
resolution: {integrity: sha512-EgSjO3Q1G6f2Q5oy7u9mmxuesE0oSfzAD97NFBjC8EmkK4guBSYLljM0Fng3DarMWIIkU70jfo4+mUzmyVISTA==}
i18next-http-backend@4.0.10:
resolution: {integrity: sha512-CfdQuwIVijbrS/fmiTAQYcYyje4nMbH9aIjKYhhm5bgVmWKWLOM1F7qrA1o63Jl1JxQcRjdtWhKlvDzyqV9aPg==}
engines: {node: '>=18'}
i18next@21.10.0:
@@ -6821,8 +6800,8 @@ packages:
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
joi@17.13.7:
resolution: {integrity: sha512-MF80Dm5Y2veNy8QWVx9Bj3ui4mo7+VPSPsR1M+oaHXV0Gx6zGX9a2F+OZG3Blby9tOlzU9Rs5FUimlEhbKtfnQ==}
joi@17.13.9:
resolution: {integrity: sha512-llFCT2rVtfwgBCaIqxtjim+iHqrgss4ONiGSYiiGH9jnjWq90ppSRffqmqKvwpa8W+YfILyQV6XyGcegXX2T4g==}
js-base64@3.7.5:
resolution: {integrity: sha512-3MEt5DTINKqfScXKfJFrRbxkrnk2AxPWGBL/ycjz4dK8iqiSJ06UxD8jh8xuh6p10TX4t2+7FsBYVxxQbMg+qA==}
@@ -7153,8 +7132,8 @@ packages:
mapbox-to-css-font@2.4.5:
resolution: {integrity: sha512-VJ6nB8emkO9VODI0Fk+TQ/0zKBTqmf/Pkt8Xv0kHstoc0iXRajA00DAid4Kc3K5xeFIOoiZrVxijEzj0GLVO2w==}
markdown-it@14.3.0:
resolution: {integrity: sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==}
markdown-it@14.3.3:
resolution: {integrity: sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg==}
hasBin: true
markdown-table@3.0.4:
@@ -7411,8 +7390,8 @@ packages:
moment-timezone@0.5.47:
resolution: {integrity: sha512-UbNt/JAWS0m/NJOebR0QMRHBk0hu03r5dx9GK8Cs0AS3I81yDcOc9k+DytPItgVvBP7J6Mf6U2n3BPAacAV9oA==}
moment@2.30.1:
resolution: {integrity: sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==}
moment@2.31.0:
resolution: {integrity: sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==}
monaco-editor@0.55.1:
resolution: {integrity: sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==}
@@ -7572,7 +7551,7 @@ packages:
'@tanstack/react-router': ^1
next: '>=14.2.0'
react: '>=18.2.0 || ^19.0.0-0'
react-router: '>=6.30.6 <7'
react-router: ^5 || ^6 || ^7
react-router-dom: ^5 || ^6 || ^7
peerDependenciesMeta:
'@remix-run/react':
@@ -7593,7 +7572,7 @@ packages:
'@tanstack/react-router': ^1
next: '>=14.2.0'
react: '>=18.2.0 || ^19.0.0-0'
react-router: '>=6.30.6 <7'
react-router: ^5 || ^6 || ^7 || ^8
react-router-dom: ^5 || ^6 || ^7
peerDependenciesMeta:
'@remix-run/react':
@@ -8191,7 +8170,7 @@ packages:
date-fns: '>= 2.x'
dayjs: '>= 1.x'
luxon: '>= 3.x'
moment: '>= 2.x'
moment: '>=2.31.0 <3'
react: '>=16.9.0'
react-dom: '>=16.9.0'
peerDependenciesMeta:
@@ -8530,14 +8509,6 @@ packages:
react: '>=16.3.0'
react-dom: '>=16.3.0'
react-router-dom-v5-compat@6.30.6:
resolution: {integrity: sha512-I54amXpivD3V0r1BYUIj1qLOljXx+UpbLG63Bqbm3BdKH62z4H3znC0L7SyMTYAMEDZuUjDSlqtkBRG/OEDXBg==}
engines: {node: '>=14.0.0'}
peerDependencies:
react: '>=16.8'
react-dom: '>=16.8'
react-router-dom: 4 || 5
react-router-dom@5.3.4:
resolution: {integrity: sha512-m4EqFMHv/Ih4kpcBCONHbkT68KoAeHN4p3lAGoNryfHi0dMy0kCzEZakiKRsvg5wHZ/JLrLW8o8KomWiz/qbYQ==}
peerDependencies:
@@ -8548,11 +8519,15 @@ packages:
peerDependencies:
react: '>=15'
react-router@6.30.6:
resolution: {integrity: sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==}
engines: {node: '>=14.0.0'}
react-router@7.18.4:
resolution: {integrity: sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==}
engines: {node: '>=20.0.0'}
peerDependencies:
react: '>=16.8'
react: '>=18'
react-dom: '>=18'
peerDependenciesMeta:
react-dom:
optional: true
react-style-singleton@2.2.3:
resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}
@@ -9647,13 +9622,12 @@ packages:
util@0.12.5:
resolution: {integrity: sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==}
uuid@14.0.1:
resolution: {integrity: sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==}
uuid@11.1.1:
resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}
hasBin: true
uuid@8.3.2:
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
uuid@14.0.1:
resolution: {integrity: sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==}
hasBin: true
uvu@0.5.6:
@@ -10007,8 +9981,8 @@ packages:
zarrita@0.7.5:
resolution: {integrity: sha512-ZriOSEne+Wf2iuM0yjDZvUKpHNlug3dO7qJ6mAxXoOgsYV18DPOkAkwB9e0rf21bHcKcOffFuwoZwn5g6pvUeA==}
zod@4.3.6:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
zod@4.6.7:
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
zstddec@0.1.0:
resolution: {integrity: sha512-w2NTI8+3l3eeltKAdK8QpiLo/flRAr2p8AGeakfMZOXBxOg9HIu4LVDxBi81sYgVhFhdJjv1OrB5ssI8uFPoLg==}
@@ -11486,7 +11460,7 @@ snapshots:
lodash: 4.18.1
marked: 15.0.6
marked-mangle: 1.1.10(marked@15.0.6)
moment: 2.30.1
moment: 2.31.0
moment-timezone: 0.5.47
ol: 7.4.0
papaparse: 5.5.2
@@ -13025,8 +12999,6 @@ snapshots:
'@react-dnd/shallowequal@4.0.2': {}
'@remix-run/router@1.23.4': {}
'@rolldown/binding-android-arm64@1.0.0-beta.53':
optional: true
@@ -13259,7 +13231,7 @@ snapshots:
'@signozhq/icons@0.4.0': {}
'@signozhq/ui@0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)':
'@signozhq/ui@0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
dependencies:
'@base-ui/react': 1.7.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@chenglou/pretext': 0.0.8
@@ -13283,7 +13255,7 @@ snapshots:
lodash-es: 4.18.1
motion: 11.18.2(@emotion/is-prop-valid@1.2.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
next-themes: 0.4.6(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
nuqs: 2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)
nuqs: 2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
react: 18.2.0
react-compiler-runtime: 1.0.0(react@18.2.0)
react-day-picker: 9.9.0(react@18.2.0)
@@ -13438,7 +13410,7 @@ snapshots:
playwright-core: 1.57.0
rimraf: 3.0.2
storybook: 10.6.3(@types/react@18.0.26)(prettier@3.8.3)(react@18.2.0)
uuid: 8.3.2
uuid: 11.1.1
transitivePeerDependencies:
- '@swc/helpers'
- '@types/node'
@@ -13739,8 +13711,6 @@ snapshots:
dependencies:
'@types/unist': 3.0.2
'@types/history@4.7.11': {}
'@types/hoist-non-react-statics@3.3.1':
dependencies:
'@types/react': 18.0.26
@@ -13839,17 +13809,6 @@ snapshots:
dependencies:
'@types/react': 18.0.26
'@types/react-router-dom@5.3.3':
dependencies:
'@types/history': 4.7.11
'@types/react': 18.0.26
'@types/react-router': 5.1.20
'@types/react-router@5.1.20':
dependencies:
'@types/history': 4.7.11
'@types/react': 18.0.26
'@types/react-syntax-highlighter@15.5.13':
dependencies:
'@types/react': 18.0.26
@@ -14246,7 +14205,7 @@ snapshots:
ajv@8.18.0:
dependencies:
fast-deep-equal: 3.1.3
fast-uri: 3.1.7
fast-uri: 3.1.9
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@@ -14286,7 +14245,7 @@ snapshots:
better-xlsx: 0.7.6
file-saver: 2.0.5
antd@5.11.0(date-fns@4.1.0)(moment@2.30.1)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
antd@5.11.0(date-fns@4.1.0)(moment@2.31.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
'@ant-design/colors': 7.0.0
'@ant-design/cssinjs': 1.17.2(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -14317,7 +14276,7 @@ snapshots:
rc-motion: 2.9.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-notification: 5.3.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-pagination: 3.7.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-picker: 3.14.6(date-fns@4.1.0)(dayjs@1.11.20)(moment@2.30.1)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-picker: 3.14.6(date-fns@4.1.0)(dayjs@1.11.20)(moment@2.31.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-progress: 3.5.1(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-rate: 2.12.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
rc-resize-observer: 1.4.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -14400,9 +14359,9 @@ snapshots:
axe-core@4.13.0: {}
axios@1.21.0:
axios@1.21.1:
dependencies:
follow-redirects: 1.16.0
follow-redirects: 1.16.3
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
@@ -14905,6 +14864,8 @@ snapshots:
cookie@0.7.2: {}
cookie@1.1.1: {}
copy-anything@3.0.5:
dependencies:
is-what: 4.1.16
@@ -15645,7 +15606,7 @@ snapshots:
fast-shallow-equal@1.0.0: {}
fast-uri@3.1.7: {}
fast-uri@3.1.9: {}
fast_array_intersect@1.1.0: {}
@@ -15750,7 +15711,7 @@ snapshots:
kapsule: 1.16.3
preact: 10.28.4
follow-redirects@1.16.0: {}
follow-redirects@1.16.3: {}
for-each@0.3.5:
dependencies:
@@ -16111,10 +16072,6 @@ snapshots:
tiny-warning: 1.0.3
value-equal: 1.0.1
history@5.3.0:
dependencies:
'@babel/runtime': 7.29.2
hoist-non-react-statics@3.3.2:
dependencies:
react-is: 16.13.1
@@ -16181,7 +16138,7 @@ snapshots:
dependencies:
'@babel/runtime': 7.28.2
i18next-http-backend@4.0.0: {}
i18next-http-backend@4.0.10: {}
i18next@21.10.0:
dependencies:
@@ -16434,7 +16391,8 @@ snapshots:
dependencies:
is-inside-container: 1.0.0
isarray@0.0.1: {}
isarray@0.0.1:
optional: true
isarray@1.0.0: {}
@@ -16484,7 +16442,7 @@ snapshots:
istanbul-lib-coverage: 3.2.0
p-map: 3.0.0
rimraf: 3.0.2
uuid: 8.3.2
uuid: 11.1.1
istanbul-lib-report@3.0.0:
dependencies:
@@ -16706,7 +16664,7 @@ snapshots:
dependencies:
mkdirp: 1.0.4
strip-ansi: 6.0.1
uuid: 8.3.2
uuid: 11.1.1
xml: 1.0.1
jest-leak-detector@30.2.0:
@@ -17040,7 +16998,7 @@ snapshots:
jiti@2.6.1: {}
joi@17.13.7:
joi@17.13.9:
dependencies:
'@hapi/hoek': 9.3.0
'@hapi/topo': 5.1.0
@@ -17363,7 +17321,7 @@ snapshots:
mapbox-to-css-font@2.4.5: {}
markdown-it@14.3.0:
markdown-it@14.3.3:
dependencies:
argparse: 2.0.1
entities: 4.5.0
@@ -17774,9 +17732,9 @@ snapshots:
moment-timezone@0.5.47:
dependencies:
moment: 2.30.1
moment: 2.31.0
moment@2.30.1: {}
moment@2.31.0: {}
monaco-editor@0.55.1:
dependencies:
@@ -17933,20 +17891,20 @@ snapshots:
dependencies:
fflate: 0.8.3
nuqs@2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0):
nuqs@2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0):
dependencies:
'@standard-schema/spec': 1.0.0
react: 18.2.0
optionalDependencies:
react-router: 6.30.6(react@18.2.0)
react-router: 7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-router-dom: 5.3.4(react@18.2.0)
nuqs@2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0):
nuqs@2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0):
dependencies:
'@standard-schema/spec': 1.1.0
react: 18.2.0
optionalDependencies:
react-router: 6.30.6(react@18.2.0)
react-router: 7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-router-dom: 5.3.4(react@18.2.0)
nwsapi@2.2.23: {}
@@ -18331,6 +18289,7 @@ snapshots:
path-to-regexp@1.9.0:
dependencies:
isarray: 0.0.1
optional: true
path-to-regexp@6.3.0: {}
@@ -18694,7 +18653,7 @@ snapshots:
react: 18.2.0
react-dom: 18.2.0(react@18.2.0)
rc-picker@3.14.6(date-fns@4.1.0)(dayjs@1.11.20)(moment@2.30.1)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
rc-picker@3.14.6(date-fns@4.1.0)(dayjs@1.11.20)(moment@2.31.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
'@rc-component/trigger': 1.18.1(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -18705,7 +18664,7 @@ snapshots:
optionalDependencies:
date-fns: 4.1.0
dayjs: 1.11.20
moment: 2.30.1
moment: 2.31.0
rc-progress@3.5.1(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
@@ -19110,18 +19069,9 @@ snapshots:
react-draggable: 4.5.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
tslib: 2.6.2
react-router-dom-v5-compat@6.30.6(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react@18.2.0):
dependencies:
'@remix-run/router': 1.23.4
history: 5.3.0
react: 18.2.0
react-dom: 18.2.0(react@18.2.0)
react-router: 6.30.6(react@18.2.0)
react-router-dom: 5.3.4(react@18.2.0)
react-router-dom@5.3.4(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.29.2
history: 4.10.1
loose-envify: 1.4.0
prop-types: 15.8.1
@@ -19129,10 +19079,11 @@ snapshots:
react-router: 5.3.4(react@18.2.0)
tiny-invariant: 1.3.3
tiny-warning: 1.0.3
optional: true
react-router@5.3.4(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.29.2
history: 4.10.1
hoist-non-react-statics: 3.3.2
loose-envify: 1.4.0
@@ -19142,11 +19093,15 @@ snapshots:
react-is: 16.13.1
tiny-invariant: 1.3.3
tiny-warning: 1.0.3
optional: true
react-router@6.30.6(react@18.2.0):
react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
'@remix-run/router': 1.23.4
cookie: 1.1.1
react: 18.2.0
set-cookie-parser: 2.6.0
optionalDependencies:
react-dom: 18.2.0(react@18.2.0)
react-style-singleton@2.2.3(@types/react@18.0.26)(react@18.2.0):
dependencies:
@@ -20181,7 +20136,7 @@ snapshots:
dependencies:
'@gerrit0/mini-shiki': 3.23.0
lunr: 2.3.9
markdown-it: 14.3.0
markdown-it: 14.3.3
minimatch: 10.2.5
typescript: 5.9.3
yaml: 2.8.4
@@ -20382,9 +20337,9 @@ snapshots:
is-typed-array: 1.1.15
which-typed-array: 1.1.20
uuid@14.0.1: {}
uuid@11.1.1: {}
uuid@8.3.2: {}
uuid@14.0.1: {}
uvu@0.5.6:
dependencies:
@@ -20491,8 +20446,8 @@ snapshots:
wait-on@7.2.0:
dependencies:
axios: 1.21.0
joi: 17.13.7
axios: 1.21.1
joi: 17.13.9
lodash: 4.18.1
minimist: 1.2.8
rxjs: 7.8.1
@@ -20740,7 +20695,7 @@ snapshots:
'@zarrita/storage': 0.2.0
numcodecs: 0.3.2
zod@4.3.6: {}
zod@4.6.7: {}
zstddec@0.1.0: {}

View File

@@ -45,14 +45,17 @@ overrides:
# orval >=8.20.0 and ts-jest >=29.4.11 already fixed on their side
esbuild@>=0.27.3 <0.28.1: '>=0.28.1 <0.29.0'
# via: @commitlint/cli > @commitlint/config-validator > ajv@8 (fast-uri ^3.0.1)
# remove: blocked — ajv@8 caps fast-uri at ^3, and only 3.1.6 carries the fix
fast-uri@<3.1.6: '>=3.1.6 <4'
# remove: blocked — ajv@8 caps fast-uri at ^3, and only 3.1.9 carries the fix
fast-uri@<3.1.9: '>=3.1.9 <4'
# via: direct dep posthog-js@1.298.0 (fflate ^0.4.8)
# remove: blocked, posthog-js 1.430.2 (latest) is still on ^0.4.8
fflate@<0.4.9: '>=0.4.9 <0.5'
# via: direct devDep sass@1.97.3 (immutable ^5.0.2)
# remove: blocked — plain sass bumps stay within ^5, so the floor is what pulls 5.1.8
immutable@<5.1.8: '>=5.1.8 <6'
# via: @storybook/test-runner > jest-process-manager > wait-on@7.2.0 (joi ^17.11.0)
# remove: blocked, the range is open, so the floor is what pulls the fix
joi@<17.13.9: '>=17.13.9 <18'
# via: react-use@17.5.1 (direct, js-cookie ^2.2.1); @grafana/data > react-use@17.6.0
# remove: bump react-use to >=17.6.1 (js-cookie ^3); @grafana/data side blocked
js-cookie@<=3.0.5: '>=3.0.7 <4'
@@ -60,6 +63,12 @@ overrides:
# @commitlint/cli > @commitlint/load > cosmiconfig@9 (^4.1.0)
# remove: blocked, both consumers cap js-yaml at ^4 and only 4.3.2 carries the fix
'js-yaml@>=4.0.0 <4.3.2': '>=4.3.2 <5'
# via: orval > typedoc@0.28.19 (markdown-it ^14.1.1)
# remove: blocked, typedoc 0.28.20 (latest) only widens to ^14.3.0, still vulnerable
markdown-it@<14.3.3: '>=14.3.3 <15'
# via: @grafana/data@11.6.15 (moment 2.30.1 exact)
# remove: bump @grafana/data to >=13, which drops the exact moment pin
moment@<2.31.0: '>=2.31.0 <3'
# via: react-syntax-highlighter@15.5.0 (prismjs ^1.27.0 + refractor@3 ~1.27.0 tilde-pinned)
# remove: bump react-syntax-highlighter to >=16.1.1 (prismjs ^1.30.0, refractor@5)
prismjs@<1.30.0: '>=1.30.0 <2'
@@ -67,14 +76,13 @@ overrides:
# (postcss-selector-parser ^7.0.0)
# remove: blocked, 4.2.0 is latest and the range is open, so the floor is what pulls the fix
postcss-selector-parser@>=7.1.0 <7.1.3: '>=7.1.3 <8'
# via: @signozhq/ui > nuqs@2 (react-router ^6.4.0 || ^7)
# remove: blocked. GHSA-wrjc-x8rr-h8h6 and the deserializeErrors advisory are patched
# only in 7.18.0. Do NOT open the cap: react-router >=7 requires React 19 and breaks
# the app-wide CompatRouter, so those two moderates stay until the app moves to React 19
react-router@>=6.7.0 <6.30.6: '>=6.30.6 <7'
# via: msw@1.3.2 (devDep) > inquirer@8 > external-editor@3.1.0 (tmp ^0.0.33)
# remove: upgrade msw to >=2 (drops the inquirer/external-editor chain)
tmp@<0.2.6: '>=0.2.6 <0.3.0'
# via: @storybook/test-runner (uuid ^8.3.2)
# remove: blocked, test-runner (latest) still depends on uuid ^8.3.2. Forces a
# major: 11.x keeps the CJS build and the v4 export the runner imports
uuid@<11.1.1: '>=11.1.1 <12'
# via: jest > babel-plugin-macros > cosmiconfig@7 (yaml ^1.10.0);
# typescript-plugin-css-modules > postcss-load-config@3 (^1.10.2)
# remove: blocked — babel-plugin-macros 3.1.0 (latest) still uses cosmiconfig@7

View File

@@ -1,5 +1,4 @@
import { ReactChild, useCallback, useMemo } from 'react';
import { matchPath, Redirect, useLocation } from 'react-router-dom';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
import { useListUsers } from 'api/generated/services/users';
@@ -9,6 +8,9 @@ import ROUTES from 'constants/routes';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { isEmpty } from 'lodash-es';
import { matchRoute } from 'lib/router/matchRoute';
import { Redirect } from 'lib/router/Redirect';
import { useAppLocation } from 'lib/router/useAppLocation';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
import { OrgPreference } from 'types/api/preferences/preference';
@@ -26,10 +28,12 @@ import routes, {
ROUTES_NOT_TO_BE_OVERRIDEN,
SUPPORT_ROUTE,
} from './routes';
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
import { UserListPermission } from '@/lib/authz/hooks/useAuthZ/permissions/user.permissions';
// eslint-disable-next-line sonarjs/cognitive-complexity
function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const location = useLocation();
const location = useAppLocation();
const { pathname } = location;
const {
org,
@@ -48,10 +52,11 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
() =>
new Map(
[...routes, LIST_LICENSES, SUPPORT_ROUTE].map((e) => {
const currentPath = matchPath(pathname, {
path: e.path,
});
return [currentPath === null ? null : 'current', e];
const patterns = Array.isArray(e.path) ? e.path : [e.path];
const matches = patterns.some(
(pattern) => matchRoute(pathname, pattern) !== null,
);
return [matches ? 'current' : null, e];
}),
),
[pathname],
@@ -66,9 +71,16 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
return undefined;
}, [org]);
const { permissions: authzPermission } = useAuthZ([UserListPermission], {
enabled: isLoggedInState,
});
const canListUsers = authzPermission?.[UserListPermission]?.isGranted ?? false;
// Without `list:user` the list isn't fetched, so the onboarding redirect is skipped.
const { data: usersData, isFetching: isFetchingUsers } = useListUsers({
query: {
enabled: !isEmpty(orgData) && user.role === 'ADMIN',
enabled: !isEmpty(orgData) && canListUsers,
},
});
@@ -162,10 +174,9 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const isRouteEnabledForWorkspaceBlockedState =
pathname === ROUTES.SETTINGS ||
pathname === ROUTES.BILLING ||
pathname === ROUTES.MEMBERS_SETTINGS ||
(isAdmin &&
(pathname === ROUTES.ORG_SETTINGS ||
pathname === ROUTES.MEMBERS_SETTINGS ||
pathname === ROUTES.MY_SETTINGS));
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
if (
pathname !== ROUTES.WORKSPACE_LOCKED &&

View File

@@ -0,0 +1,29 @@
import type { ComponentType } from 'react';
import { useOutletContext } from 'react-router';
import NotFound from 'components/NotFound';
import type { AppRoutes } from './routes';
/**
* The routes the plan, the license and the feature flags enable. The root
* layout computes it and hands it down as outlet context.
*/
export type EnabledRouteKeys = ReadonlySet<AppRoutes['key']>;
interface RouteGateProps {
routeKey: AppRoutes['key'];
component: ComponentType;
}
/**
* The table is created once, so a route the session may not use is still in
* it. It renders the not-found page instead, which is what the old dynamic
* `<Switch>` fell through to.
*/
export function RouteGate({
routeKey,
component: Component,
}: RouteGateProps): JSX.Element {
const enabledRouteKeys = useOutletContext<EnabledRouteKeys>();
return enabledRouteKeys.has(routeKey) ? <Component /> : <NotFound />;
}

View File

@@ -1,11 +1,25 @@
import { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
import {
MemoryRouter,
Route,
Routes,
useLocation,
useNavigationType,
} from 'react-router';
import { act, render, screen, waitFor } from '@testing-library/react';
import { useListUsers } from 'api/generated/services/users';
import { SIGNOZ_ADMIN_EMAIL } from 'constants/app';
import { LOCALSTORAGE } from 'constants/localStorage';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { rest, server } from 'mocks-server/server';
import { AppContext } from 'providers/App/App';
import { IAppContext, IUser } from 'providers/App/types';
import {
@@ -74,11 +88,13 @@ const queryClient = new QueryClient({
// Component to capture current location for assertions
function LocationDisplay(): ReactElement {
const location = useLocation();
const navigationType = useNavigationType();
return (
<>
<div data-testid="location-display">{location.pathname}</div>
<div data-testid="location-search">{location.search}</div>
<div data-testid="location-hash">{location.hash}</div>
<div data-testid="navigation-type">{navigationType}</div>
</>
);
}
@@ -238,12 +254,17 @@ function buildPrivateRouteTree(
<MemoryRouter initialEntries={[initialRoute]}>
<AppContext.Provider value={contextValue}>
<PrivateRoute>
<Switch>
<Route path="*">
<div data-testid="children-rendered">Content</div>
<LocationDisplay />
</Route>
</Switch>
<Routes>
<Route
path="*"
element={
<>
<div data-testid="children-rendered">Content</div>
<LocationDisplay />
</>
}
/>
</Routes>
</PrivateRoute>
</AppContext.Provider>
</MemoryRouter>
@@ -506,6 +527,19 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
});
it('should replace the login entry when redirecting to the saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] =
ROUTES.ALL_DASHBOARD;
renderPrivateRoute({
initialRoute: ROUTES.LOGIN,
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
expect(screen.getByTestId('navigation-type')).toHaveTextContent('REPLACE');
});
it('should clear localStorage after redirecting to saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] = ROUTES.HOME;
@@ -630,6 +664,19 @@ describe('PrivateRoute', () => {
expect(mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT]).toBe('');
});
});
it('should replace the unknown route entry when redirecting to the saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] =
ROUTES.ALL_DASHBOARD;
renderPrivateRoute({
initialRoute: '/unknown-route-that-does-not-exist',
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
expect(screen.getByTestId('navigation-type')).toHaveTextContent('REPLACE');
});
});
describe('Workspace Blocked - Trial Expired (Cloud Users)', () => {
@@ -777,7 +824,7 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should redirect VIEWER to workspace locked when trying to access members settings', async () => {
it('should allow VIEWER to access members settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.MEMBERS_SETTINGS,
appContext: {
@@ -790,7 +837,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
});
it('should redirect VIEWER to workspace locked when trying to access my-settings', async () => {
@@ -1117,6 +1164,72 @@ describe('PrivateRoute', () => {
assertStaysOnRoute(ROUTES.HOME);
});
it('fetches the user list for a non-admin role that has list:user', async () => {
server.use(setupAuthzAdmin());
jest.mocked(useListUsers).mockClear();
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
await waitFor(() =>
expect(useListUsers).toHaveBeenLastCalledWith({
query: { enabled: true },
}),
);
});
it('does not check list:user while logged out', async () => {
const authzCheck = jest.fn();
server.use(
rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => {
authzCheck();
return res(ctx.status(401));
}),
);
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: { isLoggedIn: false },
isCloudUser: true,
});
await act(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 50);
});
});
expect(authzCheck).not.toHaveBeenCalled();
});
it('does not fetch the user list for an admin without list:user', async () => {
server.use(setupAuthzDeny(UserListPermission));
jest.mocked(useListUsers).mockClear();
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
expect(useListUsers).not.toHaveBeenCalledWith({
query: { enabled: true },
});
});
it('should not redirect to onboarding when org preferences are still fetching', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,

View File

@@ -0,0 +1,85 @@
import { lazy, Suspense, useState } from 'react';
import {
createBrowserRouter,
type DataRouter,
Outlet,
RouterProvider,
} from 'react-router';
import { act, render, screen } from '@testing-library/react';
import ROUTES from 'constants/routes';
import { resetTestRoute } from 'tests/router-utils';
import type { EnabledRouteKeys } from '../RouteGate';
import { createGatedRoutes } from '../routeTable';
import type { AppRoutes } from '../routes';
let mounts = 0;
function Page(): JSX.Element {
const [mount] = useState(() => {
mounts += 1;
return mounts;
});
return <div data-testid="page">mount {mount}</div>;
}
// Two lazy wrappers of one module, like the logs explorer and pipelines routes.
const Explorer = lazy(async () => ({ default: Page }));
const Pipelines = lazy(async () => ({ default: Page }));
const routes: AppRoutes[] = [
{ path: ROUTES.LOGS, component: Explorer, key: 'LOGS', isPrivate: true },
{
path: [ROUTES.LOGS_PIPELINES, ROUTES.LOGS_INDEX_FIELDS],
component: Pipelines,
key: 'LOGS_PIPELINES',
isPrivate: true,
},
];
const enabledRouteKeys: EnabledRouteKeys = new Set(['LOGS', 'LOGS_PIPELINES']);
function renderRoutes(): DataRouter {
window.history.replaceState(null, '', ROUTES.LOGS);
const router = createBrowserRouter([
{
element: (
<Suspense fallback={<div data-testid="fallback" />}>
<Outlet context={enabledRouteKeys} />
</Suspense>
),
children: createGatedRoutes(routes),
},
]);
render(<RouterProvider router={router} useTransitions={false} />);
return router;
}
describe('createGatedRoutes', () => {
beforeEach(() => {
mounts = 0;
});
afterEach(() => {
resetTestRoute();
});
it('remounts the page when another route entry resolves to the same component', async () => {
const router = renderRoutes();
await expect(screen.findByText('mount 1')).resolves.toBeInTheDocument();
await act(() => router.navigate(ROUTES.LOGS_PIPELINES));
await expect(screen.findByText('mount 2')).resolves.toBeInTheDocument();
});
it('keeps the page mounted across the patterns of one route entry', async () => {
const router = renderRoutes();
await act(() => router.navigate(ROUTES.LOGS_PIPELINES));
await expect(screen.findByText('mount 2')).resolves.toBeInTheDocument();
await act(() => router.navigate(ROUTES.LOGS_INDEX_FIELDS));
expect(screen.getByTestId('page')).toHaveTextContent('mount 2');
});
});

View File

@@ -2,9 +2,9 @@ import type { ErrorEvent, StackFrame } from '@sentry/react';
import { AxiosError, AxiosHeaders } from 'axios';
import {
hasNoAppFrames,
isInjectedScriptError,
isExpectedRequestFailure,
isExternalIntegrationError,
isThirdPartyScriptError,
SENTRY_IGNORE_ERRORS,
} from '../sentryFilters';
@@ -27,7 +27,7 @@ function eventWithFrames(...filenames: string[]): ErrorEvent {
};
}
describe('isExternalIntegrationError', () => {
describe('isThirdPartyScriptError', () => {
it.each([
[
'PostHog recorder',
@@ -39,14 +39,12 @@ describe('isExternalIntegrationError', () => {
],
['Appcues', 'https://fast.appcues.com/123456.js'],
])('drops an error with a %s frame', (_, url) => {
expect(isExternalIntegrationError(eventWithFrames(APP_BUNDLE, url))).toBe(
true,
);
expect(isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, url))).toBe(true);
});
it('drops it when the top frame is our bundle', () => {
expect(
isExternalIntegrationError(
isThirdPartyScriptError(
eventWithFrames(
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
'<anonymous>',
@@ -58,13 +56,13 @@ describe('isExternalIntegrationError', () => {
it('keeps an error from our bundle only', () => {
expect(
isExternalIntegrationError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(false);
});
it('keeps an error from a host that only contains an integration name', () => {
expect(
isExternalIntegrationError(
isThirdPartyScriptError(
eventWithFrames(
'https://posthog.example.com/app.js',
'https://notusepylon.com/widget.js',
@@ -74,11 +72,11 @@ describe('isExternalIntegrationError', () => {
});
it('keeps an error without a stack trace', () => {
expect(isExternalIntegrationError({ type: undefined })).toBe(false);
expect(isThirdPartyScriptError({ type: undefined })).toBe(false);
});
});
describe('hasNoAppFrames', () => {
describe('isInjectedScriptError', () => {
const PAGE_URL = 'https://example.us.signoz.cloud/dashboard/01a081e1';
function eventWithStackFrames(frames: StackFrame[]): ErrorEvent {
@@ -92,7 +90,7 @@ describe('hasNoAppFrames', () => {
it('drops a script appended to the page', () => {
expect(
hasNoAppFrames(
isInjectedScriptError(
eventWithStackFrames([
{ filename: PAGE_URL, lineno: 1, colno: 30, function: 'global code' },
{ filename: '[native code]', function: 'eval' },
@@ -104,7 +102,7 @@ describe('hasNoAppFrames', () => {
it('drops a browser extension error', () => {
expect(
hasNoAppFrames(
isInjectedScriptError(
eventWithStackFrames([
{ filename: 'chrome-extension://abc/content.js', lineno: 4, colno: 12 },
]),
@@ -112,21 +110,46 @@ describe('hasNoAppFrames', () => {
).toBe(true);
});
it('drops an error thrown from injected code behind the Sentry wrapper', () => {
expect(
isInjectedScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(true);
});
it('keeps an error thrown from our bundle after an anonymous frame', () => {
expect(
isInjectedScriptError(eventWithFrames('<anonymous>', APP_BUNDLE)),
).toBe(false);
});
it('keeps an error with a frame from our bundle', () => {
expect(hasNoAppFrames(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(false);
expect(isInjectedScriptError(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(
false,
);
});
it('keeps an error without a stack trace', () => {
expect(hasNoAppFrames({ type: undefined })).toBe(false);
expect(isInjectedScriptError({ type: undefined })).toBe(false);
});
it('keeps an error whose frames have no position', () => {
expect(
hasNoAppFrames(
isInjectedScriptError(
eventWithStackFrames([{ filename: '[native code]', function: 'eval' }]),
),
).toBe(false);
});
it('keeps an error a builtin threw for our bundle', () => {
expect(
isInjectedScriptError(
eventWithStackFrames([
{ filename: APP_BUNDLE, lineno: 1, colno: 1 },
{ filename: '<anonymous>', function: 'JSON.parse' },
]),
),
).toBe(false);
});
});
describe('SENTRY_IGNORE_ERRORS', () => {

View File

@@ -1,6 +1,12 @@
import { ReactNode, Suspense, useCallback, useEffect, useState } from 'react';
import { Route, Router, Switch } from 'react-router-dom';
import { CompatRouter } from 'react-router-dom-v5-compat';
import {
ReactNode,
Suspense,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { Outlet } from 'react-router';
import * as Sentry from '@sentry/react';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
@@ -9,7 +15,6 @@ import AppPageProviders from 'app/AppPageProviders';
import AppShell from 'app/AppShell';
import AppLoading from 'components/AppLoading/AppLoading';
import { CmdKPalette } from 'components/cmdKPalette/cmdKPalette';
import NotFound from 'components/NotFound';
import { ShiftHoldOverlayController } from 'components/ShiftOverlay/ShiftHoldOverlayController';
import Spinner from 'components/Spinner';
import { LOCALSTORAGE } from 'constants/localStorage';
@@ -23,7 +28,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { StatusCodes } from 'http-status-codes';
import { IS_PROD } from 'lib/env';
import history from 'lib/history';
import { getCurrentLocation, navigate, subscribe } from 'lib/router/navigation';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import posthog from 'posthog-js';
import { useAppContext } from 'providers/App/App';
@@ -31,26 +36,20 @@ import { IUser } from 'providers/App/types';
import { LicenseStatus } from 'types/api/licensesV3/getActive';
import { extractDomain } from 'utils/app';
import { Home } from './pageComponents';
import PrivateRoute from './Private';
import defaultRoutes, {
AppRoutes,
LIST_LICENSES,
SUPPORT_ROUTE,
} from './routes';
import type { EnabledRouteKeys } from './RouteGate';
import {
hasNoAppFrames,
isInjectedScriptError,
isExpectedRequestFailure,
isExternalIntegrationError,
isThirdPartyScriptError,
SENTRY_IGNORE_ERRORS,
} from './sentryFilters';
const appRouter = (children: ReactNode): ReactNode => (
<Router history={history}>
<CompatRouter>{children}</CompatRouter>
</Router>
);
const appLayout = (children: ReactNode): ReactNode => (
<AppLayout>{children}</AppLayout>
);
@@ -71,18 +70,24 @@ function App(): JSX.Element {
isPreflightLoading,
} = useAppContext();
const [routes, setRoutes] = useState<AppRoutes[]>(defaultRoutes);
const enabledRouteKeys = useMemo<EnabledRouteKeys>(
() => new Set(routes.map(({ key }) => key)),
[routes],
);
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const chatSupport = useChatSupport();
const { hostname } = window.location;
const [pathname, setPathname] = useState(history.location.pathname);
// Through the facade, not the raw history: the router owns the base path
// now, so `history.location.pathname` would still carry it.
const [pathname, setPathname] = useState(getCurrentLocation().pathname);
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const [isSentryInitialized, setIsSentryInitialized] = useState(false);
useEffect(() => {
return history.listen((location) => {
return subscribe(({ location }) => {
setPathname(location.pathname);
});
}, []);
@@ -355,12 +360,12 @@ function App(): JSX.Element {
return null;
}
if (isExternalIntegrationError(event)) {
if (isThirdPartyScriptError(event)) {
return null;
}
// Dev serves source from /src/, so every frame would look foreign there.
if (IS_PROD && hasNoAppFrames(event)) {
if (IS_PROD && isInjectedScriptError(event)) {
return null;
}
@@ -402,7 +407,7 @@ function App(): JSX.Element {
// this needs to be on top of data missing error because if there is an error, data will never be loaded and it will
// move to indefinitive loading
if (userFetchError && pathname !== ROUTES.SOMETHING_WENT_WRONG) {
history.replace(ROUTES.SOMETHING_WENT_WRONG);
navigate(ROUTES.SOMETHING_WENT_WRONG, { replace: true });
}
// if all of the data is not set then return a spinner, this is required because there is some gap between loading states and data setting
@@ -418,7 +423,6 @@ function App(): JSX.Element {
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
<AppShell
router={appRouter}
overlays={
isLoggedInState && (
<>
@@ -431,18 +435,7 @@ function App(): JSX.Element {
<PrivateRoute>
<AppPageProviders layout={appLayout}>
<Suspense fallback={<Spinner size="large" tip="Loading..." />}>
<Switch>
{routes.map(({ path, component, exact }) => (
<Route
key={`${path}`}
exact={exact}
path={path}
component={component}
/>
))}
<Route exact path="/" component={Home} />
<Route path="*" component={NotFound} />
</Switch>
<Outlet context={enabledRouteKeys} />
</Suspense>
</AppPageProviders>
</PrivateRoute>

View File

@@ -0,0 +1,46 @@
import type { ReactNode } from 'react';
import type { RouteObject } from 'react-router';
import NotFound from 'components/NotFound';
import { RethrowRouteError } from 'lib/router/RethrowRouteError';
import { Home } from './pageComponents';
import { RouteGate } from './RouteGate';
import routes, { AppRoutes, LIST_LICENSES, SUPPORT_ROUTE } from './routes';
/**
* The gate is keyed by its route entry. The outlet renders the match unkeyed,
* so every route would otherwise reuse the previous route's gate, and a lazy
* page that resolves to the same component would keep its instance. The
* patterns of one entry share the key.
*/
export function createGatedRoutes(appRoutes: AppRoutes[]): RouteObject[] {
return appRoutes.flatMap(({ path, component, nested, key }) =>
(Array.isArray(path) ? path : [path]).map((pattern) => ({
path: nested ? `${pattern}/*` : pattern,
element: <RouteGate key={key} routeKey={key} component={component} />,
})),
);
}
const gatedRoutes = createGatedRoutes([
...routes,
LIST_LICENSES,
SUPPORT_ROUTE,
]);
/** `root` is the layout every route renders in; it has to render an `<Outlet>`. */
export function createRouteTable(root: ReactNode): RouteObject[] {
return [
{
element: root,
// An error above `Sentry.ErrorBoundary` in the root layout crashes the
// root and reaches Sentry, as it did before the data router.
errorElement: <RethrowRouteError />,
children: [
...gatedRoutes,
{ path: '/', element: <Home /> },
{ path: '*', element: <NotFound /> },
],
},
];
}

View File

@@ -1,4 +1,4 @@
import { RouteProps } from 'react-router-dom';
import type { ComponentType } from 'react';
import ROUTES from 'constants/routes';
import {
@@ -58,27 +58,25 @@ const routes: AppRoutes[] = [
{
component: SignupPage,
path: ROUTES.SIGN_UP,
exact: true,
isPrivate: false,
key: 'SIGN_UP',
},
{
path: ROUTES.GET_STARTED_WITH_CLOUD,
exact: false,
nested: true,
component: OnboardingV2,
isPrivate: true,
key: 'GET_STARTED_WITH_CLOUD',
},
{
path: ROUTES.HOME,
exact: true,
component: Home,
isPrivate: true,
key: 'HOME',
},
{
path: ROUTES.ONBOARDING,
exact: false,
nested: true,
component: OrgOnboarding,
isPrivate: true,
key: 'ONBOARDING',
@@ -86,27 +84,23 @@ const routes: AppRoutes[] = [
{
component: LogsIndexToFields,
path: ROUTES.LOGS_INDEX_FIELDS,
exact: true,
isPrivate: true,
key: 'LOGS_INDEX_FIELDS',
},
{
component: ServicesTablePage,
path: ROUTES.APPLICATION,
exact: true,
isPrivate: true,
key: 'APPLICATION',
},
{
path: ROUTES.SERVICE_METRICS,
exact: true,
component: ServiceMetricsPage,
isPrivate: true,
key: 'SERVICE_METRICS',
},
{
path: ROUTES.SERVICE_TOP_LEVEL_OPERATIONS,
exact: true,
component: ServiceTopLevelOperationsPage,
isPrivate: true,
key: 'SERVICE_TOP_LEVEL_OPERATIONS',
@@ -115,292 +109,252 @@ const routes: AppRoutes[] = [
path: ROUTES.SERVICE_MAP,
component: ServiceMapPage,
isPrivate: true,
exact: true,
key: 'SERVICE_MAP',
},
{
path: ROUTES.TRACE_DETAIL,
exact: true,
component: TraceDetailV3,
isPrivate: true,
key: 'TRACE_DETAIL',
},
{
path: ROUTES.SETTINGS,
exact: false,
nested: true,
component: SettingsPage,
isPrivate: true,
key: 'SETTINGS',
},
{
path: ROUTES.USAGE_EXPLORER,
exact: true,
component: UsageExplorerPage,
isPrivate: true,
key: 'USAGE_EXPLORER',
},
{
path: ROUTES.ALL_DASHBOARD,
exact: true,
component: DashboardsListPage,
isPrivate: true,
key: 'ALL_DASHBOARD',
},
{
path: ROUTES.DASHBOARD,
exact: true,
component: DashboardPage,
isPrivate: true,
key: 'DASHBOARD',
},
{
path: ROUTES.PUBLIC_DASHBOARD,
exact: false,
nested: true,
component: PublicDashboardPage,
isPrivate: false,
key: 'PUBLIC_DASHBOARD',
},
{
path: ROUTES.DASHBOARD_PANEL_EDITOR,
exact: true,
component: DashboardPanelEditorPage,
isPrivate: true,
key: 'DASHBOARD_PANEL_EDITOR',
},
{
path: ROUTES.EDIT_ALERTS,
exact: true,
component: EditRulesPage,
isPrivate: true,
key: 'EDIT_ALERTS',
},
{
path: ROUTES.LIST_ALL_ALERT,
exact: true,
component: ListAllALertsPage,
isPrivate: true,
key: 'LIST_ALL_ALERT',
},
{
path: ROUTES.ALERTS_NEW,
exact: true,
component: CreateNewAlerts,
isPrivate: true,
key: 'ALERTS_NEW',
},
{
path: ROUTES.ALERT_HISTORY,
exact: true,
component: AlertHistory,
isPrivate: true,
key: 'ALERT_HISTORY',
},
{
path: ROUTES.ALERT_OVERVIEW,
exact: true,
component: AlertOverview,
isPrivate: true,
key: 'ALERT_OVERVIEW',
},
{
path: ROUTES.TRACES_EXPLORER,
exact: true,
component: TracesExplorer,
isPrivate: true,
key: 'TRACES_EXPLORER',
},
{
path: ROUTES.TRACES_FUNNELS,
exact: true,
component: TracesFunnels,
isPrivate: true,
key: 'TRACES_FUNNELS',
},
{
path: ROUTES.TRACES_FUNNELS_DETAIL,
exact: true,
component: TracesFunnelDetails,
isPrivate: true,
key: 'TRACES_FUNNELS_DETAIL',
},
{
path: ROUTES.CHANNELS_NEW,
exact: true,
component: ChannelsNew,
isPrivate: true,
key: 'CHANNELS_NEW',
},
{
path: ROUTES.CHANNELS_EDIT,
exact: true,
component: ChannelsEdit,
isPrivate: true,
key: 'CHANNELS_EDIT',
},
{
path: ROUTES.ALL_ERROR,
exact: true,
isPrivate: true,
component: AllErrors,
key: 'ALL_ERROR',
},
{
path: ROUTES.ERROR_DETAIL,
exact: true,
component: ErrorDetails,
isPrivate: true,
key: 'ERROR_DETAIL',
},
{
path: ROUTES.VERSION,
exact: true,
component: StatusPage,
isPrivate: true,
key: 'VERSION',
},
{
path: ROUTES.LOGS,
exact: true,
component: Logs,
key: 'LOGS',
isPrivate: true,
},
{
path: ROUTES.LOGS_PIPELINES,
exact: true,
component: PipelinePage,
key: 'LOGS_PIPELINES',
isPrivate: true,
},
{
path: ROUTES.LOGIN,
exact: true,
component: Login,
isPrivate: false,
key: 'LOGIN',
},
{
path: ROUTES.FORGOT_PASSWORD,
exact: true,
component: ForgotPassword,
isPrivate: false,
key: 'FORGOT_PASSWORD',
},
{
path: ROUTES.UN_AUTHORIZED,
exact: true,
component: UnAuthorized,
key: 'UN_AUTHORIZED',
isPrivate: true,
},
{
path: ROUTES.PASSWORD_RESET,
exact: true,
component: PasswordReset,
key: 'PASSWORD_RESET',
isPrivate: false,
},
{
path: ROUTES.SOMETHING_WENT_WRONG,
exact: true,
component: SomethingWentWrong,
key: 'SOMETHING_WENT_WRONG',
isPrivate: false,
},
{
path: ROUTES.WORKSPACE_LOCKED,
exact: true,
component: WorkspaceBlocked,
isPrivate: true,
key: 'WORKSPACE_LOCKED',
},
{
path: ROUTES.WORKSPACE_SUSPENDED,
exact: true,
component: WorkspaceSuspended,
isPrivate: true,
key: 'WORKSPACE_SUSPENDED',
},
{
path: ROUTES.WORKSPACE_ACCESS_RESTRICTED,
exact: true,
component: WorkspaceAccessRestricted,
isPrivate: true,
key: 'WORKSPACE_ACCESS_RESTRICTED',
},
{
path: ROUTES.INTEGRATIONS_DETAIL,
exact: true,
component: IntegrationsDetailsPage,
isPrivate: true,
key: 'INTEGRATIONS_DETAIL',
},
{
path: ROUTES.INTEGRATIONS,
exact: true,
component: Integrations,
isPrivate: true,
key: 'INTEGRATIONS',
},
{
path: ROUTES.MESSAGING_QUEUES_KAFKA,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_KAFKA',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_CELERY_TASK,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_CELERY_TASK',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_OVERVIEW,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_OVERVIEW',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_KAFKA_DETAIL',
isPrivate: true,
},
{
path: ROUTES.INFRASTRUCTURE_MONITORING_HOSTS,
exact: true,
component: InfrastructureMonitoring,
key: 'INFRASTRUCTURE_MONITORING_HOSTS',
isPrivate: true,
},
{
path: ROUTES.INFRASTRUCTURE_MONITORING_KUBERNETES,
exact: true,
component: InfrastructureMonitoring,
key: 'INFRASTRUCTURE_MONITORING_KUBERNETES',
isPrivate: true,
},
{
path: ROUTES.METRICS_EXPLORER,
exact: true,
component: MetricsExplorer,
key: 'METRICS_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.METRICS_EXPLORER_EXPLORER,
exact: true,
component: MetricsExplorer,
key: 'METRICS_EXPLORER_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.METRICS_EXPLORER_VOLUME_CONTROL,
exact: true,
component: MetricsExplorer,
key: 'METRICS_EXPLORER_VOLUME_CONTROL',
isPrivate: true,
@@ -408,56 +362,48 @@ const routes: AppRoutes[] = [
{
path: ROUTES.METER,
exact: true,
component: MeterExplorerPage,
key: 'METER',
isPrivate: true,
},
{
path: ROUTES.METER_EXPLORER,
exact: true,
component: MeterExplorerPage,
key: 'METER_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.API_MONITORING,
exact: true,
component: ApiMonitoring,
key: 'API_MONITORING',
isPrivate: true,
},
{
path: [ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT],
exact: true,
component: AIAssistantPage,
key: 'AI_ASSISTANT',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_ATTRIBUTE_MAPPING,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_ATTRIBUTE_MAPPING',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_OVERVIEW,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_OVERVIEW',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_EXPLORER,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_CONFIGURATION,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_CONFIGURATION',
isPrivate: true,
@@ -466,7 +412,6 @@ const routes: AppRoutes[] = [
export const SUPPORT_ROUTE: AppRoutes = {
path: ROUTES.SUPPORT,
exact: true,
component: SupportPage,
key: 'SUPPORT',
isPrivate: true,
@@ -474,7 +419,6 @@ export const SUPPORT_ROUTE: AppRoutes = {
export const LIST_LICENSES: AppRoutes = {
path: ROUTES.LIST_LICENSES,
exact: true,
component: LicensePage,
isPrivate: true,
key: 'LIST_LICENSES',
@@ -506,9 +450,15 @@ export const ROUTES_NOT_TO_BE_OVERRIDEN: string[] = [
];
export interface AppRoutes {
component: RouteProps['component'];
path: RouteProps['path'];
exact: RouteProps['exact'];
component: ComponentType;
/** An array registers the same component under each pattern. */
path: string | string[];
/**
* The route renders its own child routes, so it matches as a prefix. v6
* matches the whole path by default, so the mount appends a `/*` splat for
* these and nothing for the rest.
*/
nested?: boolean;
isPrivate: boolean;
key: keyof typeof ROUTES;
}

View File

@@ -28,10 +28,15 @@ export function isExpectedRequestFailure(error: unknown): boolean {
}
const APP_ASSETS_PATH = '/assets/';
const ANONYMOUS_FILENAME = '<anonymous>';
// Frames without a position are `[native code]`, which says nothing about the
// script that threw.
export function hasNoAppFrames(event: ErrorEvent): boolean {
// Frames without a position are `[native code]` or a browser builtin such as
// `JSON.parse (<anonymous>)`, which say nothing about the script that threw.
// A positioned `<anonymous>` throwing (last) frame is code loaded without a
// URL: the DevTools console, CDP, or an extension's `executeScript`. Sentry's
// own timer wrapper is bundled with the app, so checking for any app frame
// alone misses it.
export function isInjectedScriptError(event: ErrorEvent): boolean {
const frames = (event.exception?.values ?? [])
.flatMap((exception) => exception.stacktrace?.frames ?? [])
.filter(
@@ -40,12 +45,13 @@ export function hasNoAppFrames(event: ErrorEvent): boolean {
return (
frames.length > 0 &&
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH))
(frames[frames.length - 1].filename === ANONYMOUS_FILENAME ||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH)))
);
}
// PostHog's lazy recorder, the Pylon widget and Appcues.
const EXTERNAL_SCRIPT_URLS = [
const THIRD_PARTY_SCRIPT_URLS = [
/^https?:\/\/[^/]+\.posthog\.com\//,
/^https?:\/\/(?:[^/]+\.)?usepylon\.com\//,
/^https?:\/\/(?:[^/]+\.)?appcues\.(?:com|net)\//,
@@ -53,10 +59,10 @@ const EXTERNAL_SCRIPT_URLS = [
// Checks every frame, not only the top one: a failed fetch from the recorder
// tops out in Sentry's own fetch wrapper, which is bundled with the app.
export function isExternalIntegrationError(event: ErrorEvent): boolean {
export function isThirdPartyScriptError(event: ErrorEvent): boolean {
return (event.exception?.values ?? []).some((exception) =>
(exception.stacktrace?.frames ?? []).some((frame) =>
EXTERNAL_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
THIRD_PARTY_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
),
);
}

View File

@@ -13156,7 +13156,7 @@ export interface RuletypesNotificationSettingsDTO {
export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13273,7 +13273,7 @@ export interface RuletypesPostableRuleDTO {
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13306,7 +13306,7 @@ export interface RuletypesPostableRuleViewDTO {
export type RuletypesRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13365,7 +13365,7 @@ export interface RuletypesRuleDTO {
id: string;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
*/
labels?: RuletypesRuleDTOLabels;
/**

View File

@@ -27,6 +27,10 @@ export interface AppProvidersProps {
* A new provider belongs here only if it holds process-wide state that does not
* depend on the user, the license or the route. One that fetches on mount would
* fire unauthenticated from here; put it in `AppShell` or lower.
*
* The whole stack is the root route's element, so it renders inside the data
* router: `searchParams` (nuqs) reads the router's `useNavigate` /
* `useSearchParams`, and the boot spinner renders at a route too.
*/
function AppProviders({
children,

View File

@@ -0,0 +1,17 @@
import { type DataRouter, RouterProvider } from 'react-router';
interface AppRouterProviderProps {
router: DataRouter;
}
/**
* Transitions are off on purpose: under one React keeps the previous screen up
* instead of committing the Suspense fallback, so a route whose chunk is not
* cached yet renders no loader at all. Pending UI under transitions needs
* route `lazy` and `useNavigation()`.
*/
export function AppRouterProvider({
router,
}: AppRouterProviderProps): JSX.Element {
return <RouterProvider router={router} useTransitions={false} />;
}

View File

@@ -5,11 +5,8 @@ import { NotificationProvider } from 'hooks/useNotifications';
import { CmdKProvider } from 'providers/cmdKProvider';
import { ErrorModalProvider } from 'providers/ErrorModalProvider';
import { AppLayer } from './types';
export interface AppShellProps {
children: ReactNode;
router: AppLayer;
/** Mounted beside the routed content: the command palette and its siblings. */
overlays?: ReactNode;
}
@@ -19,28 +16,26 @@ export interface AppShellProps {
* fetches settle, above `PrivateRoute`, so it also covers the redirects and the
* not-found route, and it survives every navigation.
*
* A new provider belongs here if it needs the router or the user and has to
* outlive the page: a global overlay, a shortcut host, anything one route opens
* and the next one keeps.
* A new provider belongs here if it needs the user and has to outlive the page:
* a global overlay, a shortcut host, anything one route opens and the next one
* keeps. The router itself is higher up, in `AppProviders`.
*
* `ConfigProvider` reads `useThemeConfig`, which needs `ThemeProvider` above it,
* so the antd theme is settled here instead of by the caller.
*/
function AppShell({ children, router, overlays }: AppShellProps): JSX.Element {
function AppShell({ children, overlays }: AppShellProps): JSX.Element {
const themeConfig = useThemeConfig();
return (
<ConfigProvider theme={themeConfig}>
{router(
<CmdKProvider>
<NotificationProvider>
<ErrorModalProvider>
{overlays}
{children}
</ErrorModalProvider>
</NotificationProvider>
</CmdKProvider>,
)}
<CmdKProvider>
<NotificationProvider>
<ErrorModalProvider>
{overlays}
{children}
</ErrorModalProvider>
</NotificationProvider>
</CmdKProvider>
</ConfigProvider>
);
}

View File

@@ -0,0 +1,19 @@
import type { ReactNode } from 'react';
import { createBrowserRouter, type DataRouter } from 'react-router';
import { createRouteTable } from 'AppRoutes/routeTable';
import { attachRouter } from 'lib/router/navigation';
import { getBasePath } from 'utils/basePath';
/**
* Creates the app's data router and attaches it to `lib/router/navigation`, so
* code outside a component navigates through it. `root` is the layout route:
* every provider the pages need, `nuqs/adapters/react-router/v7` included,
* renders inside it, because a data router owns everything below it.
*/
export function createAppRouter(root: ReactNode): DataRouter {
const router = createBrowserRouter(createRouteTable(root), {
basename: getBasePath(),
});
attachRouter(router);
return router;
}

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import { LockKeyhole, RefreshCw, Trash2, X } from '@signozhq/icons';
import { Badge } from '@signozhq/ui/badge';
@@ -39,6 +39,17 @@ import DeleteMemberDialog from './DeleteMemberDialog';
import ResetLinkDialog from './ResetLinkDialog';
import './EditMemberDrawer.styles.scss';
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
import {
buildResetPasswordPermission,
buildUserDeletePermission,
buildUserReadPermission,
buildUserUpdatePermission,
PasswordListPermission,
} from '@/lib/authz/hooks/useAuthZ/permissions/user.permissions';
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
import AuthZTooltip from '@/lib/authz/components/AuthZTooltip/AuthZTooltip';
const ROOT_USER_TOOLTIP = 'This operation is not supported for the root user';
const SELF_DELETE_TOOLTIP =
@@ -59,6 +70,7 @@ function getDeleteTooltip(
function getInviteButtonLabel(
isLoading: boolean,
canListPassword: boolean,
existingToken: { expiresAt?: string } | undefined,
isExpired: boolean,
notFound: boolean,
@@ -66,6 +78,9 @@ function getInviteButtonLabel(
if (isLoading) {
return 'Checking invite...';
}
if (!canListPassword) {
return 'Invite Link Unavailable';
}
if (existingToken && !isExpired) {
return 'Copy Invite Link';
}
@@ -87,7 +102,6 @@ function toSaveApiError(err: unknown): APIError {
export interface EditMemberDrawerProps {
member: MemberRow | null;
open: boolean;
onClose: () => void;
onComplete: () => void;
}
@@ -95,7 +109,6 @@ export interface EditMemberDrawerProps {
// eslint-disable-next-line sonarjs/cognitive-complexity
function EditMemberDrawer({
member,
open,
onClose,
onComplete,
}: EditMemberDrawerProps): JSX.Element {
@@ -119,16 +132,47 @@ function EditMemberDrawer({
const isDeleted = member?.status === MemberStatus.Deleted;
const isSelf = !!member?.id && member.id === currentUser?.id;
const requestPermission = useMemo(() => {
if (member) {
return isInvited
? [buildUserReadPermission(member.id), PasswordListPermission]
: [buildUserReadPermission(member.id)];
}
return [];
}, [member, isInvited]);
const {
permissions: authZPermission,
error: authZError,
isLoading: isLoadingAuthZ,
} = useAuthZ(requestPermission);
const canReadUser = member
? !!authZError ||
(authZPermission?.[buildUserReadPermission(member.id)]?.isGranted ?? false)
: false;
const canListPassword =
!!authZError ||
(authZPermission?.[PasswordListPermission]?.isGranted ?? false);
const resetLinkChecks = useMemo(() => {
if (!member) {
return [];
}
if (isInvited && !canListPassword) {
return [PasswordListPermission];
}
return buildResetPasswordPermission(member.id);
}, [member, isInvited, canListPassword]);
const { showErrorModal } = useErrorModal();
const {
data: fetchedUser,
isLoading: isFetchingUser,
refetch: refetchUser,
} = useGetUser(
{ id: member?.id ?? '' },
{ query: { enabled: open && !!member?.id } },
);
} = useGetUser({ id: member?.id ?? '' }, { query: { enabled: canReadUser } });
const isRootUser = !!fetchedUser?.data?.isRoot;
@@ -144,7 +188,7 @@ function EditMemberDrawer({
currentRoles: currentMemberRoles,
isLoading: isMemberRolesLoading,
applyDiff,
} = useMemberRoleManager(member?.id ?? '', open && !!member?.id);
} = useMemberRoleManager(member?.id ?? '', canReadUser);
// Token status query for invited users
const {
@@ -153,7 +197,7 @@ function EditMemberDrawer({
isError: tokenNotFound,
} = useGetResetPasswordToken(
{ id: member?.id ?? '' },
{ query: { enabled: open && !!member?.id && isInvited } },
{ query: { enabled: !!member?.id && isInvited && canListPassword } },
);
const existingToken = tokenQueryData?.data;
@@ -187,13 +231,17 @@ function EditMemberDrawer({
useEffect(() => {
if (!member?.id) {
roleSessionRef.current = null;
} else if (member.id !== roleSessionRef.current && !isMemberRolesLoading) {
} else if (
canReadUser &&
member.id !== roleSessionRef.current &&
!isMemberRolesLoading
) {
setLocalRoles(
currentMemberRoles.map((r) => r.id).filter(Boolean) as string[],
);
roleSessionRef.current = member.id;
}
}, [member?.id, currentMemberRoles, isMemberRolesLoading]);
}, [member?.id, canReadUser, currentMemberRoles, isMemberRolesLoading]);
const isDirty =
member !== null &&
@@ -463,6 +511,31 @@ function EditMemberDrawer({
[formatTimezoneAdjustedTimestamp],
);
const inviteLinkAndResetPasswordText = useMemo(() => {
if (isGeneratingLink) {
return 'Generating...';
}
if (isInvited) {
return getInviteButtonLabel(
isLoadingTokenStatus || isLoadingAuthZ,
canListPassword,
existingToken,
isTokenExpired,
tokenNotFound,
);
}
return 'Generate Password Reset Link';
}, [
isGeneratingLink,
isInvited,
isLoadingTokenStatus,
isLoadingAuthZ,
canListPassword,
existingToken,
isTokenExpired,
tokenNotFound,
]);
const drawerBody = isFetchingUser ? (
<Skeleton active paragraph={{ rows: 6 }} />
) : (
@@ -471,7 +544,11 @@ function EditMemberDrawer({
<label className="edit-member-drawer__label" htmlFor="member-name">
Name
</label>
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
<AuthZTooltip
checks={member && !isSelf ? [buildUserUpdatePermission(member.id)] : []}
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
>
<Input
id="member-name"
value={localDisplayName}
@@ -484,7 +561,7 @@ function EditMemberDrawer({
placeholder="Enter name"
disabled={isRootUser || isDeleted}
/>
</Tooltip>
</AuthZTooltip>
</div>
<div className="edit-member-drawer__field">
@@ -503,17 +580,12 @@ function EditMemberDrawer({
<label className="edit-member-drawer__label" htmlFor="member-role">
Roles
</label>
{isSelf || isRootUser || isDeleted ? (
<Tooltip
title={
isRootUser
? ROOT_USER_TOOLTIP
: isDeleted
? undefined
: 'You cannot modify your own role'
}
>
<div className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled">
{isRootUser || isDeleted ? (
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
<div
className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled"
data-testid="member-roles-locked"
>
<div className="edit-member-drawer__disabled-roles">
{localRoles.length > 0 ? (
localRoles.map((roleId) => {
@@ -620,42 +692,33 @@ function EditMemberDrawer({
{!isDeleted && (
<>
<div className="edit-member-drawer__footer-left">
<Button
<AuthZButton
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
size="md"
onClick={(): void => setShowDeleteConfirm(true)}
testId="member-delete-btn"
disabled={isRootUser || isSelf}
variant="link"
color="danger"
checks={member ? [buildUserDeletePermission(member.id)] : []}
prefix={<Trash2 size={12} />}
>
{isInvited ? 'Revoke Invite' : 'Delete Member'}
</Button>
</AuthZButton>
<div className="edit-member-drawer__footer-divider" />
<Button
disabledTooltip={ROOT_USER_TOOLTIP}
<AuthZButton
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
size="md"
onClick={handleGenerateResetLink}
testId="member-reset-link-btn"
disabled={isRootUser}
loading={isGeneratingLink || isLoadingTokenStatus}
variant="link"
color="warning"
checks={resetLinkChecks}
prefix={<RefreshCw size={12} />}
>
{isGeneratingLink
? 'Generating...'
: isInvited
? getInviteButtonLabel(
isLoadingTokenStatus,
existingToken,
isTokenExpired,
tokenNotFound,
)
: 'Generate Password Reset Link'}
</Button>
{inviteLinkAndResetPasswordText}
</AuthZButton>
</div>
<div className="edit-member-drawer__footer-right">
@@ -669,18 +732,25 @@ function EditMemberDrawer({
Cancel
</Button>
<Button
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : 'No changes to save'}
<AuthZButton
disabledTooltip={
isRootUser
? ROOT_USER_TOOLTIP
: !isDirty
? 'No changes to save'
: undefined
}
size="md"
variant="solid"
color="primary"
disabled={!isDirty || isRootUser}
onClick={handleSave}
checks={[]}
testId="member-save-btn"
loading={isSaving}
>
{isSaving ? 'Saving...' : 'Save Member Details'}
</Button>
</AuthZButton>
</div>
</>
)}
@@ -690,7 +760,7 @@ function EditMemberDrawer({
return (
<>
<DrawerWrapper
open={open}
open={member !== null}
onOpenChange={(isOpen): void => {
if (!isOpen) {
handleClose();
@@ -703,7 +773,12 @@ function EditMemberDrawer({
footer={footer}
width="wide"
>
{drawerContent}
<AuthZGuardContent
checks={member ? [buildUserReadPermission(member?.id)] : []}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 6 }} />}
>
{drawerContent}
</AuthZGuardContent>
</DrawerWrapper>
<ResetLinkDialog

View File

@@ -17,6 +17,16 @@ import {
managedRoles,
} from 'mocks-server/__mockdata__/roles';
import { rest, server } from 'mocks-server/server';
import {
buildUserUpdatePermission,
PasswordListPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
setupAuthzDeny,
setupAuthzDenyAll,
} from 'lib/authz/utils/authz-test-utils';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import EditMemberDrawer, { EditMemberDrawerProps } from '../EditMemberDrawer';
@@ -168,7 +178,6 @@ function renderDrawer(
return render(
<EditMemberDrawer
member={activeMember}
open
onClose={jest.fn()}
onComplete={jest.fn()}
{...props}
@@ -176,6 +185,16 @@ function renderDrawer(
);
}
async function clickDeleteButton(
user: ReturnType<typeof userEvent.setup>,
): Promise<void> {
const deleteBtn = await screen.findByTestId('member-delete-btn');
await waitFor(() =>
expect(deleteBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(deleteBtn);
}
describe('EditMemberDrawer', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -186,6 +205,7 @@ describe('EditMemberDrawer', () => {
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
),
setupAuthzAdmin(),
);
(useGetUser as jest.Mock).mockReturnValue({
data: mockFetchedUser,
@@ -243,15 +263,33 @@ describe('EditMemberDrawer', () => {
server.resetHandlers();
});
it('renders active member details and disables Save when form is not dirty', () => {
it('renders active member details and disables Save when form is not dirty', async () => {
renderDrawer();
expect(screen.getByDisplayValue('Alice Smith')).toBeInTheDocument();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.toBeInTheDocument();
expect(screen.getByText('alice@signoz.io')).toBeInTheDocument();
expect(screen.getByText('ACTIVE')).toBeInTheDocument();
expect(
screen.getByRole('button', { name: /save member details/i }),
).toHaveAttribute('aria-disabled', 'true');
await waitFor(() =>
expect(screen.getByTestId('member-save-btn')).toHaveAttribute(
'aria-disabled',
'true',
),
);
});
it('still fetches the member when the permission check fails', async () => {
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
renderDrawer();
await waitFor(() =>
expect(useGetUser).toHaveBeenLastCalledWith(
{ id: 'user-1' },
{ query: { enabled: true } },
),
);
});
it('enables Save after editing name and calls updateUser on confirm', async () => {
@@ -266,7 +304,8 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
const nameInput = screen.getByDisplayValue('Alice Smith');
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -292,7 +331,8 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onClose });
const nameInput = screen.getByDisplayValue('Alice Smith');
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -323,7 +363,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
// signoz-admin is already selected; add signoz-editor on top
await user.click(screen.getByLabelText('Roles'));
await user.click(await screen.findByLabelText('Roles'));
await user.click(await screen.findByTitle('signoz-editor'));
const saveBtn = screen.getByRole('button', { name: /save member details/i });
@@ -381,7 +421,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
await user.click(screen.getByRole('button', { name: /delete member/i }));
await clickDeleteButton(user);
await expect(
screen.findByText(/are you sure you want to delete/i),
@@ -398,9 +438,11 @@ describe('EditMemberDrawer', () => {
});
});
it('shows revoke invite and copy invite link for invited members; hides Last Modified', () => {
it('shows revoke invite and copy invite link for invited members; hides Last Modified', async () => {
renderDrawer({ member: invitedMember });
await screen.findByText('Invited On');
expect(
screen.getByRole('button', { name: /revoke invite/i }),
).toBeInTheDocument();
@@ -414,7 +456,7 @@ describe('EditMemberDrawer', () => {
expect(screen.queryByText('Last Modified')).not.toBeInTheDocument();
});
it('shows "Regenerate Invite Link" when token is expired', () => {
it('shows "Regenerate Invite Link" when token is expired', async () => {
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
data: {
data: {
@@ -429,12 +471,12 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
expect(
screen.getByRole('button', { name: /regenerate invite link/i }),
).toBeInTheDocument();
await expect(
screen.findByRole('button', { name: /regenerate invite link/i }),
).resolves.toBeInTheDocument();
});
it('shows "Generate Invite Link" when no token exists', () => {
it('shows "Generate Invite Link" when no token exists', async () => {
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
data: undefined,
isLoading: false,
@@ -443,9 +485,88 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
expect(
screen.getByRole('button', { name: /generate invite link/i }),
).toBeInTheDocument();
await expect(
screen.findByRole('button', { name: /generate invite link/i }),
).resolves.toBeInTheDocument();
});
it('looks up the invite link when factor-password list is granted', async () => {
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
{ id: invitedMember.id },
{ query: { enabled: true } },
),
);
await waitFor(() =>
expect(screen.getByTestId('member-reset-link-btn')).not.toHaveAttribute(
'aria-disabled',
'true',
),
);
});
it('skips the invite link lookup and disables the button without factor-password list', async () => {
server.use(setupAuthzDeny(PasswordListPermission));
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
'data-denied-permissions',
PasswordListPermission,
),
);
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
'aria-disabled',
'true',
);
expect(screen.getByTestId('member-reset-link-btn')).toHaveTextContent(
'Invite Link Unavailable',
);
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
{ id: invitedMember.id },
{ query: { enabled: false } },
);
});
it('reports only factor-password list for an invited member who lacks every permission', async () => {
server.use(setupAuthzDenyAll());
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
'data-denied-permissions',
PasswordListPermission,
),
);
});
it('still looks up the invite link when the permission check fails', async () => {
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
{ id: invitedMember.id },
{ query: { enabled: true } },
),
);
});
it('keeps the reset link enabled for an active member without factor-password list', async () => {
server.use(setupAuthzDeny(PasswordListPermission));
renderDrawer();
await screen.findByDisplayValue('Alice Smith');
expect(screen.getByTestId('member-reset-link-btn')).not.toHaveAttribute(
'aria-disabled',
'true',
);
});
it('calls deleteUser after confirming revoke invite for invited members', async () => {
@@ -461,7 +582,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember, onComplete });
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
await clickDeleteButton(user);
await expect(
screen.findByText(/Are you sure you want to revoke the invite/i),
@@ -508,7 +629,8 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: { ...invitedMember, name: 'Bob' }, onComplete });
const nameInput = screen.getByDisplayValue('Bob');
const nameInput = await screen.findByDisplayValue('Bob');
await waitFor(() => expect(nameInput).toBeEnabled());
await user.clear(nameInput);
await user.type(nameInput, 'Bob Updated');
@@ -546,7 +668,8 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const nameInput = screen.getByDisplayValue('Alice Smith');
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -575,7 +698,7 @@ describe('EditMemberDrawer', () => {
renderDrawer();
await user.click(screen.getByRole('button', { name: /delete member/i }));
await clickDeleteButton(user);
const confirmBtns = screen.getAllByRole('button', {
name: /delete member/i,
});
@@ -606,7 +729,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
await clickDeleteButton(user);
const confirmBtns = screen.getAllByRole('button', {
name: /revoke invite/i,
});
@@ -645,16 +768,86 @@ describe('EditMemberDrawer', () => {
).not.toBeInTheDocument();
});
it('keeps name input enabled when viewing own profile', () => {
it('keeps name input enabled when viewing own profile', async () => {
renderDrawer({ member: selfMember });
expect(screen.getByDisplayValue('Alice Smith')).not.toBeDisabled();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.not.toBeDisabled();
});
it('keeps Reset Link button enabled when viewing own profile', () => {
it('keeps Reset Link button enabled when viewing own profile', async () => {
renderDrawer({ member: selfMember });
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
});
});
describe('self user roles', () => {
it('keeps roles editable', async () => {
renderDrawer({ member: selfMember });
await expect(screen.findByText('Select roles')).resolves.toBeInTheDocument();
expect(screen.queryByTestId('member-roles-locked')).not.toBeInTheDocument();
});
});
describe('deleted member', () => {
const deletedMember = { ...activeMember, status: MemberStatus.Deleted };
it('is read-only with no footer actions', async () => {
renderDrawer({ member: deletedMember });
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() =>
expect(nameInput).not.toHaveStyle({ cursor: 'not-allowed' }),
);
expect(nameInput).toBeDisabled();
expect(screen.getByTestId('member-roles-locked')).toBeInTheDocument();
expect(
screen.getByRole('button', { name: /generate password reset link/i }),
).not.toHaveAttribute('aria-disabled', 'true');
screen.queryByPlaceholderText('Select roles'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('member-save-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('member-delete-btn')).not.toBeInTheDocument();
expect(
screen.queryByTestId('member-reset-link-btn'),
).not.toBeInTheDocument();
});
});
describe('self user name update', () => {
it('saves through the me API without update:user', async () => {
const updateMyUser = jest.fn().mockResolvedValue({});
(useUpdateMyUserV2 as jest.Mock).mockReturnValue({
mutateAsync: updateMyUser,
isLoading: false,
});
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer({ member: selfMember });
const input = await screen.findByDisplayValue('Alice Smith');
await user.clear(input);
await user.type(input, 'Alice Cooper');
await user.click(screen.getByTestId('member-save-btn'));
await waitFor(() =>
expect(updateMyUser).toHaveBeenCalledWith({
data: { displayName: 'Alice Cooper' },
}),
);
});
it('does not gate Save on permissions', async () => {
server.use(setupAuthzDenyAll());
renderDrawer({ member: selfMember });
await screen.findByText(/is not authorized/);
expect(screen.getByTestId('member-save-btn')).not.toHaveAttribute(
'data-denied-permissions',
);
});
});
@@ -667,9 +860,11 @@ describe('EditMemberDrawer', () => {
});
});
it('disables name input for root user', () => {
it('disables name input for root user', async () => {
renderDrawer();
expect(screen.getByDisplayValue('Alice Smith')).toBeDisabled();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.toBeDisabled();
});
it('disables Delete button for root user', () => {
@@ -726,9 +921,11 @@ describe('EditMemberDrawer', () => {
renderDrawer();
await user.click(
screen.getByRole('button', { name: /generate password reset link/i }),
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(resetBtn);
const dialog = await screen.findByRole('dialog', {
name: /password reset link/i,
@@ -747,9 +944,11 @@ describe('EditMemberDrawer', () => {
renderDrawer();
await user.click(
screen.getByRole('button', { name: /generate password reset link/i }),
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(resetBtn);
const dialog = await screen.findByRole('dialog', {
name: /password reset link/i,

View File

@@ -0,0 +1,68 @@
import { useListUsers } from 'api/generated/services/users';
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { useCreatorOptions } from '../useCreatorOptions';
jest.mock('api/generated/services/users', () => ({
...jest.requireActual('api/generated/services/users'),
useListUsers: jest.fn(),
}));
const ARGS = {
currentUserEmail: 'me@signoz.io',
fallbackEmails: ['author@signoz.io'],
};
function mockUsers(users: { email: string; displayName: string }[]): void {
jest.mocked(useListUsers).mockReturnValue({
data: { data: users },
} as ReturnType<typeof useListUsers>);
}
describe('useCreatorOptions', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('lists the org users with their display names when list:user is granted', async () => {
server.use(setupAuthzAdmin());
mockUsers([{ email: 'alice@signoz.io', displayName: 'Alice' }]);
const { result } = renderHook(() => useCreatorOptions(ARGS), {
wrapper: AllTheProviders,
});
await waitFor(() =>
expect(useListUsers).toHaveBeenLastCalledWith({ query: { enabled: true } }),
);
expect(result.current).toStrictEqual([
{ email: 'alice@signoz.io', label: 'Alice (alice@signoz.io)' },
{ email: 'me@signoz.io', label: 'me@signoz.io (me)' },
]);
});
it('does not fetch users without list:user and falls back to me and the page authors', async () => {
server.use(setupAuthzDeny(UserListPermission));
jest.mocked(useListUsers).mockReturnValue({
data: undefined,
} as ReturnType<typeof useListUsers>);
const { result } = renderHook(() => useCreatorOptions(ARGS), {
wrapper: AllTheProviders,
});
await waitFor(() => expect(useListUsers).toHaveBeenCalled());
expect(useListUsers).not.toHaveBeenCalledWith({ query: { enabled: true } });
expect(useListUsers).toHaveBeenLastCalledWith({ query: { enabled: false } });
expect(result.current).toStrictEqual([
{ email: 'author@signoz.io', label: 'author@signoz.io' },
{ email: 'me@signoz.io', label: 'me@signoz.io (me)' },
]);
});
});

View File

@@ -1,5 +1,7 @@
import { useMemo } from 'react';
import { useListUsers } from 'api/generated/services/users';
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import type { CreatorOption } from './types';
@@ -15,7 +17,12 @@ export function useCreatorOptions({
currentUserEmail,
fallbackEmails,
}: Args): CreatorOption[] {
const { data } = useListUsers();
const { permissions } = useAuthZ([UserListPermission]);
const canListUsers = permissions?.[UserListPermission]?.isGranted ?? false;
// Without `list:user` the list isn't fetched: options shrink to "me" and the
// page's authors, with bare emails instead of display names.
const { data } = useListUsers({ query: { enabled: canListUsers } });
return useMemo<CreatorOption[]>(() => {
const users = data?.data ?? [];

View File

@@ -121,6 +121,7 @@ exports[`Not Found page test should render Not Found page without errors 1`] = `
</div>
<a
class="c3"
data-discover="true"
href="/home"
tabindex="0"
>

View File

@@ -1,4 +1,4 @@
import { ReactNode, useEffect, useRef } from 'react';
import { ReactNode, useCallback, useEffect, useRef } from 'react';
import { parseAsString, useQueryState } from 'nuqs';
import { useStore } from 'zustand';
@@ -61,34 +61,37 @@ export function QuerySearchV2Provider({
);
}, [urlExpression, initialExpression, store]);
// Back and Forward. Reads the browser's URL: after a write, nuqs can briefly
// report the value it replaced.
useEffect(() => {
const onPopState = (): void => {
isInitialized.current = true;
const urlValue = new URLSearchParams(window.location.search).get(
queryParamKey,
);
const expression = urlValue
? getUserExpressionFromCombined(initialExpression, urlValue)
: '';
// Another param changed; keep any text typed but not run.
if (expression === store.getState().committedExpression) {
return;
}
// Already in the URL, so the write below must not run for it.
lastCommittedRef.current = expression;
if (expression) {
store.getState().initializeFromUrl(expression);
} else {
store.getState().resetExpression();
}
};
window.addEventListener('popstate', onPopState);
return (): void => window.removeEventListener('popstate', onPopState);
// The URL owns the expression. Reads the browser's URL: after a write, nuqs
// can briefly report the value it replaced.
const followBrowserUrl = useCallback((): void => {
isInitialized.current = true;
const urlValue = new URLSearchParams(window.location.search).get(
queryParamKey,
);
const expression = urlValue
? getUserExpressionFromCombined(initialExpression, urlValue)
: '';
// Another param changed; keep any text typed but not run.
if (expression === store.getState().committedExpression) {
return;
}
// Already in the URL, so the write below must not run for it.
lastCommittedRef.current = expression;
if (expression) {
store.getState().initializeFromUrl(expression);
} else {
store.getState().resetExpression();
}
}, [queryParamKey, initialExpression, store]);
// Back and Forward.
useEffect(() => {
window.addEventListener('popstate', followBrowserUrl);
return (): void => window.removeEventListener('popstate', followBrowserUrl);
}, [followBrowserUrl]);
// Write only when the committed filter changes, never in reply to a URL change.
// Declared before the effect below, which can reset the filter this render holds.
useEffect(() => {
if (committedExpression === lastCommittedRef.current) {
return;
@@ -102,6 +105,24 @@ export function QuerySearchV2Provider({
void setUrlExpression(next);
}, [committedExpression, urlExpression, setUrlExpression]);
// Any other navigation. A provider can outlive the navigation away from its
// page (a route-driven tab keeps the leaving pane mounted until its animation
// ends), so a param that disappeared is followed, not restored.
const previousUrlExpression = useRef(urlExpression);
useEffect(() => {
if (urlExpression === previousUrlExpression.current) {
return;
}
previousUrlExpression.current = urlExpression;
const browserValue = new URLSearchParams(window.location.search).get(
queryParamKey,
);
if (urlExpression !== browserValue) {
return;
}
followBrowserUrl();
}, [urlExpression, queryParamKey, followBrowserUrl]);
useEffect(() => {
return (): void => {
if (!persistOnUnmount) {

View File

@@ -1,4 +1,4 @@
import { ReactNode } from 'react';
import { ReactNode, useEffect, useRef } from 'react';
import { act, renderHook } from 'tests/test-utils';
import {
@@ -215,6 +215,83 @@ describe('QuerySearchExpressionProvider', () => {
expect(result.current.userExpression).toBe('status = 404');
});
it('should follow the URL when the param is dropped', () => {
mockUrlValue = 'status = 500';
const { result, rerender } = renderHook(() => useTestHooks(), {
wrapper: createWrapper(),
});
expect(result.current.expression).toBe('status = 500');
mockSetQueryState.mockClear();
mockUrlValue = null;
rerender();
expect(result.current.expression).toBe('');
expect(mockSetQueryState).not.toHaveBeenCalledWith('status = 500');
});
it('should keep an expression a child runs on mount', () => {
function RunOnMount(): null {
const onRun = useQuerySearchOnRun();
useEffect(() => {
onRun('service = "api"');
}, [onRun]);
return null;
}
const Wrapper = createWrapper();
const { result } = renderHook(() => useTestHooks(), {
wrapper: ({ children }: { children: ReactNode }) => (
<Wrapper>
<RunOnMount />
{children}
</Wrapper>
),
});
expect(result.current.userExpression).toBe('service = "api"');
expect(mockSetQueryState).toHaveBeenCalledWith('service = "api"');
});
it('should keep an expression a child runs when the initial expression changes', () => {
mockUrlValue = "k8s.pod.name = 'pod-1'";
let initialExpression = "k8s.cluster.name = 'a'";
let runExpression = "k8s.pod.name = 'pod-1'";
// Runs once per initial expression, as the K8s carry-over does.
function RunOnce(): null {
const onRun = useQuerySearchOnRun();
const hasRun = useRef(false);
useEffect(() => {
if (!hasRun.current) {
hasRun.current = true;
onRun(runExpression);
}
}, [onRun]);
return null;
}
const { result, rerender } = renderHook(() => useTestHooks(), {
wrapper: ({ children }: { children: ReactNode }) => (
<QuerySearchV2Provider
queryParamKey="testExpression"
initialExpression={initialExpression}
>
<RunOnce key={initialExpression} />
{children}
</QuerySearchV2Provider>
),
});
expect(result.current.userExpression).toBe("k8s.pod.name = 'pod-1'");
initialExpression = "k8s.node.name = 'b'";
runExpression = '';
rerender();
expect(result.current.userExpression).toBe('');
expect(mockSetQueryState).toHaveBeenLastCalledWith(null);
});
it('should throw error when used outside provider', () => {
expect(() => {
renderHook(() => useExpression());

View File

@@ -5,6 +5,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
import { useAppLocation } from 'lib/router/useAppLocation';
import { navigate } from 'lib/router/navigation';
import { ArrowRight } from '@signozhq/icons';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import TopContributorsContent from './TopContributorsContent';
import { TopContributorsCardProps } from './types';
@@ -27,23 +28,15 @@ function TopContributorsCard({
const isDarkMode = useIsDarkMode();
const toggleViewAllParam = (isOpen: boolean): void => {
if (isOpen) {
searchParams.set('viewAllTopContributors', 'true');
} else {
searchParams.delete('viewAllTopContributors');
}
};
const toggleViewAllDrawer = (): void => {
setIsViewAllVisible((prev) => {
const newState = !prev;
toggleViewAllParam(newState);
return newState;
});
navigate({ search: searchParams.toString() });
const params = getUnstableCurrentSearchParams();
if (isViewAllVisible) {
params.delete('viewAllTopContributors');
} else {
params.set('viewAllTopContributors', 'true');
}
setIsViewAllVisible(!isViewAllVisible);
navigate({ search: params.toString() });
};
return (

View File

@@ -6,7 +6,6 @@ import Uplot from 'components/Uplot';
import { QueryParams } from 'constants/query';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import useUrlQuery from 'hooks/useUrlQuery';
import { navigate } from 'lib/router/navigation';
import heatmapPlugin from 'lib/uPlotLib/plugins/heatmapPlugin';
import timelinePlugin from 'lib/uPlotLib/plugins/timelinePlugin';
@@ -15,6 +14,7 @@ import { useTimezone } from 'providers/Timezone';
import { UpdateTimeInterval } from 'store/actions';
import { AlertRuleTimelineGraphResponse } from 'types/api/alerts/def';
import uPlot, { AlignedData } from 'uplot';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { ALERT_STATUS, TIMELINE_OPTIONS } from './constants';
@@ -49,7 +49,6 @@ function HorizontalTimelineGraph({
return [timestamps, states];
}, [data]);
const urlQuery = useUrlQuery();
const dispatch = useDispatch();
const { timezone } = useTimezone();
@@ -89,6 +88,7 @@ function HorizontalTimelineGraph({
const diff = endTime - startTime;
if (diff > 0) {
const urlQuery = getUnstableCurrentSearchParams();
if (urlQuery.has(QueryParams.relativeTime)) {
urlQuery.delete(QueryParams.relativeTime);
}
@@ -125,14 +125,7 @@ function HorizontalTimelineGraph({
tzDate: (timestamp: number): Date =>
uPlot.tzDate(new Date(timestamp * 1e3), timezone.value),
}),
[
width,
isDarkMode,
transformedData.length,
urlQuery,
dispatch,
timezone.value,
],
[width, isDarkMode, transformedData.length, dispatch, timezone.value],
);
return <Uplot data={transformedData} options={options} />;
}

View File

@@ -5,6 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import { navigate } from 'lib/router/navigation';
import { Info } from '@signozhq/icons';
import Tabs2 from 'periscope/components/Tabs2';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import './TabsAndFilters.styles.scss';
@@ -51,8 +52,9 @@ function TimelineFilters(): JSX.Element {
);
const handleFilter = (value: TimelineFilter): void => {
searchParams.set('timelineFilter', value);
navigate({ search: searchParams.toString() });
const params = getUnstableCurrentSearchParams();
params.set('timelineFilter', value);
navigate({ search: params.toString() });
};
const tabs = [

View File

@@ -0,0 +1,149 @@
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
import { parseAsString, useQueryState } from 'nuqs';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import type uPlot from 'uplot';
import TopContributorsCard from '../Statistics/TopContributorsCard/TopContributorsCard';
import Graph from '../Timeline/Graph/Graph';
import { ALERT_HISTORY_EXPRESSION_KEY } from '../Timeline/Table/Table';
import TabsAndFilters from '../Timeline/TabsAndFilters/TabsAndFilters';
import { TimelineFilter } from '../types';
const mockUplot: { options?: uPlot.Options } = {};
jest.mock('components/Uplot', () => ({
__esModule: true,
default: ({ options }: { options: uPlot.Options }): null => {
mockUplot.options = options;
return null;
},
}));
jest.mock('lib/uPlotLib/plugins/timelinePlugin', () => ({
__esModule: true,
default: (): object => ({}),
}));
const EXPRESSION = "service.name = 'frontend'";
// Writes the expression the way the search box does: a shallow nuqs write that
// reaches the address bar but not the router's location.
function Expression(): JSX.Element {
const [expression, setExpression] = useQueryState(
ALERT_HISTORY_EXPRESSION_KEY,
parseAsString,
);
return (
<>
<button
type="button"
aria-label="Run expression"
data-testid="run-expression"
onClick={(): void => {
void setExpression(EXPRESSION);
}}
/>
<output data-testid="expression">{expression ?? ''}</output>
</>
);
}
function getUrlParam(key: string): string | null {
return new URLSearchParams(window.location.search).get(key);
}
async function runExpression(): Promise<void> {
await userEvent.click(screen.getByTestId('run-expression'));
await waitFor(() =>
expect(getUrlParam(ALERT_HISTORY_EXPRESSION_KEY)).toBe(EXPRESSION),
);
}
function expectExpressionKept(): void {
expect(getUrlParam(ALERT_HISTORY_EXPRESSION_KEY)).toBe(EXPRESSION);
expect(screen.getByTestId('expression')).toHaveTextContent(EXPRESSION);
}
const initialRoute = `${ROUTES.ALERT_HISTORY}?ruleId=1`;
describe('Alert history navigations keep the expression', () => {
it('keeps it when a state tab is clicked', async () => {
render(
<>
<Expression />
<TabsAndFilters />
</>,
undefined,
{ initialRoute },
);
await runExpression();
await userEvent.click(screen.getByTestId('timeline-filter-fired'));
await waitFor(() =>
expect(getUrlParam('timelineFilter')).toBe(TimelineFilter.FIRED),
);
expectExpressionKept();
});
it('keeps it when the top contributors drawer opens', async () => {
const topContributorsData = [1, 2, 3, 4].map((fingerprint) => ({
fingerprint,
labels: { service: `service-${fingerprint}` },
count: fingerprint,
relatedLogsLink: '',
relatedTracesLink: '',
}));
render(
<>
<Expression />
<TopContributorsCard
topContributorsData={topContributorsData}
totalCurrentTriggers={10}
/>
</>,
undefined,
{ initialRoute },
);
await runExpression();
await userEvent.click(screen.getByTestId('top-contributors-view-all'));
await waitFor(() =>
expect(getUrlParam('viewAllTopContributors')).toBe('true'),
);
expectExpressionKept();
});
it('keeps it when a range is selected on the graph', async () => {
render(
<>
<Expression />
<Graph
type="horizontal"
data={[
{
start: 1_700_000_000_000,
end: 1_700_000_600_000,
state: RuletypesAlertStateDTO.firing,
},
]}
/>
</>,
undefined,
{ initialRoute },
);
await runExpression();
const self = {
select: { left: 10, width: 20 },
posToVal: (pos: number): number => 1_700_000_000 + pos,
} as unknown as uPlot;
act(() => {
mockUplot.options?.hooks?.setSelect?.[0]?.(self);
});
await waitFor(() => expect(getUrlParam('startTime')).toBe('1700000010000'));
expectExpressionKept();
});
});

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
@@ -17,10 +17,10 @@ import {
QuickFilterChangeEventData,
QuickFiltersSource,
} from 'components/QuickFilters/types';
import { initialQueriesMap } from 'constants/queryBuilder';
import K8sBaseDetails, {
K8sDetailsFilters,
} from 'container/InfraMonitoringK8sV2/Base/K8sBaseDetails';
import { DefaultQueryRedirect } from 'container/InfraMonitoringK8sV2/Base/DefaultQueryRedirect';
import { K8sBaseList } from 'container/InfraMonitoringK8sV2/Base/K8sBaseList';
import StatusFilter from 'container/InfraMonitoringHostsV2/StatusFilter';
import { K8sBaseFilters } from 'container/InfraMonitoringK8sV2/Base/types';
@@ -28,9 +28,6 @@ import {
InfraMonitoringEntity,
METRIC_NAMESPACE_BY_ENTITY,
} from 'container/InfraMonitoringK8sV2/constants';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { DataSource } from 'types/common/queryBuilder';
import {
getHostMetricsQueryPayload,
@@ -60,10 +57,6 @@ import {
function Hosts(): JSX.Element {
const [showFilters, setShowFilters] = useState(true);
const compositeQuery = useGetCompositeQueryParam();
const { redirectWithQueryBuilderData } = useQueryBuilder();
const isInitialized = useRef(false);
const selectedTime = useGlobalTimeStore((state) => state.selectedTime);
const getMinMaxTime = useGlobalTimeStore((state) => state.getMinMaxTime);
const { startUnixMilli, endUnixMilli } = useMemo(() => {
@@ -75,28 +68,6 @@ function Hosts(): JSX.Element {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedTime, getMinMaxTime]);
useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
if (!compositeQuery) {
const defaultQuery = initialQueriesMap[DataSource.METRICS];
redirectWithQueryBuilderData({
...defaultQuery,
builder: {
...defaultQuery.builder,
queryData: defaultQuery.builder.queryData.map((query) => ({
...query,
filter: { expression: '' },
filters: { items: [], op: 'AND' as const },
})),
},
});
}
}, [compositeQuery, redirectWithQueryBuilderData]);
const handleFilterVisibilityChange = (): void => {
setShowFilters(!showFilters);
};
@@ -226,6 +197,7 @@ function Hosts(): JSX.Element {
return (
<>
<DefaultQueryRedirect />
<div className={styles.infraMonitoringContainer}>
<div className={styles.infraContentRow}>
{showFilters && (

View File

@@ -0,0 +1,42 @@
import { useEffect, useRef } from 'react';
import { initialQueriesMap } from 'constants/queryBuilder';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { DataSource } from 'types/common/queryBuilder';
/**
* Puts the default query in the URL when the page mounts without one.
*
* Render it before the list: React runs sibling effects in tree order, and this
* navigation drops the nuqs writes still queued, such as the page size the list
* writes on mount.
*/
export function DefaultQueryRedirect(): null {
const compositeQuery = useGetCompositeQueryParam();
const { redirectWithQueryBuilderData } = useQueryBuilder();
const isInitialized = useRef(false);
useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
if (!compositeQuery) {
const defaultQuery = initialQueriesMap[DataSource.METRICS];
redirectWithQueryBuilderData({
...defaultQuery,
builder: {
...defaultQuery.builder,
queryData: defaultQuery.builder.queryData.map((query) => ({
...query,
filter: { expression: '' },
filters: { items: [], op: 'AND' as const },
})),
},
});
}
}, [compositeQuery, redirectWithQueryBuilderData]);
return null;
}

View File

@@ -60,7 +60,6 @@ function K8sHeader({
const currentExpression =
currentQuery.builder.queryData[0]?.filter?.expression || '';
const finalExpression = newExpression ?? currentExpression;
void setCurrentPage(1);
const updatedQuery = {
...currentQuery,
@@ -87,6 +86,8 @@ function K8sHeader({
);
safeNavigate(`${location.pathname}?${newUrlQuery.toString()}`);
// After the navigation: a navigation drops the nuqs writes still queued.
void setCurrentPage(1);
void invalidateQueries();
if (finalExpression?.trim()) {

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import * as Sentry from '@sentry/react';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
@@ -9,14 +9,12 @@ import {
QuickFilterCheckboxUseFieldApis,
QuickFiltersSource,
} from 'components/QuickFilters/types';
import { initialQueriesMap } from 'constants/queryBuilder';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { ArrowUpToLine, Filter } from '@signozhq/icons';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { DataSource } from 'types/common/queryBuilder';
import { CategoryIcon } from './Base/categoryIcons';
import { DefaultQueryRedirect } from './Base/DefaultQueryRedirect';
import { K8sDynamicList } from './Base/K8sDynamicList';
import EntityStatusFilter from './Base/components/EntityStatusFilter/EntityStatusFilter';
import {
@@ -66,9 +64,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
const [, setNodeReadinessFilter] = useInfraMonitoringNodeReadinessFilter();
const [, setContainerStatusFilter] = useInfraMonitoringContainerStatusFilter();
const compositeQuery = useGetCompositeQueryParam();
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
const isInitialized = useRef(false);
const selectedTime = useGlobalTimeStore((state) => state.selectedTime);
const getMinMaxTime = useGlobalTimeStore((state) => state.getMinMaxTime);
@@ -95,28 +91,6 @@ export default function InfraMonitoringK8s(): JSX.Element {
[getUseFieldApis, selectedCategory],
);
useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
if (!compositeQuery) {
const defaultQuery = initialQueriesMap[DataSource.METRICS];
redirectWithQueryBuilderData({
...defaultQuery,
builder: {
...defaultQuery.builder,
queryData: defaultQuery.builder.queryData.map((query) => ({
...query,
filter: { expression: '' },
filters: { items: [], op: 'AND' as const },
})),
},
});
}
}, [compositeQuery, redirectWithQueryBuilderData]);
useEffect(() => {
// The category query param is a plain string; entities are validated by
// getEntityConfig before rendering
@@ -212,14 +186,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
const handleCategorySelect = (key: string): void => {
if (key !== selectedCategory) {
void setSelectedCategory(key as string);
void setOrderBy(null);
void setGroupBy(null);
void setCurrentPage(null);
setSelectedItemParams(null);
void setPodStatusFilter(null);
void setNodeReadinessFilter(null);
void setContainerStatusFilter(null);
// Navigate first: a navigation drops the nuqs writes still queued.
redirectWithQueryBuilderData({
...currentQuery,
builder: {
@@ -233,6 +200,14 @@ export default function InfraMonitoringK8s(): JSX.Element {
],
},
});
void setSelectedCategory(key as string);
void setOrderBy(null);
void setGroupBy(null);
void setCurrentPage(null);
setSelectedItemParams(null);
void setPodStatusFilter(null);
void setNodeReadinessFilter(null);
void setContainerStatusFilter(null);
}
};
@@ -262,6 +237,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
<DefaultQueryRedirect />
<div className={styles.infraMonitoringContainer}>
<div className={styles.infraContentRow}>
{showFilters && (

View File

@@ -0,0 +1,211 @@
import { usePreferredPageSizeStore } from 'components/TanStackTableView/usePreferredPageSize.store';
import { initialQueriesMap } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { DataSource } from 'types/common/queryBuilder';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import K8sHeader from '../Base/K8sHeader';
import EntityDateTimeSelector from '../EntityDetailsUtils/EntityDateTimeSelector/EntityDateTimeSelector';
import {
InfraMonitoringEntity,
INFRA_MONITORING_K8S_PARAMS_KEYS,
K8sCategories,
} from '../constants';
import {
useInfraMonitoringCategory,
useInfraMonitoringSelectedItemParams,
} from '../hooks';
import InfraMonitoringK8s from '../InfraMonitoringK8s';
// The real hook: a navigation made while a nuqs write is queued drops that write,
// which is what these tests guard. The extension slips past jest.config.ts's mock.
jest.mock('hooks/useSafeNavigate', () =>
jest.requireActual('../../../hooks/useSafeNavigate.ts'),
);
jest.mock('components/QuickFilters/QuickFilters', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="quick-filters" />,
}));
// Keeps the list's own URL write on mount: the page size.
jest.mock('../Base/K8sDynamicList', () => {
const { useTableParams } = jest.requireActual<
typeof import('components/TanStackTableView')
>('components/TanStackTableView');
function K8sDynamicList(): JSX.Element {
useTableParams(
{ page: 'page', limit: 'pageSize' },
{ page: 1, limit: 10, storageKey: 'k8s-containers' },
);
return <div data-testid="k8s-dynamic-list" />;
}
return { __esModule: true, K8sDynamicList, default: K8sDynamicList };
});
jest.mock('components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch', () => ({
__esModule: true,
default: ({ onRun }: { onRun: (expression: string) => void }): JSX.Element => (
<button
type="button"
aria-label="Run filter"
data-testid="run-filter"
onClick={(): void => onRun("k8s.pod.name = 'pod-1'")}
/>
),
}));
jest.mock('lib/navigation', () => ({
getNavigationReferrer: (): string => 'direct',
}));
const route = ROUTES.INFRASTRUCTURE_MONITORING_KUBERNETES;
function DrawerHarness(): JSX.Element {
const [, setCategory] = useInfraMonitoringCategory();
const [selectedItemParams, setSelectedItemParams] =
useInfraMonitoringSelectedItemParams();
return (
<>
<button
type="button"
aria-label="Select category"
data-testid="select-category"
onClick={(): void => {
void setCategory(K8sCategories.PODS);
}}
/>
<button
type="button"
aria-label="Open row"
data-testid="open-row"
onClick={(): void =>
setSelectedItemParams({
selectedItem: 'pod-1',
clusterName: null,
namespaceName: null,
})
}
/>
{selectedItemParams.selectedItem && (
<div data-testid="drawer">
<EntityDateTimeSelector category={InfraMonitoringEntity.PODS} />
</div>
)}
</>
);
}
function getUrlParam(key: string): string | null {
return new URLSearchParams(window.location.search).get(key);
}
describe('K8s URL writes queued by nuqs', () => {
afterEach(() => {
usePreferredPageSizeStore
.getState()
.setPreferredPageSize('k8s-containers', null);
});
it('opens the drawer on the first click after an earlier shallow write', async () => {
render(<DrawerHarness />, undefined, {
initialRoute: `${route}?relativeTime=15m`,
});
await userEvent.click(screen.getByTestId('select-category'));
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY)).toBe(
K8sCategories.PODS,
),
);
await userEvent.click(screen.getByTestId('open-row'));
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM)).toBe(
'pod-1',
),
);
expect(screen.getByTestId('drawer')).toBeInTheDocument();
});
it('switches category on the first click while a filter is applied', async () => {
const query = initialQueriesMap[DataSource.METRICS];
const filteredQuery = {
...query,
builder: {
...query.builder,
queryData: [
{
...query.builder.queryData[0],
filter: { expression: "k8s.pod.name = 'pod-1'" },
},
],
},
};
const params = new URLSearchParams({
[INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY]: K8sCategories.PODS,
compositeQuery: encodeURIComponent(JSON.stringify(filteredQuery)),
});
render(<InfraMonitoringK8s />, undefined, {
initialRoute: `${route}?${params.toString()}`,
});
await userEvent.click(
await screen.findByTestId(`category-${K8sCategories.CONTAINERS}`),
);
await waitFor(() => {
const compositeQuery = JSON.parse(
decodeURIComponent(getUrlParam('compositeQuery') ?? ''),
);
expect(compositeQuery.builder.queryData[0].filter.expression).toBe('');
});
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY)).toBe(
K8sCategories.CONTAINERS,
),
);
});
it('goes back to the first page when a filter runs', async () => {
render(
<K8sHeader
entity={InfraMonitoringEntity.PODS}
showAutoRefresh={false}
cancelQuery={jest.fn()}
/>,
undefined,
{ initialRoute: `${route}?relativeTime=30m&page=3` },
);
await userEvent.click(screen.getByTestId('run-filter'));
await waitFor(() => {
const compositeQuery = JSON.parse(
decodeURIComponent(getUrlParam('compositeQuery') ?? ''),
);
expect(compositeQuery.builder.queryData[0].filter.expression).toBe(
"k8s.pod.name = 'pod-1'",
);
});
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.PAGE)).toBe('1'),
);
});
it('keeps the page size the list writes while the default query loads', async () => {
usePreferredPageSizeStore
.getState()
.setPreferredPageSize('k8s-containers', 25);
render(<InfraMonitoringK8s />, undefined, { initialRoute: route });
await waitFor(() => expect(getUrlParam('compositeQuery')).not.toBeNull());
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.PAGE_SIZE)).toBe('25'),
);
});
});

View File

@@ -991,6 +991,15 @@ describe('Login Component', () => {
describe('Enter key submission', () => {
const EMAIL_PASSWORD_ENDPOINT = '*/api/v2/sessions/email_password';
const originalLocation = window.location;
afterEach(() => {
Object.defineProperty(window, 'location', {
value: originalLocation,
writable: true,
configurable: true,
});
});
async function typeEmail(
user: ReturnType<typeof userEvent.setup>,
@@ -1157,8 +1166,15 @@ describe('Login Component', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
Object.defineProperty(window, 'location', {
value: { href: 'http://localhost/' },
value: {
href: 'http://localhost/',
origin: 'http://localhost',
pathname: '/',
search: '',
hash: '',
},
writable: true,
configurable: true,
});
server.use(

View File

@@ -47,6 +47,10 @@
flex: 1;
min-width: 0;
}
&__search-trigger {
width: 100%;
}
}
.members-filter-trigger__chevron {

View File

@@ -6,15 +6,25 @@ import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
import { Input } from '@signozhq/ui/input';
import { useListUsers } from 'api/generated/services/users';
import EditMemberDrawer from 'components/EditMemberDrawer/EditMemberDrawer';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import InviteMembersModal from 'container/MembersSettings/components/InviteMembersModal/InviteMembersModal';
import MembersTable, { MemberRow } from 'components/MembersTable/MembersTable';
import useUrlQuery from 'hooks/useUrlQuery';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import {
UserCreatePermission,
UserListPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { parseAsBoolean, useQueryState } from 'nuqs';
import { toISOString } from 'utils/app';
import { toAPIError } from 'utils/errorUtils';
import { FilterMode, MemberStatus, toMemberStatus } from './utils';
import './MembersSettings.styles.scss';
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
const PAGE_SIZE = 20;
@@ -23,6 +33,12 @@ function MembersSettings(): JSX.Element {
const pageParam = parseInt(urlQuery.get('page') ?? '1', 10);
const currentPage = Number.isNaN(pageParam) || pageParam < 1 ? 1 : pageParam;
const {
permissions: authzPermissions,
isLoading: isAuthZLoading,
error: authzError,
} = useAuthZ([UserListPermission]);
// TODO(nuqs): Replace with nuqs once the nuqs setup and integration is done - for search
const [searchQuery, setSearchQuery] = useState('');
const [filterMode, setFilterMode] = useState<FilterMode>(FilterMode.All);
@@ -32,7 +48,18 @@ function MembersSettings(): JSX.Element {
);
const [selectedMember, setSelectedMember] = useState<MemberRow | null>(null);
const { data: usersData, isLoading, refetch: refetchUsers } = useListUsers();
const canListUsers =
!!authzError || (authzPermissions?.[UserListPermission]?.isGranted ?? false);
const {
data: usersData,
isLoading,
refetch: refetchUsers,
isError,
error,
} = useListUsers({ query: { enabled: canListUsers } });
const controlsDisabled = !canListUsers || isAuthZLoading;
const allMembers = useMemo(
(): MemberRow[] =>
@@ -176,57 +203,89 @@ function MembersSettings(): JSX.Element {
</div>
<div className="members-settings__controls">
<Dropdown items={filterMenuItems} nativeButton align="end" side="bottom">
<Button
size="md"
variant="solid"
color="secondary"
suffix={
<ChevronDown size={12} className="members-filter-trigger__chevron" />
}
testId="members-filter-trigger"
>
<span>{filterLabel}</span>
</Button>
</Dropdown>
<AuthZTooltip checks={[UserListPermission]}>
<span>
<Dropdown
disabled={controlsDisabled}
disabledTooltip={undefined}
items={filterMenuItems}
nativeButton
align="end"
side="bottom"
>
<Button
size="md"
variant="solid"
color="secondary"
loading={isAuthZLoading}
disabled={!canListUsers}
disabledTooltip={undefined}
suffix={
<ChevronDown size={12} className="members-filter-trigger__chevron" />
}
testId="members-filter-trigger"
>
<span>{filterLabel}</span>
</Button>
</Dropdown>
</span>
</AuthZTooltip>
<div className="members-settings__search">
<Input
type="search"
placeholder="Search by name or email..."
value={searchQuery}
onChange={(e): void => {
setSearchQuery(e.target.value);
setPage(1);
}}
className="members-search-input"
name="members-search"
testId="members-search-input"
/>
<AuthZTooltip
checks={[UserListPermission]}
triggerClassName="members-settings__search-trigger"
>
<Input
type="search"
placeholder="Search by name or email..."
value={searchQuery}
onChange={(e): void => {
setSearchQuery(e.target.value);
setPage(1);
}}
className="members-search-input"
name="members-search"
testId="members-search-input"
disabled={controlsDisabled}
/>
</AuthZTooltip>
</div>
<Button
<AuthZButton
size="md"
variant="solid"
color="primary"
checks={[UserCreatePermission]}
onClick={(): void => void setIsInviteModalOpen(true)}
prefix={<Plus size={12} />}
testId="invite-member-btn"
>
Invite member
</Button>
</AuthZButton>
</div>
</div>
<MembersTable
data={filteredMembers}
loading={isLoading}
total={filteredMembers.length}
currentPage={currentPage}
pageSize={PAGE_SIZE}
searchQuery={searchQuery}
onPageChange={setPage}
onRowClick={handleRowClick}
/>
<AuthZGuardContent checks={[UserListPermission]}>
{isError ? (
<ErrorInPlace
error={toAPIError(
error,
'An unexpected error occurred while fetching members.',
)}
/>
) : (
<MembersTable
data={filteredMembers}
loading={isLoading}
total={filteredMembers.length}
currentPage={currentPage}
pageSize={PAGE_SIZE}
searchQuery={searchQuery}
onPageChange={setPage}
onRowClick={handleRowClick}
/>
)}
</AuthZGuardContent>
<InviteMembersModal
open={isInviteModalOpen}
@@ -236,7 +295,6 @@ function MembersSettings(): JSX.Element {
<EditMemberDrawer
member={selectedMember}
open={selectedMember !== null}
onClose={handleDrawerClose}
onComplete={handleMemberEditComplete}
/>

View File

@@ -1,7 +1,11 @@
import type { TypesUserDTO } from 'api/generated/services/sigNoz.schemas';
import userEvent from '@testing-library/user-event';
import { rest, server } from 'mocks-server/server';
import { fireEvent, render, screen } from 'tests/test-utils';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
import MembersSettings from '../MembersSettings';
@@ -57,6 +61,7 @@ describe('MembersSettings (integration)', () => {
rest.get(USERS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockUsers })),
),
setupAuthzAdmin(),
);
});
@@ -123,10 +128,22 @@ describe('MembersSettings (integration)', () => {
expect(screen.queryByText('Member Details')).toBeInTheDocument();
});
it('still lists members when the permission check fails', async () => {
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
render(<MembersSettings />);
await expect(screen.findByText('Alice Smith')).resolves.toBeInTheDocument();
});
it('opens InviteMembersModal when "Invite member" button is clicked', async () => {
render(<MembersSettings />);
fireEvent.click(screen.getByRole('button', { name: /invite member/i }));
const inviteBtn = await screen.findByTestId('invite-member-btn');
await waitFor(() =>
expect(inviteBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await userEvent.click(inviteBtn);
await expect(
screen.findAllByPlaceholderText('e.g. john@signoz.io'),

View File

@@ -4,6 +4,8 @@ import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { toast } from '@signozhq/ui/sonner';
import InviteMembers from 'components/InviteMembers/InviteMembers';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import './InviteMembersModal.styles.scss';
@@ -58,18 +60,21 @@ function InviteMembersModal({
Cancel
</Button>
<Button
<AuthZButton
size="md"
variant="solid"
color="primary"
onClick={submit}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
loading={isSubmitting}
testId="invite-submit-btn"
>
{isSubmitting ? 'Inviting...' : 'Invite Team Members'}
</Button>
</AuthZButton>
</div>
)}
/>

View File

@@ -1,5 +1,11 @@
import { toast } from '@signozhq/ui/sonner';
import { render, screen, userEvent } from 'tests/test-utils';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import InviteMembersModal from '../InviteMembersModal';
@@ -55,6 +61,7 @@ describe('InviteMembersModal', () => {
beforeEach(() => {
jest.clearAllMocks();
mockInviteMembersProps = null;
server.use(setupAuthzAdmin());
});
describe('rendering', () => {
@@ -134,7 +141,7 @@ describe('InviteMembersModal', () => {
const { unmount } = renderComponent();
unmount();
const { getByRole } = render(
const { getByTestId } = render(
mockInviteMembersProps?.renderFooter({
submit: mockSubmit,
canSubmit: true,
@@ -142,10 +149,27 @@ describe('InviteMembersModal', () => {
}) as JSX.Element,
);
await user.click(getByRole('button', { name: /invite team members/i }));
const submit = getByTestId('invite-submit-btn');
await waitFor(() =>
expect(submit).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(submit);
expect(mockSubmit).toHaveBeenCalledTimes(1);
});
it('disables the Invite button without create permission', async () => {
server.use(setupAuthzDeny(UserCreatePermission));
renderComponent();
await waitFor(() =>
expect(screen.getByTestId('invite-submit-btn')).toHaveAttribute(
'aria-disabled',
'true',
),
);
});
});
describe('handleSuccess callback', () => {

View File

@@ -58,22 +58,6 @@
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;
}
.user-role {
display: flex;
align-items: center;
gap: 8px;
text-transform: capitalize;
color: var(--l2-foreground);
font-family: Inter;
font-size: 13px;
font-style: normal;
font-weight: 400;
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;
}
}
}

View File

@@ -8,7 +8,7 @@ import {
useUpdateMyUserV2,
} from 'api/generated/services/users';
import { toast } from '@signozhq/ui/sonner';
import { Check, FileTerminal, Mail, User } from '@signozhq/icons';
import { Check, FileTerminal, Mail } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
@@ -129,13 +129,9 @@ function UserInfo(): JSX.Element {
</div>
<div className="user-info-subsection">
<div className="user-email">
<div className="user-email" data-testid="user-info-email">
<Mail size={16} /> {user.email}
</div>
<div className="user-role">
<User size={16} /> {user.role.toLowerCase()}
</div>
</div>
</div>

View File

@@ -168,6 +168,13 @@ describe('MySettings Flows', () => {
expect(modalUpdateNameButton).toBeInTheDocument();
});
it('Should show the email and not the role', () => {
expect(screen.getByTestId('user-info-email')).toHaveTextContent(
'does-not-matter@signoz.io',
);
expect(screen.queryByText('admin')).not.toBeInTheDocument();
});
it('Should update the name on clicking Update button', async () => {
// Open the Update name modal first
const updateNameButton = screen.getByText(UPDATE_NAME_BUTTON_TEXT);
@@ -464,3 +471,34 @@ describe('MySettings Flows', () => {
});
});
});
describe('MySettings name update and app context', () => {
beforeEach(() => {
jest.clearAllMocks();
editUserFn.mockResolvedValue({});
mockUseActiveLicenseKey.mockReturnValue({
licenseKey: 'test-key',
isLoading: false,
});
});
it('updates the user in the app context with the new name', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const updateUser = jest.fn();
render(<MySettingsContainer />, undefined, {
appContextOverrides: { updateUser },
});
await user.click(screen.getByTestId('update-name-open-btn'));
const nameInput = screen.getByTestId('update-name-input');
await user.clear(nameInput);
await user.type(nameInput, 'New Name');
await user.click(screen.getByTestId(UPDATE_NAME_BUTTON_TEST_ID));
await waitFor(() =>
expect(updateUser).toHaveBeenCalledWith(
expect.objectContaining({ displayName: 'New Name' }),
),
);
});
});

View File

@@ -6,6 +6,8 @@ import InviteMembers from 'components/InviteMembers/InviteMembers';
import { InviteMemberRow, InviteResult } from 'components/InviteMembers/types';
import { useRoles } from 'components/RolesSelect/RolesSelect';
import { useNotifications } from 'hooks/useNotifications';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { getBaseUrl } from 'utils/basePath';
import { OnboardingQuestionHeader } from '../OnboardingQuestionHeader';
@@ -118,20 +120,22 @@ function InviteTeamMembers({
return (
<div className="onboarding-buttons-container">
<Button
<AuthZButton
size="md"
variant="solid"
color="primary"
width="100%"
onClick={submit}
loading={isButtonDisabled}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
testId="send-invites-button"
suffix={<ArrowRight size={12} />}
>
Send Invites
</Button>
</AuthZButton>
<Button
size="md"
variant="ghost"

View File

@@ -0,0 +1,78 @@
import { InviteMembersProps } from 'components/InviteMembers/types';
import type { useRoles } from 'components/RolesSelect/RolesSelect';
import type { useNotifications } from 'hooks/useNotifications';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { render, screen, waitFor } from 'tests/test-utils';
import InviteTeamMembers from '../InviteTeamMembers';
jest.mock('hooks/useNotifications', () => ({
useNotifications: (): ReturnType<typeof useNotifications> => ({
notifications: {
success: jest.fn(),
error: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
open: jest.fn(),
destroy: jest.fn(),
},
}),
}));
jest.mock('components/RolesSelect/RolesSelect', () => ({
useRoles: (): ReturnType<typeof useRoles> => ({
roles: [],
isLoading: false,
isError: false,
error: undefined,
refetch: jest.fn(),
}),
}));
jest.mock('components/InviteMembers/InviteMembers', () => {
return function MockInviteMembers(props: InviteMembersProps): JSX.Element {
return (
<div>
{props.renderFooter?.({
submit: jest.fn().mockResolvedValue([]),
reset: jest.fn(),
canSubmit: true,
isSubmitting: false,
touchedCount: 1,
})}
</div>
);
};
});
describe('InviteTeamMembers authz', () => {
it('enables Send Invites with create:user', async () => {
server.use(setupAuthzAdmin());
render(<InviteTeamMembers isLoading={false} onNext={jest.fn()} />);
const button = screen.getByTestId('send-invites-button');
await waitFor(() => expect(button).not.toHaveAttribute('aria-busy', 'true'));
expect(button).not.toHaveAttribute('aria-disabled', 'true');
});
it('disables Send Invites without create:user', async () => {
server.use(setupAuthzDeny(UserCreatePermission));
render(<InviteTeamMembers isLoading={false} onNext={jest.fn()} />);
await waitFor(() =>
expect(screen.getByTestId('send-invites-button')).toHaveAttribute(
'data-denied-permissions',
UserCreatePermission,
),
);
expect(screen.getByTestId('send-invites-button')).toHaveAttribute(
'aria-disabled',
'true',
);
});
});

View File

@@ -22,6 +22,8 @@ import { useGetGlobalConfig } from 'api/generated/services/global';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { isEmpty } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
import { isModifierKeyPressed } from 'utils/app';
@@ -711,6 +713,7 @@ function OnboardingAddDataSource(): JSX.Element {
<Button
type="default"
className="periscope-btn invite-teammate-btn outlined"
data-testid="invite-teammate-btn"
onClick={handleShowInviteTeamMembersModal}
icon={<UserPlus size={16} />}
>
@@ -1185,7 +1188,7 @@ function OnboardingAddDataSource(): JSX.Element {
>
Cancel
</SignozButton>
<SignozButton
<AuthZButton
size="md"
color="primary"
variant="solid"
@@ -1196,13 +1199,16 @@ function OnboardingAddDataSource(): JSX.Element {
);
void submit();
}}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
loading={isSubmitting}
suffix={<ArrowRight size={14} />}
testId="onboarding-send-invites-btn"
>
Send Invites
</SignozButton>
</AuthZButton>
</div>
)}
/>

View File

@@ -0,0 +1,61 @@
import { InviteMembersProps } from 'components/InviteMembers/types';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import OnboardingAddDataSource from '../AddDataSource';
jest.mock('components/LaunchChatSupport/LaunchChatSupport', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('components/InviteMembers/InviteMembers', () => {
return function MockInviteMembers(props: InviteMembersProps): JSX.Element {
return (
<div>
{props.renderFooter?.({
submit: jest.fn().mockResolvedValue([]),
reset: jest.fn(),
canSubmit: true,
isSubmitting: false,
touchedCount: 1,
})}
</div>
);
};
});
async function openInviteModal(): Promise<HTMLElement> {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<OnboardingAddDataSource />);
await user.click(screen.getByTestId('invite-teammate-btn'));
return screen.findByTestId('onboarding-send-invites-btn');
}
describe('OnboardingAddDataSource invite modal authz', () => {
it('enables Send Invites with create:user', async () => {
server.use(setupAuthzAdmin());
const button = await openInviteModal();
await waitFor(() => expect(button).not.toHaveAttribute('aria-busy', 'true'));
expect(button).not.toHaveAttribute('aria-disabled', 'true');
});
it('disables Send Invites without create:user', async () => {
server.use(setupAuthzDeny(UserCreatePermission));
const button = await openInviteModal();
await waitFor(() =>
expect(button).toHaveAttribute(
'data-denied-permissions',
UserCreatePermission,
),
);
expect(button).toHaveAttribute('aria-disabled', 'true');
});
});

View File

@@ -1,15 +1,16 @@
import { Form } from 'antd';
import QueryBuilderSearchV2 from 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2';
import { rest, server } from 'mocks-server/server';
import { server } from 'mocks-server/server';
import { act, render, waitFor } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';
import type { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import type {
IBuilderQuery,
TagFilter,
} from 'types/api/queryBuilder/queryBuilderData';
BaseBuilderQuery,
QueryRangePayloadV5,
} from 'types/api/v5/queryRange';
import { pipelineFields } from '../../../../config';
import { queryRangeV5Handler } from '../../../../Preview/__tests__/fixtures';
import FilterInput from '..';
jest.mock(
@@ -38,27 +39,22 @@ const v5Filter: TagFilter = {
};
describe('Pipeline FilterInput', () => {
it('previews sample logs with the legacy key types the v3 logs builder reads', async () => {
const previewFilters: TagFilter[] = [];
server.use(
rest.post('*/api/v3/query_range', async (req, res, ctx) => {
const body: QueryRangePayload = await req.json();
const query = body.compositeQuery.builderQueries?.A as IBuilderQuery;
if (query.filters) {
previewFilters.push(query.filters);
}
return res(ctx.status(200), ctx.json({ data: { result: [] } }));
}),
);
it('saves the filter with the legacy key types the pipeline builders read', () => {
const onValuesChange = jest.fn() as jest.MockedFunction<
(changedValues: { filter: TagFilter }) => void
>;
render(<Form>{filterField && <FilterInput fieldData={filterField} />}</Form>);
render(
<Form onValuesChange={onValuesChange}>
{filterField && <FilterInput fieldData={filterField} />}
</Form>,
);
const { onChange } = jest.mocked(QueryBuilderSearchV2).mock.calls[0][0];
act(() => onChange(v5Filter));
await waitFor(() => expect(previewFilters).not.toHaveLength(0));
expect(
previewFilters[previewFilters.length - 1].items.map((item) => [
onValuesChange.mock.lastCall?.[0].filter.items.map((item) => [
item.key?.key,
item.key?.type,
]),
@@ -67,4 +63,26 @@ describe('Pipeline FilterInput', () => {
['severity_text', ''],
]);
});
it('previews sample logs for the picked filter', async () => {
const requests: QueryRangePayloadV5[] = [];
server.use(queryRangeV5Handler({ rows: [], count: 0, requests }));
render(<Form>{filterField && <FilterInput fieldData={filterField} />}</Form>);
const { onChange } = jest.mocked(QueryBuilderSearchV2).mock.calls[0][0];
act(() => onChange(v5Filter));
await waitFor(() =>
expect(
requests
.filter((request) => request.requestType === 'raw')
.map(
(request) =>
(request.compositeQuery.queries[0].spec as BaseBuilderQuery).filter
?.expression,
),
).toContain("http.method = 'GET' AND severity_text = 'ERROR'"),
);
});
});

View File

@@ -0,0 +1,64 @@
import { server } from 'mocks-server/server';
import { render, screen } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { BaseBuilderQuery, QueryRangePayloadV5 } from 'types/api/v5/queryRange';
import { queryRangeV5Handler } from '../../__tests__/fixtures';
import LogsFilterPreview from '../index';
const filter: TagFilter = {
op: 'AND',
items: [
{
id: 'code-function',
key: { key: 'code.function', dataType: DataTypes.String, type: 'tag' },
op: '=',
value: 'PlaceOrder',
},
],
};
describe('LogsFilterPreview', () => {
it('loads the sample logs and the match count from query_range v5', async () => {
const requests: QueryRangePayloadV5[] = [];
server.use(
queryRangeV5Handler({
rows: [
{
timestamp: '2026-11-16T10:00:02Z',
data: { id: 'log-2', body: 'order placed' },
},
{
timestamp: '2026-11-16T10:00:01Z',
data: { id: 'log-1', body: 'payment charged' },
},
],
count: 4213,
requests,
}),
);
render(<LogsFilterPreview filter={filter} />);
await expect(
screen.findByTestId('pipeline-filter-preview-count'),
).resolves.toHaveTextContent('4213 matches in');
await expect(
screen.findAllByTestId('pipeline-preview-log'),
).resolves.toHaveLength(2);
const specOf = (requestType: string): BaseBuilderQuery | undefined =>
requests.find((request) => request.requestType === requestType)
?.compositeQuery.queries[0].spec as BaseBuilderQuery | undefined;
expect(specOf('raw')).toMatchObject({
filter: { expression: "code.function = 'PlaceOrder'" },
limit: 5,
order: [{ key: { name: 'timestamp' }, direction: 'desc' }],
});
expect(specOf('scalar')?.filter?.expression).toBe(
"code.function = 'PlaceOrder'",
);
});
});

View File

@@ -0,0 +1,54 @@
import { PipelineSimulationRequest } from 'api/pipeline/preview';
import { pipelineMockData } from 'container/PipelinePage/mocks/pipeline';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { queryRangeV5Handler } from '../../__tests__/fixtures';
import PipelineProcessingPreview from '../index';
describe('PipelineProcessingPreview', () => {
it('sends object bodies to the simulation as JSON strings', async () => {
const simulations: PipelineSimulationRequest[] = [];
server.use(
queryRangeV5Handler({
rows: [
{
timestamp: '2026-11-16T10:00:02Z',
data: {
id: 'log-2',
body: { order: { id: 'o-1' }, message: 'order placed' },
},
},
{
timestamp: '2026-11-16T10:00:01Z',
data: { id: 'log-1', body: 'payment charged' },
},
],
count: 2,
}),
rest.post('*/api/v1/logs/pipelines/preview', async (req, res, ctx) => {
const body: PipelineSimulationRequest = await req.json();
simulations.push(body);
return res(
ctx.status(200),
ctx.json({ status: 'success', data: { logs: body.logs } }),
);
}),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<PipelineProcessingPreview pipeline={pipelineMockData[0]} />);
await expect(
screen.findAllByTestId('pipeline-preview-log'),
).resolves.toHaveLength(2);
await user.click(screen.getByTestId('pipeline-simulate-processing'));
await waitFor(() => expect(simulations).toHaveLength(1));
expect(simulations[0].logs.map((log) => log.body)).toStrictEqual([
'{"order":{"id":"o-1"},"message":"order placed"}',
'payment charged',
]);
});
});

View File

@@ -19,6 +19,7 @@ function LogsProcessingSimulator({
disabled={(inputLogs?.length || 0) < 1}
type="primary"
onClick={simulate}
data-testid="pipeline-simulate-processing"
>
Simulate Processing
</Button>

View File

@@ -0,0 +1,63 @@
import {
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
type Querybuildertypesv5RawDataDTO,
type Querybuildertypesv5RawRowDTO,
type Querybuildertypesv5ScalarDataDTO,
} from 'api/generated/services/sigNoz.schemas';
import { rest, RestHandler } from 'msw';
import { QueryRangePayloadV5 } from 'types/api/v5/queryRange';
function countResponse(count: number): QueryRangeV5200 {
const result: Querybuildertypesv5ScalarDataDTO = {
columns: [
{
name: '__result_0',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
},
],
data: [[count]],
};
return {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: { results: [result] },
},
};
}
function rowsResponse(rows: Querybuildertypesv5RawRowDTO[]): QueryRangeV5200 {
const result: Querybuildertypesv5RawDataDTO = { queryName: 'A', rows };
return {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.raw,
data: { results: [result] },
},
};
}
export function queryRangeV5Handler({
rows,
count,
requests,
}: {
rows: Querybuildertypesv5RawRowDTO[];
count: number;
requests?: QueryRangePayloadV5[];
}): RestHandler {
return rest.post('*/api/v5/query_range', async (req, res, ctx) => {
const body: QueryRangePayloadV5 = await req.json();
requests?.push(body);
return res(
ctx.status(200),
ctx.json(
body.requestType === 'scalar' ? countResponse(count) : rowsResponse(rows),
),
);
});
}

View File

@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import {
initialFilters,
initialQueriesMap,
@@ -34,18 +34,26 @@ function LogsCountInInterval({
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: timeInterval,
},
DEFAULT_ENTITY_VERSION,
ENTITY_VERSION_V5,
);
const count = useMemo(() => {
const table = result.data?.payload?.data?.result?.[0]?.table;
const countColumn = table?.columns.find((column) => column.isValueColumn);
return (
countColumn && table?.rows[0]?.data[countColumn.id || countColumn.name]
);
}, [result.data]);
if (!result.isFetched) {
return null;
}
const count =
result?.data?.payload?.data?.newResult?.data?.result?.[0]?.series?.[0]
?.values?.[0]?.value;
return (
<div className="logs-filter-preview-matched-logs-count">
<div
className="logs-filter-preview-matched-logs-count"
data-testid="pipeline-filter-preview-count"
>
{count} matches in
</div>
);

View File

@@ -4,6 +4,7 @@ import simulatePipelineProcessing, {
} from 'api/pipeline/preview';
import { AxiosError } from 'axios';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { getBodyDisplay } from 'lib/logs/logBody';
import { ILog } from 'types/api/logs/log';
import { PipelineData } from 'types/api/pipeline/def';
@@ -29,6 +30,8 @@ const usePipelinePreview = ({
...l,
// log timestamps in query service API are unix nanos
timestamp: new Date(l.timestamp).getTime() * 10 ** 6,
// the preview API only accepts a string body
body: getBodyDisplay(l.body),
}));
const response = useQuery<PipelineSimulationResponse, AxiosError>({

View File

@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import {
initialFilters,
initialQueriesMap,
@@ -50,7 +50,7 @@ const useSampleLogs = ({
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: timeInterval,
},
DEFAULT_ENTITY_VERSION,
ENTITY_VERSION_V5,
);
const { isFetching: isLoading, data } = response;

View File

@@ -329,7 +329,7 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
it('returns all resources from RESOURCE_ORDER even with empty transaction groups', () => {
const result = transformTransactionGroupsToResourcePermissions([]);
expect(result).toHaveLength(13);
expect(result).toHaveLength(15);
expect(result.map((r) => r.resourceKind)).toStrictEqual([
'factor-api-key',
'dashboard',
@@ -338,12 +338,14 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
'meter-metrics',
'metrics',
'notification-channel',
'factor-password',
'quick-filter',
'role',
'saved-view',
'serviceaccount',
'subscription',
'traces',
'user',
]);
});
@@ -424,7 +426,7 @@ describe('createEmptyRolePermissions', () => {
it('creates permissions for all resources in RESOURCE_ORDER', () => {
const result = createEmptyRolePermissions();
expect(result).toHaveLength(13);
expect(result).toHaveLength(15);
expect(result.map((r) => r.resourceKind)).toStrictEqual([
'factor-api-key',
'dashboard',
@@ -433,12 +435,14 @@ describe('createEmptyRolePermissions', () => {
'meter-metrics',
'metrics',
'notification-channel',
'factor-password',
'quick-filter',
'role',
'saved-view',
'serviceaccount',
'subscription',
'traces',
'user',
]);
});

View File

@@ -150,6 +150,21 @@ export const RESOURCE_PANELS: Record<AuthZResource, ResourcePanelConfig> = {
docsAnchor: 'meter-metrics',
selectorType: 'telemetryBuilder',
},
user: {
label: 'User',
description: 'Users of the workspace, including their roles and permissions.',
icon: Bot,
selectorPlaceholder: 'Type user ID, separate multiple with comma or space',
docsAnchor: 'user',
},
'factor-password': {
label: 'Passwords',
description: 'Passwords of the workspace users.',
icon: Key,
selectorPlaceholder:
'Type password ID, separate multiple with comma or space',
docsAnchor: 'factor-password',
},
};
export const RESOURCE_ORDER = (

View File

@@ -526,14 +526,6 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
]);
useEffect(() => {
if (!isAdmin) {
setHelpSupportDropdownMenuItems((prevState) =>
prevState.filter(
(item) => !('key' in item) || item.key !== 'invite-collaborators',
),
);
}
const showAddCreditCardModal =
!isPremiumSupportEnabled && !trialInfo?.trialConvertedToSubscription;
@@ -616,7 +608,6 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
isAdmin,
isChatSupportEnabled,
isPremiumSupportEnabled,
isCloudUser,

View File

@@ -0,0 +1,51 @@
import ROUTES from 'constants/routes';
import { mockNavigate } from 'tests/router-mocks';
import { render, screen, userEvent } from 'tests/test-utils';
import { USER_ROLES } from 'types/roles';
import SideNav from '../SideNav';
jest.mock('providers/cmdKProvider', () => ({
useCmdK: (): { openCmdK: jest.Mock } => ({ openCmdK: jest.fn() }),
}));
jest.mock('hooks/hotkeys/useKeyboardHotkeys', () => ({
useKeyboardHotkeys: (): Record<string, jest.Mock> => ({
registerShortcut: jest.fn(),
deregisterShortcut: jest.fn(),
}),
}));
const INVITE_ITEM_TEST_ID = 'help-menu-invite-collaborators';
async function openHelpMenu(
user: ReturnType<typeof userEvent.setup>,
): Promise<void> {
await user.click(screen.getByTestId('help-support-nav-item'));
await screen.findByRole('menu');
}
describe('SideNav help dropdown invite entry', () => {
let mockNavigateFn: ReturnType<typeof mockNavigate>;
beforeEach(() => {
jest.clearAllMocks();
mockNavigateFn = mockNavigate();
});
it.each([USER_ROLES.ADMIN, USER_ROLES.EDITOR, USER_ROLES.VIEWER])(
'shows Invite a Team Member and opens the invite modal for %s',
async (role) => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<SideNav isPinned />, undefined, { role });
await openHelpMenu(user);
await user.click(screen.getByTestId(INVITE_ITEM_TEST_ID));
expect(mockNavigateFn).toHaveBeenCalledWith(
`${ROUTES.MEMBERS_SETTINGS}?invite=true`,
);
},
);
});

View File

@@ -1,28 +1,46 @@
import { act, renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
import { act, renderHook, type RenderHookResult } from '@testing-library/react';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import { TestRouter } from 'tests/router';
import { useNavigationBlocker } from '../useNavigationBlocker';
function settle(): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, 60);
type BlockerHook = RenderHookResult<
ReturnType<typeof useNavigationBlocker>,
{ shouldBlock: boolean }
>;
function wrapper({ children }: { children: ReactNode }): JSX.Element {
return <TestRouter initialRoute="/start">{children}</TestRouter>;
}
/** Lets router updates, and the `popstate` a POP arrives on, reach React. */
async function settle(): Promise<void> {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 60));
});
}
describe('useNavigationBlocker against the real history', () => {
beforeEach(async () => {
navigate('/start');
navigate('/a');
navigate('/b');
navigate('/c');
await settle();
});
/** Mounts the blocker, disarmed, at /c with /start, /a and /b behind it. */
async function renderAtC(): Promise<BlockerHook> {
const hook = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: false } },
);
navigate('/a');
navigate('/b');
navigate('/c');
await settle();
return hook;
}
describe('useNavigationBlocker against the real history', () => {
it('lets a bypassed browser Back through without showing the modal', async () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const { result, rerender } = await renderAtC();
rerender({ shouldBlock: true });
act(() => result.current.allowNextNavigation());
act(() => window.history.back());
window.history.back();
await settle();
expect(getCurrentLocation().pathname).toBe('/b');
@@ -30,23 +48,26 @@ describe('useNavigationBlocker against the real history', () => {
});
it('keeps blocking after a bypassed navigation', async () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const { result, rerender } = await renderAtC();
rerender({ shouldBlock: true });
act(() => result.current.allowNextNavigation());
act(() => window.history.back());
window.history.back();
await settle();
navigate('/elsewhere');
await settle();
act(() => navigate('/elsewhere'));
expect(getCurrentLocation().pathname).toBe('/b');
expect(result.current.isBlocked).toBe(true);
});
it('replays a blocked Forward on confirm', async () => {
act(() => window.history.go(-2));
const { result, rerender } = await renderAtC();
window.history.go(-2);
await settle();
const { result } = renderHook(() => useNavigationBlocker(true));
rerender({ shouldBlock: true });
act(() => window.history.forward());
window.history.forward();
await settle();
expect(result.current.isBlocked).toBe(true);
@@ -59,12 +80,16 @@ describe('useNavigationBlocker against the real history', () => {
});
it('replays a blocked multi-entry jump on confirm', async () => {
act(() => window.history.go(-2));
const { result, rerender } = await renderAtC();
window.history.go(-2);
await settle();
const { result } = renderHook(() => useNavigationBlocker(true));
rerender({ shouldBlock: true });
act(() => window.history.go(2));
window.history.go(2);
await settle();
expect(result.current.isBlocked).toBe(true);
act(() => result.current.confirmNavigation());
await settle();

View File

@@ -1,383 +0,0 @@
import { act, renderHook } from '@testing-library/react';
import { useNavigationBlocker } from '../useNavigationBlocker';
const mockUnblock = jest.fn();
const mockBlock = jest.fn().mockReturnValue(mockUnblock);
const mockRetry = jest.fn();
jest.mock('lib/router/navigation', () => ({
blockNavigation: (blocker: unknown): unknown => mockBlock(blocker),
}));
describe('useNavigationBlocker', () => {
const mockLocation = {
pathname: '/new-route',
search: '',
hash: '',
state: null,
key: 'test-key',
};
/**
* `blockNavigation` hands the blocker one transition object and cancels the
* navigation on its own; `retry()` is the only way through, which is why
* these cases assert on `retry` rather than on a returned `false`.
*/
function transition(action: string): {
location: typeof mockLocation;
action: string;
retry: jest.Mock;
} {
return { location: mockLocation, action, retry: mockRetry };
}
beforeEach(() => {
jest.clearAllMocks();
mockBlock.mockReturnValue(mockUnblock);
});
describe('initial state', () => {
it('returns isBlocked false when shouldBlock is false', () => {
const { result } = renderHook(() => useNavigationBlocker(false));
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
it('returns isBlocked false when shouldBlock is true but no navigation attempted', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
});
describe('blockNavigation behavior', () => {
it('registers a blocker when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true));
expect(mockBlock).toHaveBeenCalledTimes(1);
expect(mockBlock).toHaveBeenCalledWith(expect.any(Function));
});
it('does not register a blocker when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false));
expect(mockBlock).not.toHaveBeenCalled();
});
it('unblocks when shouldBlock changes from true to false', () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ initialProps: { shouldBlock: true } },
);
expect(mockBlock).toHaveBeenCalledTimes(1);
rerender({ shouldBlock: false });
expect(mockUnblock).toHaveBeenCalledTimes(1);
});
it('unblocks on unmount when blocking', () => {
const { unmount } = renderHook(() => useNavigationBlocker(true));
unmount();
expect(mockUnblock).toHaveBeenCalledTimes(1);
});
it('does not call unblock on unmount when not blocking', () => {
const { unmount } = renderHook(() => useNavigationBlocker(false));
unmount();
expect(mockUnblock).not.toHaveBeenCalled();
});
});
describe('navigation blocking', () => {
it('blocks PUSH navigation and sets blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails).toStrictEqual({
location: mockLocation,
action: 'PUSH',
});
});
it('blocks REPLACE navigation and sets blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('REPLACE'));
});
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails?.action).toBe('REPLACE');
});
it('blocks POP navigation and sets blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('POP'));
});
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails?.action).toBe('POP');
});
});
describe('confirmNavigation', () => {
it('does nothing when no blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
act(() => {
result.current.confirmNavigation();
});
expect(mockRetry).not.toHaveBeenCalled();
});
it('unblocks before retrying, or the blocker would catch the retry too', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
act(() => {
result.current.confirmNavigation();
});
expect(mockUnblock).toHaveBeenCalled();
expect(mockUnblock.mock.invocationCallOrder[0]).toBeLessThan(
mockRetry.mock.invocationCallOrder[0],
);
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
it.each(['PUSH', 'REPLACE', 'POP'])(
'retries the blocked %s, which replays it with its own action',
(action) => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition(action));
});
act(() => {
result.current.confirmNavigation();
});
expect(mockRetry).toHaveBeenCalledTimes(1);
},
);
});
describe('cancelNavigation', () => {
it('clears blockedNavigationDetails without performing navigation', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(result.current.isBlocked).toBe(true);
act(() => {
result.current.cancelNavigation();
});
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
expect(mockRetry).not.toHaveBeenCalled();
});
});
describe('allowNextNavigation', () => {
it('bypasses blocking for next navigation only', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
act(() => {
result.current.allowNextNavigation();
});
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).toHaveBeenCalledTimes(1);
expect(result.current.isBlocked).toBe(false);
expect(mockBlock).toHaveBeenCalledTimes(1);
expect(mockUnblock).not.toHaveBeenCalled();
});
it('drops a pending prompt when a bypassed navigation goes through', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
const stale = jest.fn();
act(() => {
blockCallback({ ...transition('PUSH'), retry: stale });
});
expect(result.current.isBlocked).toBe(true);
act(() => {
result.current.allowNextNavigation();
});
act(() => {
blockCallback(transition('PUSH'));
});
act(() => {
result.current.confirmNavigation();
});
expect(result.current.isBlocked).toBe(false);
expect(stale).not.toHaveBeenCalled();
});
it('resumes blocking after bypassed navigation', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
result.current.allowNextNavigation();
});
act(() => {
blockCallback(transition('PUSH'));
});
mockRetry.mockClear();
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
});
it('resets bypass flag when shouldBlock changes to false before navigation', () => {
const { result, rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ initialProps: { shouldBlock: true } },
);
act(() => {
result.current.allowNextNavigation();
});
rerender({ shouldBlock: false });
rerender({ shouldBlock: true });
const blockCallback = mockBlock.mock.calls[1][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
});
});
describe('beforeunload event', () => {
let addEventListenerSpy: jest.SpyInstance;
let removeEventListenerSpy: jest.SpyInstance;
beforeEach(() => {
addEventListenerSpy = jest.spyOn(window, 'addEventListener');
removeEventListenerSpy = jest.spyOn(window, 'removeEventListener');
});
afterEach(() => {
addEventListenerSpy.mockRestore();
removeEventListenerSpy.mockRestore();
});
it('adds beforeunload listener when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true));
expect(addEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('does not add beforeunload listener when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false));
expect(addEventListenerSpy).not.toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener on unmount', () => {
const { unmount } = renderHook(() => useNavigationBlocker(true));
unmount();
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener when shouldBlock changes to false', () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ initialProps: { shouldBlock: true } },
);
rerender({ shouldBlock: false });
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('beforeunload handler calls preventDefault', () => {
renderHook(() => useNavigationBlocker(true));
const beforeUnloadHandler = addEventListenerSpy.mock.calls.find(
(call) => call[0] === 'beforeunload',
)?.[1];
const mockEvent = {
preventDefault: jest.fn(),
};
const result = beforeUnloadHandler(mockEvent);
expect(mockEvent.preventDefault).toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
});

View File

@@ -0,0 +1,317 @@
import type { ReactNode } from 'react';
import { act, renderHook, waitFor } from '@testing-library/react';
import { back, getCurrentLocation, navigate } from 'lib/router/navigation';
import { TestRouter } from 'tests/router';
import { useNavigationBlocker } from '../useNavigationBlocker';
function wrapper({ children }: { children: ReactNode }): JSX.Element {
return <TestRouter initialRoute="/start">{children}</TestRouter>;
}
/** Lets router updates, and the `popstate` a POP arrives on, reach React. */
async function settle(): Promise<void> {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
describe('useNavigationBlocker', () => {
describe('initial state', () => {
it('returns isBlocked false when shouldBlock is false', () => {
const { result } = renderHook(() => useNavigationBlocker(false), {
wrapper,
});
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
it('returns isBlocked false when shouldBlock is true but no navigation attempted', () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
});
describe('navigation blocking', () => {
it('lets navigation through when shouldBlock is false', async () => {
renderHook(() => useNavigationBlocker(false), { wrapper });
navigate('/next');
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
});
it('blocks PUSH navigation and sets blockedNavigationDetails', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails).toMatchObject({
location: { pathname: '/next' },
action: 'PUSH',
});
expect(getCurrentLocation().pathname).toBe('/start');
});
it('blocks REPLACE navigation and sets blockedNavigationDetails', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next', { replace: true });
await settle();
expect(result.current.blockedNavigationDetails?.action).toBe('REPLACE');
});
it('blocks POP navigation and sets blockedNavigationDetails', async () => {
const { result, rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: false } },
);
navigate('/next');
await settle();
rerender({ shouldBlock: true });
await settle();
back();
await waitFor(() => expect(result.current.isBlocked).toBe(true));
expect(result.current.blockedNavigationDetails).toMatchObject({
location: { pathname: '/start' },
action: 'POP',
});
await waitFor(() => expect(getCurrentLocation().pathname).toBe('/next'));
});
it('stops blocking when shouldBlock changes from true to false', async () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: true } },
);
rerender({ shouldBlock: false });
navigate('/next');
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
});
});
describe('confirmNavigation', () => {
it('does nothing when nothing is blocked', () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
act(() => result.current.confirmNavigation());
expect(getCurrentLocation().pathname).toBe('/start');
});
it('completes the blocked navigation', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next', { state: { from: 'test' } });
await settle();
act(() => result.current.confirmNavigation());
await settle();
expect(getCurrentLocation()).toMatchObject({
pathname: '/next',
state: { from: 'test' },
});
expect(result.current.isBlocked).toBe(false);
});
it('keeps a blocked REPLACE a replace', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
const before = window.history.length;
navigate('/next', { replace: true });
await settle();
act(() => result.current.confirmNavigation());
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
expect(window.history).toHaveLength(before);
});
});
describe('cancelNavigation', () => {
it('clears blockedNavigationDetails without performing navigation', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
act(() => result.current.cancelNavigation());
await settle();
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
expect(getCurrentLocation().pathname).toBe('/start');
});
it('keeps blocking after a cancel', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
act(() => result.current.cancelNavigation());
await settle();
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
});
});
describe('allowNextNavigation', () => {
it('bypasses blocking for next navigation only', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
act(() => result.current.allowNextNavigation());
navigate('/next');
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
expect(result.current.isBlocked).toBe(false);
navigate('/after');
await settle();
expect(result.current.isBlocked).toBe(true);
expect(getCurrentLocation().pathname).toBe('/next');
});
it('drops a pending prompt when a bypassed navigation goes through', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
act(() => result.current.allowNextNavigation());
navigate('/other');
await settle();
expect(getCurrentLocation().pathname).toBe('/other');
expect(result.current.isBlocked).toBe(false);
});
it('resets bypass flag when shouldBlock changes to false before navigation', async () => {
const { result, rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: true } },
);
act(() => result.current.allowNextNavigation());
rerender({ shouldBlock: false });
rerender({ shouldBlock: true });
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
});
});
describe('beforeunload event', () => {
let addEventListenerSpy: jest.SpyInstance;
let removeEventListenerSpy: jest.SpyInstance;
beforeEach(() => {
addEventListenerSpy = jest.spyOn(window, 'addEventListener');
removeEventListenerSpy = jest.spyOn(window, 'removeEventListener');
});
afterEach(() => {
addEventListenerSpy.mockRestore();
removeEventListenerSpy.mockRestore();
});
it('adds beforeunload listener when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true), { wrapper });
expect(addEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('does not add beforeunload listener when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false), { wrapper });
expect(addEventListenerSpy).not.toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener on unmount', () => {
const { unmount } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
unmount();
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener when shouldBlock changes to false', () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: true } },
);
rerender({ shouldBlock: false });
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('beforeunload handler calls preventDefault', () => {
renderHook(() => useNavigationBlocker(true), { wrapper });
const beforeUnloadHandler = addEventListenerSpy.mock.calls.find(
(call) => call[0] === 'beforeunload',
)?.[1];
const mockEvent = {
preventDefault: jest.fn(),
};
const result = beforeUnloadHandler(mockEvent);
expect(mockEvent.preventDefault).toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
});

View File

@@ -0,0 +1,64 @@
import { ReactNode } from 'react';
import { renderHook } from 'tests/test-utils';
import { TestRouter } from 'tests/router';
// jest.config.ts maps every `useSafeNavigate` import to a mock; the extension
// slips past that mapping.
const { useSafeNavigate } = jest.requireActual<
typeof import('hooks/useSafeNavigate')
>('../useSafeNavigate.ts');
function wrapper({ children }: { children: ReactNode }): JSX.Element {
return <TestRouter initialRoute="/page?a=1">{children}</TestRouter>;
}
describe('useSafeNavigate same-URL check', () => {
let pushState: jest.SpyInstance;
let replaceState: jest.SpyInstance;
beforeEach(() => {
pushState = jest.spyOn(window.history, 'pushState');
replaceState = jest.spyOn(window.history, 'replaceState');
});
afterEach(() => {
jest.restoreAllMocks();
});
function render(): ReturnType<typeof useSafeNavigate>['safeNavigate'] {
const { result } = renderHook(() => useSafeNavigate(), { wrapper });
pushState.mockClear();
replaceState.mockClear();
return result.current.safeNavigate;
}
it('navigates to a different URL', () => {
const safeNavigate = render();
safeNavigate('/page?a=2');
expect(pushState).toHaveBeenCalledTimes(1);
expect(window.location.search).toBe('?a=2');
});
it('skips the URL the router is on', () => {
const safeNavigate = render();
safeNavigate('/page?a=1');
expect(pushState).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
});
it('skips the URL a shallow write published ahead of the router', () => {
const safeNavigate = render();
// A nuqs write: it reaches the address bar but not the router.
window.history.replaceState(window.history.state, '', '/page?a=1&b=1');
replaceState.mockClear();
safeNavigate('/page?a=1&b=1');
expect(pushState).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
});
});

View File

@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';
import useUrlQuery from 'hooks/useUrlQuery';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { useGetCompositeQueryParam } from './useGetCompositeQueryParam';
@@ -17,10 +18,19 @@ export const useShareBuilderUrl = ({
}: UseShareBuilderUrlParams): void => {
const { resetQuery, redirectWithQueryBuilderData } = useQueryBuilder();
const urlQuery = useUrlQuery();
const { pathname } = useAppLocation();
// The page that owns this query. A caller can keep rendering for a beat after
// a sibling pushes the next route (tab switches do this), and publishing then
// writes this page's query onto the URL of the page being entered.
const ownerPathname = useRef(pathname);
const compositeQuery = useGetCompositeQueryParam();
useEffect(() => {
if (pathname !== ownerPathname.current) {
return;
}
if (!compositeQuery || forceReset) {
resetQuery(defaultValue);
redirectWithQueryBuilderData(defaultValue);
@@ -32,5 +42,6 @@ export const useShareBuilderUrl = ({
compositeQuery,
resetQuery,
forceReset,
pathname,
]);
};

View File

@@ -6,7 +6,6 @@ import useComponentPermission from './useComponentPermission';
describe('useComponentPermission', () => {
const componentList: ComponentTypes[] = [
'current_org_settings',
'invite_members',
'create_new_dashboards',
'import_dashboard',
'export_dashboard',
@@ -29,7 +28,6 @@ describe('useComponentPermission', () => {
);
const expectedResult = [
true, // current_org_settings
true, // invite_members
true, // create_new_dashboards
true, // import_dashboard
true, // export_dashboard
@@ -54,7 +52,6 @@ describe('useComponentPermission', () => {
);
const expectedResult = [
false, // current_org_settings
false, // invite_members
true, // create_new_dashboards
true, // import_dashboard
true, // export_dashboard
@@ -79,7 +76,6 @@ describe('useComponentPermission', () => {
);
const expectedResult = [
false, // current_org_settings
false, // invite_members
false, // create_new_dashboards
false, // import_dashboard
true, // export_dashboard

View File

@@ -1,10 +1,10 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { blockNavigation } from 'lib/router/navigation';
import { useCallback, useEffect, useRef } from 'react';
import type {
AppLocation,
BlockedTransition,
BlockerFunction,
NavigationAction,
} from 'lib/router/types';
import { useAppBlocker } from 'lib/router/useAppBlocker';
interface BlockedNavigationDetails {
location: AppLocation;
@@ -48,45 +48,31 @@ interface UseNavigationBlockerResult {
export function useNavigationBlocker(
shouldBlock: boolean,
): UseNavigationBlockerResult {
const [blockedNavigation, setBlockedNavigation] =
useState<BlockedNavigationDetails | null>(null);
const unblockRef = useRef<(() => void) | null>(null);
const retryRef = useRef<(() => void) | null>(null);
const bypassNextRef = useRef(false);
const blockedActionRef = useRef<NavigationAction>('PUSH');
useEffect(() => {
if (!shouldBlock) {
if (unblockRef.current) {
unblockRef.current();
unblockRef.current = null;
}
bypassNextRef.current = false;
return;
}
}, [shouldBlock]);
unblockRef.current = blockNavigation((transition: BlockedTransition) => {
const blockerFunction = useCallback<BlockerFunction>(
({ action }) => {
if (!shouldBlock) {
return false;
}
if (bypassNextRef.current) {
bypassNextRef.current = false;
retryRef.current = null;
setBlockedNavigation(null);
transition.retry();
return;
return false;
}
retryRef.current = transition.retry;
setBlockedNavigation({
location: transition.location,
action: transition.action,
});
});
blockedActionRef.current = action;
return true;
},
[shouldBlock],
);
return (): void => {
if (unblockRef.current) {
unblockRef.current();
unblockRef.current = null;
}
bypassNextRef.current = false;
};
}, [shouldBlock]);
const blocker = useAppBlocker(blockerFunction);
useEffect(() => {
if (!shouldBlock) {
@@ -104,37 +90,30 @@ export function useNavigationBlocker(
};
}, [shouldBlock]);
// The router replays a proceeded navigation itself, so a blocked REPLACE
// stays a REPLACE and a blocked POP still walks the history stack.
const confirmNavigation = useCallback((): void => {
if (!blockedNavigation) {
return;
if (blocker.state === 'blocked') {
blocker.proceed();
}
if (unblockRef.current) {
unblockRef.current();
unblockRef.current = null;
}
setBlockedNavigation(null);
// The transition replays itself, so a blocked REPLACE stays a REPLACE and
// a blocked POP still walks the history stack.
const retry = retryRef.current;
retryRef.current = null;
retry?.();
}, [blockedNavigation]);
}, [blocker]);
const cancelNavigation = useCallback((): void => {
retryRef.current = null;
setBlockedNavigation(null);
}, []);
if (blocker.state === 'blocked') {
blocker.reset();
}
}, [blocker]);
const allowNextNavigation = useCallback((): void => {
bypassNextRef.current = true;
}, []);
return {
isBlocked: blockedNavigation !== null,
blockedNavigationDetails: blockedNavigation,
isBlocked: blocker.state === 'blocked',
blockedNavigationDetails:
blocker.state === 'blocked'
? { location: blocker.location, action: blockedActionRef.current }
: null,
confirmNavigation,
cancelNavigation,
allowNextNavigation,

View File

@@ -553,8 +553,9 @@ describe('ResourceProvider', () => {
];
const encoded = encode(JSON.stringify(seeded));
// The effect that re-hydrates reads the URL through lib/history, the same
// history the router runs on, so one navigation drives both.
// The effect that re-hydrates reads the URL through lib/router/navigation,
// which drives the same router the tree renders in, so one navigation
// drives both.
act(() => {
navigate(`/?resourceAttribute=${encoded}`);
});

View File

@@ -1,11 +1,12 @@
import { useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom-v5-compat';
import { useLocation, useNavigate } from 'react-router';
import { cloneDeep, isEqual } from 'lodash-es';
import { withBasePath } from 'utils/basePath';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
interface NavigateOptions {
replace?: boolean;
state?: any;
state?: unknown;
newTab?: boolean;
}
@@ -108,6 +109,12 @@ export const useSafeNavigate = (
// oxlint-disable-next-line signoz/no-raw-absolute-path
const base = window.location.origin;
const currentUrl = new URL(`${location.pathname}${location.search}`, base);
// nuqs writes shallowly, so the address bar can be ahead of the router.
// Navigating to it anyway makes nuqs drop its queued writes.
const publishedUrl = new URL(
`${location.pathname}?${getUnstableCurrentSearchParams().toString()}`,
base,
);
let targetUrl: URL;
@@ -131,7 +138,9 @@ export const useSafeNavigate = (
return;
}
const urlsAreSame = areUrlsEffectivelySame(currentUrl, targetUrl);
const urlsAreSame =
areUrlsEffectivelySame(currentUrl, targetUrl) ||
areUrlsEffectivelySame(publishedUrl, targetUrl);
const isDefaultParamsNavigation = isDefaultNavigation(currentUrl, targetUrl);
if (preventSameUrlNavigation && urlsAreSame) {
@@ -144,9 +153,9 @@ export const useSafeNavigate = (
};
if (typeof to === 'string') {
navigate(to, navigationOptions);
void navigate(to, navigationOptions);
} else {
navigate(
void navigate(
{
pathname: to.pathname || location.pathname,
search: to.search,

View File

@@ -2,10 +2,12 @@ import { ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient } from 'react-query';
import AppProviders from 'app/AppProviders';
import { AppRouterProvider } from 'app/AppRouterProvider';
import { createAppRouter } from 'app/createAppRouter';
import AppRoutes from 'AppRoutes';
import { AxiosError } from 'axios';
import { configureOverlayScrollbars } from 'lib/configureOverlayScrollbars';
import { NuqsAdapter } from 'nuqs/adapters/react';
import { NuqsAdapter } from 'nuqs/adapters/react-router/v7';
import { AppProvider } from 'providers/App/App';
import store from 'store';
import APIError from 'types/api/error';
@@ -55,8 +57,7 @@ const container = document.getElementById('root');
if (container) {
const root = createRoot(container);
root.render(
const router = createAppRouter(
<AppProviders
store={store}
queryClient={queryClient}
@@ -66,4 +67,6 @@ if (container) {
<AppRoutes />
</AppProviders>,
);
root.render(<AppRouterProvider router={router} />);
}

View File

@@ -85,6 +85,25 @@ describe('AuthZTooltip — single check', () => {
expect(screen.getByRole('button', { name: 'Action' })).toBeDisabled();
});
it('hides the caret and blocks text selection on a denied child', () => {
mockUseAuthZ.mockReturnValue(
authZResult({
permissions: { [createPerm]: { isGranted: false } },
}),
);
render(
<AuthZTooltip checks={[createPerm]}>
<TestButton />
</AuthZTooltip>,
);
expect(screen.getByRole('button', { name: 'Action' })).toHaveAttribute(
'style',
expect.stringContaining('caret-color: transparent; user-select: none'),
);
});
it('shows formatted permission message in tooltip when denied', async () => {
mockUseAuthZ.mockReturnValue(
authZResult({
@@ -119,6 +138,10 @@ describe('AuthZTooltip — single check', () => {
);
expect(screen.getByRole('button', { name: 'Action' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Action' })).toHaveAttribute(
'style',
expect.stringContaining('caret-color: transparent; user-select: none'),
);
});
});

View File

@@ -14,6 +14,8 @@ import { deniedTooltip } from 'lib/authz/components/deniedTooltip';
const DISABLED_STYLE: CSSProperties = {
pointerEvents: 'all',
cursor: 'not-allowed',
caretColor: 'transparent',
userSelect: 'none',
};
const noOp = (): void => {};

View File

@@ -13,6 +13,11 @@ export default {
type: 'metaresource',
allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
},
{
kind: 'factor-password',
type: 'metaresource',
allowedVerbs: ['create', 'list', 'read'],
},
{
kind: 'license',
type: 'metaresource',
@@ -93,16 +98,35 @@ export default {
type: 'telemetryresource',
allowedVerbs: ['read'],
},
{
kind: 'user',
type: 'user',
allowedVerbs: [
'attach',
'create',
'delete',
'detach',
'list',
'read',
'update',
],
},
],
relations: {
assignee: ['role'],
attach: ['metaresource', 'role', 'serviceaccount'],
create: ['metaresource', 'role', 'serviceaccount'],
delete: ['metaresource', 'role', 'serviceaccount'],
detach: ['metaresource', 'role', 'serviceaccount'],
list: ['metaresource', 'role', 'serviceaccount'],
read: ['metaresource', 'role', 'serviceaccount', 'telemetryresource'],
update: ['metaresource', 'role', 'serviceaccount'],
attach: ['metaresource', 'role', 'serviceaccount', 'user'],
create: ['metaresource', 'role', 'serviceaccount', 'user'],
delete: ['metaresource', 'role', 'serviceaccount', 'user'],
detach: ['metaresource', 'role', 'serviceaccount', 'user'],
list: ['metaresource', 'role', 'serviceaccount', 'user'],
read: [
'metaresource',
'role',
'serviceaccount',
'telemetryresource',
'user',
],
update: ['metaresource', 'role', 'serviceaccount', 'user'],
},
},
} as const;

View File

@@ -12,3 +12,9 @@ export const buildRoleUpdatePermission = (id: string): BrandedPermission =>
buildPermission('update', `role:${id}`);
export const buildRoleDeletePermission = (id: string): BrandedPermission =>
buildPermission('delete', `role:${id}`);
// Wildcard role permissions — used alongside SA-level checks for role assign/revoke guards.
// Backend requires both serviceaccount:attach AND role:attach to assign a role to a SA,
// and serviceaccount:detach AND role:detach to remove a role from a SA.
export const RoleAttachWildcardPermission = buildPermission('attach', 'role:*');
export const RoleDetachWildcardPermission = buildPermission('detach', 'role:*');

View File

@@ -17,12 +17,6 @@ export const buildSAAttachPermission = (id: string): BrandedPermission =>
export const buildSADetachPermission = (id: string): BrandedPermission =>
buildPermission('detach', `serviceaccount:${id}`);
// Wildcard role permissions — used alongside SA-level checks for role assign/revoke guards.
// Backend requires both serviceaccount:attach AND role:attach to assign a role to a SA,
// and serviceaccount:detach AND role:detach to remove a role from a SA.
export const RoleAttachWildcardPermission = buildPermission('attach', 'role:*');
export const RoleDetachWildcardPermission = buildPermission('detach', 'role:*');
// API key (factor-api-key) permissions.
// Listing keys: factor-api-key:list.
// Creating a key: factor-api-key:create (wildcard) + serviceaccount:attach.

View File

@@ -0,0 +1,29 @@
import { buildPermission } from '../utils';
import type { BrandedPermission } from '../types';
export const UserCreatePermission = buildPermission('create', 'user:*');
export const UserListPermission = buildPermission('list', 'user:*');
export const buildUserReadPermission = (id: string): BrandedPermission =>
buildPermission('read', `user:${id}`);
export const buildUserUpdatePermission = (id: string): BrandedPermission =>
buildPermission('update', `user:${id}`);
export const buildUserDeletePermission = (id: string): BrandedPermission =>
buildPermission('delete', `user:${id}`);
const buildUserAttachPermission = (id: string): BrandedPermission =>
buildPermission('attach', `user:${id}`);
export const buildUserDetachPermission = (id: string): BrandedPermission =>
buildPermission('detach', `user:${id}`);
const PasswordCreatePermission = buildPermission('create', 'factor-password:*');
export const PasswordListPermission = buildPermission(
'list',
'factor-password:*',
);
export const buildResetPasswordPermission = (
id: string,
): BrandedPermission[] => [
PasswordCreatePermission,
buildUserAttachPermission(id),
];

View File

@@ -1,15 +0,0 @@
import { createBrowserHistory } from 'history';
import { getBasePath } from 'utils/basePath';
const history = createBrowserHistory({ basename: getBasePath() });
let inAppPushCount = 0;
history.listen((_, action) => {
if (action === 'PUSH') {
inAppPushCount += 1;
}
});
export const hasInAppHistory = (): boolean => inAppPushCount > 0;
export default history;

View File

@@ -1,10 +1,8 @@
import { forwardRef } from 'react';
import type { AnchorHTMLAttributes, ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { Link } from 'react-router';
import type { To } from './types';
import { useAppLocation } from './useAppLocation';
import { withState } from './utils';
export interface AppLinkProps extends Omit<
AnchorHTMLAttributes<HTMLAnchorElement>,
@@ -18,15 +16,8 @@ export interface AppLinkProps extends Omit<
export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
function AppLink({ to, replace, state, children, ...rest }, ref) {
const location = useAppLocation();
return (
<Link
ref={ref}
to={withState(to, state, location)}
replace={replace}
{...rest}
>
<Link ref={ref} to={to} replace={replace} state={state} {...rest}>
{children}
</Link>
);

View File

@@ -0,0 +1,22 @@
import type { ReactNode } from 'react';
import { type DataRouter, RouterProvider } from 'react-router';
import { HostedTreeContext } from './HostedTreeContext';
interface HostRouterProps {
router: DataRouter;
children: ReactNode;
}
/**
* A data router's routes are fixed when it is created, so the tree reaches the
* route element through context instead, and a re-render with new children
* shows them.
*/
export function HostRouter({ router, children }: HostRouterProps): JSX.Element {
return (
<HostedTreeContext.Provider value={children}>
<RouterProvider router={router} useTransitions={false} />
</HostedTreeContext.Provider>
);
}

View File

@@ -0,0 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { createContext, type ReactNode } from 'react';
/** The tree `HostRouter` was last rendered with. */
export const HostedTreeContext = createContext<ReactNode>(null);

View File

@@ -0,0 +1,8 @@
// eslint-disable-next-line no-restricted-imports
import { useContext } from 'react';
import { HostedTreeContext } from './HostedTreeContext';
export function HostedTreeOutlet(): JSX.Element {
return <>{useContext(HostedTreeContext)}</>;
}

View File

@@ -1,12 +1,11 @@
import { Redirect as RouterRedirect } from 'react-router-dom';
import { Navigate } from 'react-router';
import type { To } from './types';
import { withState } from './utils';
export interface RedirectProps {
to: To;
/**
* Defaults to `true`, matching v5's `<Redirect>`. v6's `<Navigate>` pushes
* Defaults to `true`, matching v5's `<Redirect>`. v7's `<Navigate>` pushes
* unless told otherwise, which is invisible until someone presses Back.
*/
replace?: boolean;
@@ -18,7 +17,7 @@ export function Redirect({
replace = true,
state,
}: RedirectProps): JSX.Element {
return <RouterRedirect to={withState(to, state)} push={!replace} />;
return <Navigate to={to} replace={replace} state={state} />;
}
Redirect.defaultProps = {

View File

@@ -0,0 +1,10 @@
import { useRouteError } from 'react-router';
/**
* Rethrows past the router, so a render error reaches the next error boundary
* outside it (or fails a test) instead of rendering the router's default error
* page.
*/
export function RethrowRouteError(): never {
throw useRouteError();
}

View File

@@ -1,14 +1,14 @@
import { createRef } from 'react';
import type { ReactNode } from 'react';
import { useHistory } from 'react-router-dom';
import { cleanup, fireEvent, render, screen } from 'tests/test-utils';
import { AppLink, type AppLinkProps } from '../AppLink';
import { useAppLocation } from '../useAppLocation';
import { useAppNavigationType } from '../useAppNavigationType';
function LocationProbe(): JSX.Element {
const location = useAppLocation();
const history = useHistory();
const navigationType = useAppNavigationType();
return (
<div>
@@ -16,7 +16,7 @@ function LocationProbe(): JSX.Element {
<span data-testid="search">{location.search}</span>
<span data-testid="hash">{location.hash}</span>
<span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
<span data-testid="length">{history.length}</span>
<span data-testid="action">{navigationType}</span>
</div>
);
}
@@ -146,17 +146,23 @@ describe('AppLink', () => {
expect(screen.getByTestId('state')).toHaveTextContent('{"from":"test"}');
});
it('pushes by default', () => {
renderLink({ to: '/logs', 'data-testid': 'link' } as AppLinkProps);
fireEvent.click(screen.getByTestId('link'));
expect(screen.getByTestId('action')).toHaveTextContent('PUSH');
});
it('replaces the entry when replace is set', () => {
renderLink({
to: '/logs',
replace: true,
'data-testid': 'link',
} as AppLinkProps);
const before = screen.getByTestId('length').textContent;
fireEvent.click(screen.getByTestId('link'));
expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
expect(screen.getByTestId('length').textContent).toBe(before);
expect(screen.getByTestId('action')).toHaveTextContent('REPLACE');
});
it('forwards a ref to the anchor', () => {

View File

@@ -1,19 +1,19 @@
import { useHistory } from 'react-router-dom';
import { render, screen } from 'tests/test-utils';
import { Redirect, type RedirectProps } from '../Redirect';
import { useAppLocation } from '../useAppLocation';
import { useAppNavigationType } from '../useAppNavigationType';
function LocationProbe(): JSX.Element {
const location = useAppLocation();
const history = useHistory();
const navigationType = useAppNavigationType();
return (
<div>
<span data-testid="pathname">{location.pathname}</span>
<span data-testid="search">{location.search}</span>
<span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
<span data-testid="action">{history.action}</span>
<span data-testid="action">{navigationType}</span>
</div>
);
}

View File

@@ -3,8 +3,9 @@ import ROUTES from 'constants/routes';
import { buildRoutePath } from '../buildRoutePath';
/**
* These assertions pin every URL `buildRoutePath` produces, so a router
* upgrade cannot change one unnoticed.
* The encoding contract. v7's `generatePath` percent-encodes every param with
* `encodeURIComponent`, so `buildRoutePath` no longer encodes anything itself
* and these assertions are what pins the library's behaviour.
*/
describe('buildRoutePath', () => {
it('fills a single param', () => {
@@ -45,9 +46,15 @@ describe('buildRoutePath', () => {
expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: value })).toBe(expected);
});
it('leaves a colon alone', () => {
it('percent-encodes a colon', () => {
expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'a:b' })).toBe(
'/trace/a:b',
'/trace/a%3Ab',
);
});
it('encodes a raw value rather than passing an encoded one through', () => {
expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'a%2Fb' })).toBe(
'/trace/a%252Fb',
);
});
});

View File

@@ -1,10 +1,11 @@
import type { BlockedTransition } from '../types';
/**
* `lib/history` is a module-level singleton that reads the base path at import
* time, so every case loads it in isolation with a fresh DOM.
* `utils/basePath` reads the base path at import time, so every case loads the
* module, and the test router it drives, in isolation with a fresh DOM.
*/
type NavigationModule = typeof import('../navigation');
type TestRouterModule = typeof import('tests/router-utils');
let release: (() => void) | undefined;
function loadNavigation(baseHref?: string): NavigationModule {
if (baseHref !== undefined) {
@@ -14,16 +15,25 @@ function loadNavigation(baseHref?: string): NavigationModule {
}
let mod!: NavigationModule;
let testRouter!: TestRouterModule;
jest.isolateModules(() => {
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
mod = require('../navigation');
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
testRouter = require('tests/router-utils');
});
({ release } = testRouter.attachTestRouter());
return mod;
}
function settle(): Promise<void> {
function nextUpdate(
nav: NavigationModule,
): Promise<{ location: { pathname: string }; action: string }> {
return new Promise((resolve) => {
setTimeout(resolve, 60);
const unsubscribe = nav.subscribe((update) => {
unsubscribe();
resolve(update);
});
});
}
@@ -32,6 +42,8 @@ beforeEach(() => {
});
afterEach(() => {
release?.();
release = undefined;
for (const element of document.head.querySelectorAll('base')) {
element.remove();
}
@@ -44,6 +56,13 @@ describe('navigate', () => {
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('throws when no router is attached', () => {
const nav = loadNavigation();
release?.();
release = undefined;
expect(() => nav.navigate('/logs')).toThrow('no router is attached');
});
it('carries search and hash from a string target', () => {
const nav = loadNavigation();
nav.navigate('/logs?a=1#top');
@@ -112,23 +131,79 @@ describe('basename ownership', () => {
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('does not double-prefix a path that already carries the base path', () => {
it('round-trips getCurrentLocation through navigate', () => {
const nav = loadNavigation('/signoz/');
nav.navigate('/logs');
nav.navigate(nav.getCurrentLocation().pathname);
expect(window.location.pathname).toBe('/signoz/logs');
});
it('prefixes a path whose first segment equals the base path', () => {
const nav = loadNavigation('/logs/');
nav.navigate('/logs/logs-explorer');
expect(window.location.pathname).toBe('/logs/logs/logs-explorer');
expect(nav.getCurrentLocation().pathname).toBe('/logs/logs-explorer');
});
it('prefixes the pathname of an object target', () => {
const nav = loadNavigation('/signoz/');
nav.navigate({ pathname: '/logs', search: '?a=1' });
expect(window.location.pathname).toBe('/signoz/logs');
expect(window.location.search).toBe('?a=1');
});
});
describe('subscribe', () => {
it('reports a single update object, not two arguments', async () => {
const nav = loadNavigation();
const listener = jest.fn();
const unsubscribe = nav.subscribe(listener);
nav.navigate('/logs');
expect(listener).toHaveBeenCalledTimes(1);
expect(listener.mock.calls[0]).toHaveLength(1);
expect(listener.mock.calls[0][0]).toMatchObject({
location: { pathname: '/logs' },
action: 'PUSH',
});
unsubscribe();
});
it('reports REPLACE', () => {
const nav = loadNavigation();
const listener = jest.fn();
const unsubscribe = nav.subscribe(listener);
nav.navigate('/logs', { replace: true });
expect(listener.mock.calls[0][0].action).toBe('REPLACE');
unsubscribe();
});
it('stops reporting after unsubscribe', () => {
const nav = loadNavigation();
const listener = jest.fn();
nav.subscribe(listener)();
nav.navigate('/logs');
expect(listener).not.toHaveBeenCalled();
});
});
describe('back', () => {
it('restores the previous location', async () => {
it('reports POP and restores the previous location', async () => {
const nav = loadNavigation();
nav.navigate('/logs');
nav.navigate('/traces');
const popped = nextUpdate(nav);
nav.back();
await settle();
const update = await popped;
expect(update.action).toBe('POP');
expect(update.location.pathname).toBe('/logs');
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
});
@@ -151,261 +226,3 @@ describe('hasInAppHistory', () => {
expect(nav.hasInAppHistory()).toBe(true);
});
});
describe('blockNavigation', () => {
it('hands the blocker a transition and cancels the navigation', () => {
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/logs');
expect(seen).toHaveLength(1);
expect(seen[0].action).toBe('PUSH');
expect(seen[0].location.pathname).toBe('/logs');
expect(typeof seen[0].retry).toBe('function');
expect(nav.getCurrentLocation().pathname).toBe('/');
unblock();
});
it('completes the navigation when retry runs after unblocking', () => {
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/logs');
unblock();
seen[0].retry();
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('blocks again when retry runs while still blocked, as history@5 does', () => {
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/logs');
seen[0].retry();
expect(seen).toHaveLength(2);
expect(nav.getCurrentLocation().pathname).toBe('/');
unblock();
});
it('lets a POP through when retry runs inside the blocker', async () => {
const nav = loadNavigation();
nav.navigate('/logs');
nav.navigate('/traces');
const seen: BlockedTransition[] = [];
let unblock = (): void => {};
unblock = nav.blockNavigation((tx) => {
seen.push(tx);
unblock();
tx.retry();
});
nav.back();
await settle();
expect(seen).toHaveLength(1);
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('replays a blocked Forward by one entry', async () => {
const nav = loadNavigation();
nav.navigate('/logs');
nav.navigate('/traces');
nav.back();
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.forward();
await settle();
unblock();
seen[0].retry();
await settle();
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/traces');
});
it('replays a blocked multi-entry jump by its full distance', async () => {
const nav = loadNavigation();
nav.navigate('/a');
nav.navigate('/b');
nav.navigate('/c');
window.history.go(-2);
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.go(2);
await settle();
unblock();
seen[0].retry();
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/c');
});
it('replays a blocked Back to an entry from before a reload', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
earlier.navigate('/c');
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.back();
await settle();
unblock();
seen[0].retry();
await settle();
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/b');
expect(window.location.pathname).toBe('/b');
});
it('replays a blocked Forward after leaving through an entry from before a reload', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
const nav = loadNavigation();
nav.navigate('/c');
window.history.go(-2);
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/a');
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.forward();
await settle();
unblock();
seen[0].retry();
await settle();
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/b');
expect(window.location.pathname).toBe('/b');
});
it('replays a blocked Forward that skips from an entry from before a reload past the first known one', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
const nav = loadNavigation();
nav.navigate('/c');
window.history.go(-2);
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.go(2);
await settle();
unblock();
seen[0].retry();
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/c');
expect(window.location.pathname).toBe('/c');
window.history.back();
await settle();
expect(window.location.pathname).toBe('/b');
});
it('replays a blocked Back that skips from a known entry to one from before a reload', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
const nav = loadNavigation();
nav.navigate('/c');
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.go(-2);
await settle();
unblock();
seen[0].retry();
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/a');
expect(window.location.pathname).toBe('/a');
window.history.forward();
await settle();
expect(window.location.pathname).toBe('/b');
});
it('catches the router up when history@4 does not revert a blocked POP', async () => {
const nav = loadNavigation();
nav.navigate('/p');
// nuqs pushes like this, so both entries carry the same history@4 key.
window.history.pushState(window.history.state, '', '/p?x=1');
window.history.back();
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.forward();
await settle();
unblock();
seen[0].retry();
expect(nav.getCurrentLocation().search).toBe('?x=1');
expect(window.location.search).toBe('?x=1');
});
it('keeps the blocker armed when retry runs inside it', () => {
const nav = loadNavigation();
let allowNext = true;
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => {
seen.push(tx);
if (allowNext) {
allowNext = false;
tx.retry();
}
});
nav.navigate('/logs');
nav.navigate('/traces');
expect(nav.getCurrentLocation().pathname).toBe('/logs');
expect(seen).toHaveLength(2);
unblock();
});
it('preserves the replace action through retry', () => {
const nav = loadNavigation();
nav.navigate('/logs');
const before = window.history.length;
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/traces', { replace: true });
unblock();
seen[0].retry();
expect(seen[0].action).toBe('REPLACE');
expect(nav.getCurrentLocation().pathname).toBe('/traces');
expect(window.history).toHaveLength(before);
});
it('stops blocking after unblock', () => {
const nav = loadNavigation();
const listener = jest.fn();
nav.blockNavigation(listener)();
nav.navigate('/logs');
expect(listener).not.toHaveBeenCalled();
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
});

View File

@@ -1,6 +1,6 @@
import type { ReactNode } from 'react';
import { TestRouter } from 'tests/router';
import { renderHook } from 'tests/test-utils';
import { act, renderHook } from 'tests/test-utils';
import { navigate } from '../navigation';
import { useAppLocation } from '../useAppLocation';
@@ -25,10 +25,10 @@ describe('useAppLocation', () => {
});
it('returns the entry state', () => {
navigate('/logs', { replace: true, state: { from: 'test' } });
const { result } = renderHook(() => useAppLocation<{ from: string }>(), {
wrapper: TestRouter,
});
act(() => navigate('/logs', { replace: true, state: { from: 'test' } }));
expect(result.current.state.from).toBe('test');
});

View File

@@ -1,9 +1,9 @@
import { useHistory } from 'react-router-dom';
import { fireEvent, render, screen } from 'tests/test-utils';
import type { NavigateOptions, To } from '../types';
import { useAppLocation } from '../useAppLocation';
import { useAppNavigate } from '../useAppNavigate';
import { useAppNavigationType } from '../useAppNavigationType';
function Probe({
to,
@@ -14,7 +14,7 @@ function Probe({
}): JSX.Element {
const navigate = useAppNavigate();
const location = useAppLocation();
const history = useHistory();
const navigationType = useAppNavigationType();
return (
<div>
@@ -27,7 +27,7 @@ function Probe({
<span data-testid="pathname">{location.pathname}</span>
<span data-testid="search">{location.search}</span>
<span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
<span data-testid="length">{history.length}</span>
<span data-testid="action">{navigationType}</span>
</div>
);
}
@@ -62,20 +62,16 @@ describe('useAppNavigate', () => {
it('adds a history entry by default', () => {
renderProbe('/logs');
const before = screen.getByTestId('length').textContent;
fireEvent.click(screen.getByTestId('navigate'));
expect(Number(screen.getByTestId('length').textContent)).toBe(
Number(before) + 1,
);
expect(screen.getByTestId('action')).toHaveTextContent('PUSH');
});
it('does not add a history entry when replacing', () => {
renderProbe('/logs', { replace: true });
const before = screen.getByTestId('length').textContent;
fireEvent.click(screen.getByTestId('navigate'));
expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
expect(screen.getByTestId('length').textContent).toBe(before);
expect(screen.getByTestId('action')).toHaveTextContent('REPLACE');
});
});

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