Compare commits

..

7 Commits

Author SHA1 Message Date
Naman Verma
8101a79371 Merge branch 'main' into nv/exec-stats 2026-11-16 10:43:03 +05:30
Naman Verma
62d477e920 Merge branch 'main' into nv/exec-stats 2026-11-09 12:20:27 +05:30
Naman Verma
fe45b9dcae Merge branch 'main' into nv/exec-stats 2026-11-06 00:51:46 +05:30
Naman Verma
63ee60a40c fix(querier): stop cache refreshes from inflating exec stats 2026-11-06 00:51:03 +05:30
Naman Verma
29a393e47e Merge branch 'main' into nv/exec-stats 2026-11-05 10:51:11 +05:30
Naman Verma
c58f76f998 Merge branch 'main' into nv/exec-stats 2026-11-03 11:34:10 +05:30
Naman Verma
e39ad9e221 test: check how exec stats fail 2026-11-02 22:24:22 +05:30
579 changed files with 2574 additions and 21606 deletions

View File

@@ -2,50 +2,44 @@ name: e2eci
on:
pull_request:
types:
- opened
- synchronize
- reopened
- labeled
merge_group:
types:
- checks_requested
# Labels other than safe-to-e2e get a group of their own, so they never cancel a running e2e.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && format('-{0}', github.run_id) || '' }}
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
changes:
if: github.event.action != 'labeled' || github.event.label.name == 'safe-to-e2e'
runs-on: ubuntu-latest
outputs:
e2e: ${{ steps.changes.outputs.e2e }}
steps:
- name: merge-queue-pass
if: github.event_name == 'merge_group'
run: echo "::notice::Merge queue run. E2E already gated the PR, so the required e2e check auto-passes."
- name: changes
id: changes
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
FORCE: ${{ github.event_name == 'merge_group' || contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
FORCE: ${{ contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
run: |
if [ "$FORCE" = "true" ]; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
exit 0
fi
CHANGED_FILES=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename | select((startswith("tests/integration/") or startswith("frontend/src/api/generated/")) | not)')
PATTERN='^(frontend/|tests/|\.github/workflows/e2eci\.yaml$|cmd/enterprise/Dockerfile\.with-web\.integration$)'
if printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
if [ "$FORCE" = "true" ]; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
elif printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
else
echo "e2e=false" >> "$GITHUB_OUTPUT"
fi
fmtlint:
needs: changes
if: github.event_name != 'merge_group' && needs.changes.outputs.e2e == 'true'
if: needs.changes.outputs.e2e == 'true'
runs-on: ubuntu-latest
steps:
- name: checkout
@@ -186,8 +180,6 @@ jobs:
retention-days: 5
# Required status check. Fails when e2e was needed but did not pass.
e2e:
# Runs for other labels must not report as e2e, or their pass would hide the real result.
name: ${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && 'ignored-label' || 'e2e' }}
if: always()
needs: [changes, fmtlint, test]
runs-on: ubuntu-latest

View File

@@ -40,6 +40,7 @@ jobs:
suite:
- alertmanager
- alertmanagerrotation
- auditquerier
- basepath
- callbackauthn
- cloudintegrations
@@ -57,7 +58,6 @@ jobs:
- querierscalar
- queriercommon
- querierai
- querieraudit
- rawexportdata
- promqlconformance
- promapiconformance

View File

@@ -132,26 +132,3 @@ jobs:
run: |
cd frontend && pnpm generate:config:web-settings
git diff --compact-summary --exit-code || (echo; echo "Unexpected difference in generated web settings types. Run pnpm generate:config:web-settings in frontend/ locally and commit."; exit 1)
geo-outlines:
if: |
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
runs-on: ubuntu-latest
steps:
- name: self-checkout
uses: actions/checkout@v4
- name: node-install
uses: actions/setup-node@v5
with:
node-version: "22"
- name: install-pnpm
uses: pnpm/action-setup@v6
with:
version: 10
- name: install-frontend
run: cd frontend && pnpm install
- name: generate-geo-outlines
run: |
cd frontend && pnpm build:geo-outlines
git status --short
test -z "$(git status --porcelain)" || (echo; echo "Unexpected difference in geo map outlines. Run pnpm build:geo-outlines in frontend/ locally and commit."; exit 1)

View File

@@ -30,7 +30,7 @@ export default {
],
relations: {
{{- range .Relations }}
{{ .FormattedTypes }}
{{ .Verb }}: [{{ range $i, $t := .Types }}{{ if $i }}, {{ end }}'{{ $t }}'{{ end }}],
{{- end }}
},
},
@@ -38,8 +38,8 @@ export default {
`))
type permissionsTypeRelation struct {
Verb string
FormattedTypes string
Verb string
Types []string
}
type permissionsTypeResource struct {
@@ -77,29 +77,6 @@ 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",
@@ -129,8 +106,6 @@ 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{}
@@ -179,8 +154,8 @@ func runGenerateAuthz(_ context.Context) error {
types = append(types, t.StringValue())
}
relations = append(relations, permissionsTypeRelation{
Verb: verb.StringValue(),
FormattedTypes: formatRelationTypes(verb.StringValue(), types, 3, 80),
Verb: verb.StringValue(),
Types: types,
})
}

View File

@@ -4318,11 +4318,6 @@ components:
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
type: object
DashboardtypesBubbleRadius:
maximum: 64
minimum: 1
nullable: true
type: integer
DashboardtypesBuilderQuerySpec:
discriminator:
mapping:
@@ -4555,231 +4550,6 @@ components:
minimum: 0
nullable: true
type: number
DashboardtypesGeoMapBubbles:
properties:
maxRadius:
allOf:
- $ref: '#/components/schemas/DashboardtypesBubbleRadius'
description: Radius of the largest circle, in CSS pixels from 1 to 64. Null
means 8 on the points layer, 28 otherwise.
minRadius:
allOf:
- $ref: '#/components/schemas/DashboardtypesBubbleRadius'
description: Radius of the smallest circle, in CSS pixels from 1 to 64.
Null means 2 on the points layer, 3 otherwise.
type: object
DashboardtypesGeoMapChartAppearance:
properties:
bubbles:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapBubbles'
description: The circle radius range of the bubbles and points layers.
colors:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapColors'
description: The color scale applied to the colorBy values.
labels:
description: Shows country and state names once each fits inside its shape.
Null shows them.
nullable: true
type: boolean
type: object
DashboardtypesGeoMapColors:
properties:
fill:
description: The hex color varied in opacity mode. Empty uses the default
fill.
type: string
max:
description: The value mapped to the highest color. Null uses the highest
value in the data.
nullable: true
type: number
min:
description: The value mapped to the lowest color. Null uses the lowest
value in the data. Must not exceed max.
nullable: true
type: number
mode:
allOf:
- $ref: '#/components/schemas/DashboardtypesHeatmapColorMode'
description: 'How values are colored: palette (default) picks a hue from
palette, opacity varies the opacity of fill.'
palette:
allOf:
- $ref: '#/components/schemas/DashboardtypesHeatmapPalette'
description: The named color ramp used in palette mode, such as lava (default),
ice or ember.
scale:
allOf:
- $ref: '#/components/schemas/DashboardtypesHeatmapColorScale'
description: 'How values map onto the color range: log (default), sqrt or
linear.'
steps:
description: The number of distinct color steps, 2 to 128. 0 uses the chart
default.
type: integer
type: object
DashboardtypesGeoMapCountryFormat:
enum:
- auto
- alpha2
- alpha3
- name
type: string
DashboardtypesGeoMapLayer:
enum:
- regions
- bubbles
- points
type: string
DashboardtypesGeoMapLocation:
properties:
country:
description: Group-by key holding the country, for the country and subdivision
modes. Empty detects it by name, such as geo.country.iso_code.
type: string
countryFormat:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapCountryFormat'
description: 'How country values are written: auto (default) detects it,
alpha2, alpha3 or name.'
lat:
description: Group-by key holding the latitude, for the coordinates mode.
Empty detects it by name.
type: string
lon:
description: Group-by key holding the longitude, for the coordinates mode.
Empty detects it by name.
type: string
mode:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapLocationMode'
description: 'How rows are placed: auto (default) detects it from the group-by
keys, country, subdivision or coordinates.'
region:
description: Group-by key holding the ISO 3166-2 region code (e.g. geo.region.iso_code),
for the subdivision mode. Empty detects it by name.
type: string
required:
- mode
- countryFormat
type: object
DashboardtypesGeoMapLocationMode:
enum:
- auto
- country
- subdivision
- coordinates
type: string
DashboardtypesGeoMapPanelSpec:
properties:
chartAppearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapChartAppearance'
description: Color scale, bubble size and labels.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesTableFormatting'
description: Per-column units and decimal precision.
legend:
allOf:
- $ref: '#/components/schemas/DashboardtypesLegend'
description: Legend placement.
location:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapLocation'
description: The group-by columns that place each row on the map.
map:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapSettings'
description: Layer, view, projection and the value columns drawn.
thresholds:
description: Rules that recolor a shape, bubble or point when its value
compares to a threshold as specified.
items:
$ref: '#/components/schemas/DashboardtypesGeoMapThreshold'
nullable: true
type: array
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
description: The time range the values are computed over.
type: object
DashboardtypesGeoMapProjection:
enum:
- mercator
- equal_earth
- natural_earth
type: string
DashboardtypesGeoMapSettings:
properties:
colorBy:
description: Value column key, as in a Table panel, that sets the color.
Empty uses the first value column.
type: string
layer:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapLayer'
description: 'What is drawn: regions (default) fills each shape, bubbles
draws a circle per region, points a circle per coordinate.'
projection:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapProjection'
description: 'The map projection: mercator (default), equal_earth or natural_earth.'
sizeBy:
description: Value column key, as in a Table panel, that sets the bubble
or point size. Empty uses colorBy.
type: string
view:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapView'
description: 'The area shown: world (default), fit to the data, a continent,
or country with viewCountry.'
viewCountry:
description: Uppercase ISO 3166-1 alpha-2 code of the country the country
view shows.
type: string
required:
- layer
- view
- projection
type: object
DashboardtypesGeoMapThreshold:
properties:
color:
description: 'The CSS color of the shape, bubble or point while the threshold
is active, for example #F1575F; CSS named colors such as red also work.'
type: string
operator:
allOf:
- $ref: '#/components/schemas/DashboardtypesComparisonOperator'
description: 'The comparison that activates the threshold: above (default),
below, above_or_equal, below_or_equal, equal or not_equal.'
unit:
description: The unit id of value, such as ms or percent. Empty means the
colorBy column's unit.
type: string
value:
description: The value compared against, in unit.
format: double
type: number
required:
- value
- color
type: object
DashboardtypesGeoMapView:
enum:
- world
- fit
- africa
- asia
- europe
- north_america
- south_america
- oceania
- country
type: string
DashboardtypesGettableDashboardV2:
properties:
createdAt:
@@ -5517,7 +5287,6 @@ components:
mapping:
signoz/AreaChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec'
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
signoz/GeoMapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
signoz/HeatmapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
signoz/ListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
@@ -5540,7 +5309,6 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5555,7 +5323,6 @@ components:
- signoz/TextPanel
- signoz/HeatmapPanel
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5587,21 +5354,6 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/GeoMapPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec:
properties:
kind:
@@ -11992,9 +11744,8 @@ 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}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -12111,9 +11862,8 @@ 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}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:

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,7 +267,9 @@ 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()
lb.SetRuleLabels(r.Labels().Map(), expand)
for name, value := range r.Labels().Map() {
lb.Set(name, expand(value))
}
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

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

View File

@@ -56,10 +56,10 @@ const config: Config.InitialOptions = {
transformIgnorePatterns: [
// @chenglou/pretext is ESM-only; @signozhq/ui pulls it in via text-ellipsis.
// Pattern 1: allow .pnpm virtual store through (handled by pattern 2), plus root-level ESM packages.
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|d3-geo|d3-array|internmap|ol|rbush|quickselect|earcut|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
// Pattern 2: pnpm virtual store — ignore everything except ESM-only packages.
// pnpm encodes scoped packages as @scope+name@version, so match on scope prefix.
'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|d3-geo|d3-array|internmap|ol|rbush|quickselect|earcut|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testPathIgnorePatterns: ['/node_modules/', '/public/'],

View File

@@ -30,8 +30,7 @@
"test": "jest",
"test:changedsince": "jest --changedSince=main --coverage --silent",
"generate:api": "orval --config ./orval.config.ts && sh scripts/post-types-generation.sh",
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'",
"build:geo-outlines": "node scripts/geo-outlines/build.mjs"
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'"
},
"engines": {
"node": ">=22.0.0",
@@ -79,7 +78,6 @@
"classnames": "2.3.2",
"color": "^4.2.1",
"crypto-js": "4.2.0",
"d3-geo": "3.1.1",
"d3-hierarchy": "3.1.2",
"dayjs": "^1.10.7",
"dompurify": "3.4.17",
@@ -98,7 +96,6 @@
"monaco-editor": "0.55.1",
"motion": "12.4.13",
"nuqs": "2.8.8",
"ol": "10.11.0",
"overlayscrollbars": "^2.16.0",
"overlayscrollbars-react": "^0.5.6",
"papaparse": "5.4.1",
@@ -133,7 +130,6 @@
"rrule": "2.8.1",
"styled-components": "^5.3.11",
"timestamp-nano": "^1.0.0",
"topojson-client": "3.1.0",
"translation-resilience": "^0.2.0",
"typescript": "5.9.3",
"uplot": "1.6.31",
@@ -174,10 +170,8 @@
"@testing-library/user-event": "14.4.3",
"@types/color": "^3.0.3",
"@types/crypto-js": "4.2.2",
"@types/d3-geo": "3.1.1",
"@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",
@@ -194,8 +188,6 @@
"@types/redux-mock-store": "1.0.4",
"@types/styled-components": "^5.1.4",
"@types/testing-library__jest-dom": "^5.14.5",
"@types/topojson-client": "3.1.5",
"@types/topojson-specification": "1.0.5",
"@typescript/native-preview": "7.0.0-dev.20260430.1",
"eslint-plugin-sonarjs": "4.0.2",
"husky": "^9.1.7",
@@ -217,8 +209,6 @@
"storybook": "10.6.3",
"stylelint": "17.15.0",
"svgo": "4.1.0",
"topojson-server": "3.0.1",
"topojson-simplify": "3.0.3",
"ts-jest": "29.4.15",
"typescript-plugin-css-modules": "5.3.0",
"use-sync-external-store": "1.6.0",

201
frontend/pnpm-lock.yaml generated
View File

@@ -148,9 +148,6 @@ importers:
crypto-js:
specifier: 4.2.0
version: 4.2.0
d3-geo:
specifier: 3.1.1
version: 3.1.1
d3-hierarchy:
specifier: 3.1.2
version: 3.1.2
@@ -205,9 +202,6 @@ importers:
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)
ol:
specifier: 10.11.0
version: 10.11.0
overlayscrollbars:
specifier: ^2.16.0
version: 2.16.0
@@ -310,9 +304,6 @@ importers:
timestamp-nano:
specifier: ^1.0.0
version: 1.0.1
topojson-client:
specifier: 3.1.0
version: 3.1.0
translation-resilience:
specifier: ^0.2.0
version: 0.2.0
@@ -392,18 +383,12 @@ importers:
'@types/crypto-js':
specifier: 4.2.2
version: 4.2.2
'@types/d3-geo':
specifier: 3.1.1
version: 3.1.1
'@types/d3-hierarchy':
specifier: 1.1.11
version: 1.1.11
'@types/event-source-polyfill':
specifier: ^1.0.0
version: 1.0.1
'@types/geojson':
specifier: 7946.0.16
version: 7946.0.16
'@types/history':
specifier: 4.7.11
version: 4.7.11
@@ -452,12 +437,6 @@ importers:
'@types/testing-library__jest-dom':
specifier: ^5.14.5
version: 5.14.5
'@types/topojson-client':
specifier: 3.1.5
version: 3.1.5
'@types/topojson-specification':
specifier: 1.0.5
version: 1.0.5
'@typescript/native-preview':
specifier: 7.0.0-dev.20260430.1
version: 7.0.0-dev.20260430.1
@@ -521,12 +500,6 @@ importers:
svgo:
specifier: 4.1.0
version: 4.1.0
topojson-server:
specifier: 3.0.1
version: 3.0.1
topojson-simplify:
specifier: 3.0.3
version: 3.0.3
ts-jest:
specifier: 29.4.15
version: 29.4.15(@babel/core@7.29.7)(@jest/transform@30.4.1)(@jest/types@30.2.0)(babel-jest@29.6.4(@babel/core@7.29.7))(esbuild@0.28.1)(jest-util@30.4.1)(jest@30.2.0(@types/node@22.20.5)(babel-plugin-macros@3.1.0)(ts-node@10.9.1(@swc/core@1.16.2)(@types/node@22.20.5)(typescript@5.9.3)))(typescript@5.9.3)
@@ -2925,9 +2898,6 @@ packages:
'@petamoriken/float16@3.8.0':
resolution: {integrity: sha512-AhVAm6SQ+zgxIiOzwVdUcDmKlu/qU39FiYD2UD6kQQaVenrn0dGZewIghWAENGQsvC+1avLCuT+T2/3Gsp/W3w==}
'@petamoriken/float16@3.9.3':
resolution: {integrity: sha512-8awtpHXCx/bNpFt4mt2xdkgtgVvKqty8VbjHI/WWWQuEw+KLzFot3f4+LkQY9YmOtq7A5GdOnqoIC8Pdygjk2g==}
'@pkgjs/parseargs@0.11.0':
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -3981,9 +3951,6 @@ packages:
'@types/d3-geo@3.1.0':
resolution: {integrity: sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==}
'@types/d3-geo@3.1.1':
resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==}
'@types/d3-hierarchy@1.1.11':
resolution: {integrity: sha512-lnQiU7jV+Gyk9oQYk0GGYccuexmQPTp08E0+4BidgFdiJivjEvf+esPSdZqCZ2C7UwTWejWpqetVaU8A+eX3FA==}
@@ -4029,8 +3996,8 @@ packages:
'@types/file-saver@2.0.5':
resolution: {integrity: sha512-zv9kNf3keYegP5oThGLaPk8E081DFDuwfqjtiTzm6PoxChdJ1raSuADf2YGCVIyrSynLrgc8JWv296s7Q7pQSQ==}
'@types/geojson@7946.0.16':
resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
'@types/geojson@7946.0.14':
resolution: {integrity: sha512-WCfD5Ht3ZesJUsONdhvm84dmzWOiOzOAqOncN0++w0lBw1o8OuDNJF2McvvCef/yBqb/HYRahp1BYtODFQ8bRg==}
'@types/graceful-fs@4.1.6':
resolution: {integrity: sha512-Sig0SNORX9fdW+bQuTEovKj3uHcUL6LQKbCrrqb1X7J6/ReAbhCXRAhc+SMejhLELFj2QcyuxmUooZ4bt5ReSw==}
@@ -4110,9 +4077,6 @@ packages:
'@types/prop-types@15.7.5':
resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}
'@types/rbush@4.0.0':
resolution: {integrity: sha512-+N+2H39P8X+Hy1I5mC6awlTX54k3FhiUmvt7HWzGJZvF+syUAAxP/stwppS8JE84YHqFgRMv6fCy31202CMFxQ==}
'@types/react-addons-update@0.14.21':
resolution: {integrity: sha512-HOxr0Hd8C1L4uw8DHyv2etqMVIj78oLEpe567/HgjoE+1Lc+PUsTGXTrkr1BDvFqsu5r49mSlgI5evwrk9eutA==}
@@ -4164,12 +4128,6 @@ packages:
'@types/testing-library__jest-dom@5.14.5':
resolution: {integrity: sha512-SBwbxYoyPIvxHbeHxTZX2Pe/74F/tX2/D3mMvzabdeJ25bBojfW0TyB8BHrbq/9zaaKICJZjLP+8r6AeZMFCuQ==}
'@types/topojson-client@3.1.5':
resolution: {integrity: sha512-C79rySTyPxnQNNguTZNI1Ct4D7IXgvyAs3p9HPecnl6mNrJ5+UhvGNYcZfpROYV2lMHI48kJPxwR+F9C6c7nmw==}
'@types/topojson-specification@1.0.5':
resolution: {integrity: sha512-C7KvcQh+C2nr6Y2Ub4YfgvWvWCgP2nOQMtfhlnwsRL4pYmmwzBS7HclGiS87eQfDOU/DLQpX6GEscviaz4yLIQ==}
'@types/tough-cookie@4.0.5':
resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}
@@ -4455,9 +4413,6 @@ packages:
'@xobotyi/scrollbar-width@1.9.5':
resolution: {integrity: sha512-N8tkAACJx2ww8vFMneJmaAgmjAG1tnVBZJRLRcx061tmsLRZHSEZSLuGWnwPtunsSLvSqXQ2wfp7Mgqg1I+2dQ==}
'@zarrita/storage@0.2.0':
resolution: {integrity: sha512-855ZXqtnds7spnT8vNvD+MXa3QExP1m2GqShe8yt7uZXHnQLgJHgkpVwFjE1B0KDDRO0ki09hmk6OboTaIfPsQ==}
'@zxing/text-encoding@0.9.0':
resolution: {integrity: sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==}
@@ -5257,10 +5212,6 @@ packages:
resolution: {integrity: sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==}
engines: {node: '>=12'}
d3-geo@3.1.1:
resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==}
engines: {node: '>=12'}
d3-hierarchy@1.1.9:
resolution: {integrity: sha512-j8tPxlqh1srJHAtxfvOUwKNYJkQuBFdM1+JAUfq6xqH5eAqf93L7oG1NVqDa4CpFZNvnNKtCYEUC8KY9yEn9lQ==}
@@ -5536,9 +5487,6 @@ packages:
earcut@2.2.4:
resolution: {integrity: sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==}
earcut@3.2.4:
resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==}
eastasianwidth@0.2.0:
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
@@ -5806,9 +5754,6 @@ packages:
fflate@0.4.9:
resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==}
fflate@0.8.3:
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
figures@3.2.0:
resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==}
engines: {node: '>=8'}
@@ -5986,10 +5931,6 @@ packages:
resolution: {integrity: sha512-PT6uoF5a1+kbC3tHmZSUsLHBp2QJlHasxxxxPW47QIY1VBKpFB+FcDvX+MxER6UzgLQZ0xDzJ9s48B9JbOCTqA==}
engines: {node: '>=10.19'}
geotiff@3.1.0-beta.0:
resolution: {integrity: sha512-wbVwOaQYuN+ywly5NoMXn37nHslwkQg5EFHqMeUTtjDACrSag0EEVlFsc+2DK3Pzmmp6XzJW2RTZOamPsBM6ng==}
engines: {node: '>=10.19'}
get-caller-file@2.0.5:
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
engines: {node: 6.* || 8.* || >= 10.*}
@@ -7562,9 +7503,6 @@ packages:
nth-check@2.1.1:
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
numcodecs@0.3.2:
resolution: {integrity: sha512-6YSPnmZgg0P87jnNhi3s+FVLOcIn3y+1CTIgUulA3IdASzK9fJM87sUFkpyA+be9GibGRaST2wCgkD+6U+fWKw==}
nuqs@2.8.8:
resolution: {integrity: sha512-LF5sw9nWpHyPWzMMu9oho3r9C5DvkpmBIg4LQN78sexIzGaeRx8DWr0uy3YiFx5i2QGZN1Qqcb+OAtEVRa2bnA==}
peerDependencies:
@@ -7641,9 +7579,6 @@ packages:
ol-mapbox-style@10.7.0:
resolution: {integrity: sha512-S/UdYBuOjrotcR95Iq9AejGYbifKeZE85D9VtH11ryJLQPTZXZSW1J5bIXcr4AlAH6tyjPPHTK34AdkwB32Myw==}
ol@10.11.0:
resolution: {integrity: sha512-OJ+lrx7kx/1O7Xx18Ff9QkVnwZIEL0OuhJQSy2sYgzzDvyZ2qHvuZEGAajbSstUyBwaS1OtQ4RWnY84tRMDdqg==}
ol@7.4.0:
resolution: {integrity: sha512-bgBbiah694HhC0jt8ptEFNRXwgO8d6xWH3G97PCg4bmn9Li5nLLbi59oSrvqUI6VPVwonPQF1YcqJymxxyMC6A==}
@@ -7868,10 +7803,6 @@ packages:
resolution: {integrity: sha512-ClrV7pNOn7rtmoQVF4TS1vyU0WhYRnP92fzbfF75jAIwpnzdJXf8iTd4CMEqO4yUenH6NDqLiwjqlh6QgZzgLQ==}
hasBin: true
pbf@5.1.2:
resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==}
hasBin: true
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -8077,15 +8008,9 @@ packages:
quickselect@2.0.0:
resolution: {integrity: sha512-RKJ22hX8mHe3Y6wH/N3wCM6BWtjaxIyyUIkpHOvfFnxdI4yD4tBXEBKSbriGujF6jnSVkJrffuo6vxACiSSxIw==}
quickselect@3.0.0:
resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==}
rbush@3.0.1:
resolution: {integrity: sha512-XRaVO0YecOpEuIvbhbpTrZgoiI6xBlz6hnlr6EHhd+0x9ase6EmeN+hdwwUaJvLcsFFQ8iWVF1GAK1yB0BWi0w==}
rbush@4.0.1:
resolution: {integrity: sha512-IP0UpfeWQujYC8Jg162rMNc01Rf0gWMMAb2Uxus/Q0qOFw4lCcq6ZnQEZwUoJqWyUGJ9th7JjwI4yIWo+uvoAQ==}
rc-cascader@3.20.0:
resolution: {integrity: sha512-lkT9EEwOcYdjZ/jvhLoXGzprK1sijT3/Tp4BLxQQcHDZkkOzzwYQC9HgmKoJz0K7CukMfgvO9KqHeBdgE+pELw==}
peerDependencies:
@@ -8646,9 +8571,6 @@ packages:
resolution: {integrity: sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==}
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
reference-spec-reader@0.2.0:
resolution: {integrity: sha512-q0mfCi5yZSSHXpCyxjgQeaORq3tvDsxDyzaadA/5+AbAUwRyRuuTh0aRQuE/vAOt/qzzxidJ5iDeu1cLHaNBlQ==}
refractor@3.6.0:
resolution: {integrity: sha512-MY9W41IOWxxk31o+YvFCNyNzdkc9M20NoZK5vq6jkv4I/uh2zkWcfudj0Q1fovjUQJrNewS9NMzeTtqPf+n5EA==}
@@ -9336,18 +9258,6 @@ packages:
toggle-selection@1.0.6:
resolution: {integrity: sha512-BiZS+C1OS8g/q2RRbJmy59xpyghNBqrr6k5L/uKBGRsTfxmu3ffiRnd8mlGPUVayg8pvfi5urfnu8TU7DVOkLQ==}
topojson-client@3.1.0:
resolution: {integrity: sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==}
hasBin: true
topojson-server@3.0.1:
resolution: {integrity: sha512-/VS9j/ffKr2XAOjlZ9CgyyeLmgJ9dMwq6Y0YEON8O7p/tGGk+dCWnrE03zEdu7i4L7YsFZLEPZPzCvcB7lEEXw==}
hasBin: true
topojson-simplify@3.0.3:
resolution: {integrity: sha512-V+pBjLVzSQ3+hSOxBiV01OVXgFiCmMO8ia3huxKEyIMTC1ApQHBcdXdOqcQ6U2JJJD31TZduwY6KyF15R8sUgg==}
hasBin: true
tough-cookie@4.1.4:
resolution: {integrity: sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==}
engines: {node: '>=6'}
@@ -9597,10 +9507,6 @@ packages:
unrs-resolver@1.11.1:
resolution: {integrity: sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==}
unzipit@2.0.0:
resolution: {integrity: sha512-DVeVIWUZCAQPNzm5sB0hpsG1GygTTdBnzNtYYEpInkttx5evkyqRgZi6rTczoySqp8hO5jHVKzrH0f23X8FZLg==}
engines: {node: '>=18'}
update-browserslist-db@1.3.3:
resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==}
hasBin: true
@@ -9919,9 +9825,6 @@ packages:
resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==}
engines: {node: '>=12'}
xml-utils@1.10.2:
resolution: {integrity: sha512-RqM+2o1RYs6T8+3DzDSoTRAUfrvaejbVHcp3+thnAtDKo8LskR+HomLajEy5UjTz24rpka7AxVBRR3g2wTUkJA==}
xml-utils@1.7.0:
resolution: {integrity: sha512-bWB489+RQQclC7A9OW8e5BzbT8Tu//jtAOvkYwewFr+Q9T9KDGvfzC1lp0pYPEQPEoPQLDkmxkepSC/2gIAZGw==}
@@ -10004,18 +9907,12 @@ packages:
resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==}
engines: {node: '>=18'}
zarrita@0.7.5:
resolution: {integrity: sha512-ZriOSEne+Wf2iuM0yjDZvUKpHNlug3dO7qJ6mAxXoOgsYV18DPOkAkwB9e0rf21bHcKcOffFuwoZwn5g6pvUeA==}
zod@4.3.6:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
zstddec@0.1.0:
resolution: {integrity: sha512-w2NTI8+3l3eeltKAdK8QpiLo/flRAr2p8AGeakfMZOXBxOg9HIu4LVDxBi81sYgVhFhdJjv1OrB5ssI8uFPoLg==}
zstddec@0.2.0:
resolution: {integrity: sha512-oyPnDa1X5c13+Y7mA/FDMNJrn4S8UNBe0KCqtDmor40Re7ALrPN6npFwyYVRRh+PqozZQdeg23QtbcamZnG5rA==}
zustand@5.0.11:
resolution: {integrity: sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg==}
engines: {node: '>=12.20.0'}
@@ -12592,8 +12489,6 @@ snapshots:
'@petamoriken/float16@3.8.0': {}
'@petamoriken/float16@3.9.3': {}
'@pkgjs/parseargs@0.11.0':
optional: true
@@ -13681,11 +13576,7 @@ snapshots:
'@types/d3-geo@3.1.0':
dependencies:
'@types/geojson': 7946.0.16
'@types/d3-geo@3.1.1':
dependencies:
'@types/geojson': 7946.0.16
'@types/geojson': 7946.0.14
'@types/d3-hierarchy@1.1.11': {}
@@ -13725,7 +13616,7 @@ snapshots:
'@types/file-saver@2.0.5': {}
'@types/geojson@7946.0.16': {}
'@types/geojson@7946.0.14': {}
'@types/graceful-fs@4.1.6':
dependencies:
@@ -13814,8 +13705,6 @@ snapshots:
'@types/prop-types@15.7.5': {}
'@types/rbush@4.0.0': {}
'@types/react-addons-update@0.14.21':
dependencies:
'@types/react': 18.0.26
@@ -13886,15 +13775,6 @@ snapshots:
dependencies:
'@types/jest': 30.0.0
'@types/topojson-client@3.1.5':
dependencies:
'@types/geojson': 7946.0.16
'@types/topojson-specification': 1.0.5
'@types/topojson-specification@1.0.5':
dependencies:
'@types/geojson': 7946.0.16
'@types/tough-cookie@4.0.5': {}
'@types/trusted-types@2.0.7':
@@ -14190,11 +14070,6 @@ snapshots:
'@xobotyi/scrollbar-width@1.9.5': {}
'@zarrita/storage@0.2.0':
dependencies:
reference-spec-reader: 0.2.0
unzipit: 2.0.0
'@zxing/text-encoding@0.9.0':
optional: true
@@ -15083,10 +14958,6 @@ snapshots:
dependencies:
d3-array: 3.2.4
d3-geo@3.1.1:
dependencies:
d3-array: 3.2.4
d3-hierarchy@1.1.9: {}
d3-hierarchy@3.1.2: {}
@@ -15353,8 +15224,6 @@ snapshots:
earcut@2.2.4: {}
earcut@3.2.4: {}
eastasianwidth@0.2.0: {}
electron-to-chromium@1.5.427: {}
@@ -15671,8 +15540,6 @@ snapshots:
fflate@0.4.9: {}
fflate@0.8.3: {}
figures@3.2.0:
dependencies:
escape-string-regexp: 1.0.5
@@ -15861,17 +15728,6 @@ snapshots:
xml-utils: 1.7.0
zstddec: 0.1.0
geotiff@3.1.0-beta.0:
dependencies:
'@petamoriken/float16': 3.9.3
lerc: 3.0.0
pako: 2.1.0
parse-headers: 2.0.5
quick-lru: 6.1.1
web-worker: 1.5.0
xml-utils: 1.10.2
zstddec: 0.2.0
get-caller-file@2.0.5: {}
get-east-asian-width@1.5.0: {}
@@ -17929,10 +17785,6 @@ snapshots:
dependencies:
boolbase: 1.0.0
numcodecs@0.3.2:
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):
dependencies:
'@standard-schema/spec': 1.0.0
@@ -18011,15 +17863,6 @@ snapshots:
mapbox-to-css-font: 2.4.5
ol: 7.4.0
ol@10.11.0:
dependencies:
'@types/rbush': 4.0.0
earcut: 3.2.4
geotiff: 3.1.0-beta.0
pbf: 5.1.2
rbush: 4.0.1
zarrita: 0.7.5
ol@7.4.0:
dependencies:
earcut: 2.2.4
@@ -18346,10 +18189,6 @@ snapshots:
ieee754: 1.2.1
resolve-protobuf-schema: 2.1.0
pbf@5.1.2:
dependencies:
resolve-protobuf-schema: 2.1.0
picocolors@1.1.1: {}
picomatch@2.3.2: {}
@@ -18533,16 +18372,10 @@ snapshots:
quickselect@2.0.0: {}
quickselect@3.0.0: {}
rbush@3.0.1:
dependencies:
quickselect: 2.0.0
rbush@4.0.1:
dependencies:
quickselect: 3.0.0
rc-cascader@3.20.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
@@ -19276,8 +19109,6 @@ snapshots:
dependencies:
'@eslint-community/regexpp': 4.12.2
reference-spec-reader@0.2.0: {}
refractor@3.6.0:
dependencies:
hastscript: 6.0.0
@@ -20053,19 +19884,6 @@ snapshots:
toggle-selection@1.0.6: {}
topojson-client@3.1.0:
dependencies:
commander: 2.20.3
topojson-server@3.0.1:
dependencies:
commander: 2.20.3
topojson-simplify@3.0.3:
dependencies:
commander: 2.20.3
topojson-client: 3.1.0
tough-cookie@4.1.4:
dependencies:
psl: 1.15.0
@@ -20334,8 +20152,6 @@ snapshots:
'@unrs/resolver-binding-win32-ia32-msvc': 1.11.1
'@unrs/resolver-binding-win32-x64-msvc': 1.11.1
unzipit@2.0.0: {}
update-browserslist-db@1.3.3(browserslist@4.28.9):
dependencies:
browserslist: 4.28.9
@@ -20657,8 +20473,6 @@ snapshots:
xml-name-validator@4.0.0: {}
xml-utils@1.10.2: {}
xml-utils@1.7.0: {}
xml@1.0.1: {}
@@ -20735,17 +20549,10 @@ snapshots:
yoctocolors@2.1.2: {}
zarrita@0.7.5:
dependencies:
'@zarrita/storage': 0.2.0
numcodecs: 0.3.2
zod@4.3.6: {}
zstddec@0.1.0: {}
zstddec@0.2.0: {}
zustand@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)):
optionalDependencies:
'@types/react': 18.0.26

View File

@@ -1,210 +0,0 @@
// Builds the Geo Map outlines assets: Natural Earth 50m admin-0 countries, and
// 10m admin-1 states/provinces for every country with at least two of them.
// Run by hand when bumping Natural Earth or editing regions/aliases; the output is committed.
// Usage: pnpm build:geo-outlines
//
// Nothing is written until every invariant in validate.mjs holds. The assets
// are built in a staging folder and swapped in whole, so a failed run leaves
// the committed ones as they were.
import {
existsSync,
mkdirSync,
readdirSync,
renameSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { join } from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import { gzipSync } from 'node:zlib';
import {
ASSETS_DIR,
COUNTRIES_URL,
SUBDIVISION_LIST_FILE,
SUBDIVISIONS_URL,
} from './config.mjs';
import { buildCountries } from './countries.mjs';
import { buildSubdivisions } from './subdivisions.mjs';
import { validate } from './validate.mjs';
const DOWNLOAD_TIMEOUT_MS = 120_000;
const DOWNLOAD_ATTEMPTS = 3;
const STAGING_DIR = `${ASSETS_DIR}.staging`;
const PREVIOUS_DIR = `${ASSETS_DIR}.previous`;
// Everything in the assets folder is generated; anything else would be lost
// in the swap, so its presence stops the build.
const GENERATED_ENTRIES = new Set([
'countries-50m.json',
'lookups.json',
'subdivisions',
]);
const kb = (bytes) => `${(bytes / 1024).toFixed(0)} KB`;
const sizeOf = (json) =>
`${kb(Buffer.byteLength(json))} raw / ${kb(gzipSync(json).length)} gzip`;
async function downloadFeatures(url) {
for (let attempt = 1; ; attempt += 1) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const body = await response.json();
if (
body?.type !== 'FeatureCollection' ||
!Array.isArray(body.features) ||
body.features.length === 0
) {
throw new Error('response is not a non-empty GeoJSON FeatureCollection');
}
return body;
} catch (error) {
if (attempt === DOWNLOAD_ATTEMPTS) {
throw new Error(
`download failed after ${attempt} attempts: ${url}\n ${error.message}`,
);
}
await sleep(attempt * 2_000);
}
}
}
function subdivisionListSource(countries) {
return `// Generated by scripts/geo-outlines/build.mjs; do not edit.
export const SUBDIVISION_COUNTRY_CODES = [
${countries.map((country) => `\t'${country}',`).join('\n')}
] as const;
`;
}
// A run that died mid-swap leaves the assets in the previous folder.
function recoverInterruptedSwap() {
if (!existsSync(ASSETS_DIR) && existsSync(PREVIOUS_DIR)) {
renameSync(PREVIOUS_DIR, ASSETS_DIR);
}
rmSync(STAGING_DIR, { recursive: true, force: true });
rmSync(PREVIOUS_DIR, { recursive: true, force: true });
}
function assertOnlyGeneratedEntries() {
if (!existsSync(ASSETS_DIR)) {
return;
}
const foreign = readdirSync(ASSETS_DIR).filter(
(entry) => !GENERATED_ENTRIES.has(entry),
);
if (foreign.length > 0) {
throw new Error(
`${ASSETS_DIR} holds files this build doesn't generate: ${foreign.join(', ')}`,
);
}
}
/** Writes every output under the staging folder; returns the sizes report. */
function stage(outputs) {
const subdivisionDir = join(STAGING_DIR, 'subdivisions');
mkdirSync(subdivisionDir, { recursive: true });
writeFileSync(join(STAGING_DIR, 'countries-50m.json'), outputs.countriesJson);
writeFileSync(join(STAGING_DIR, 'lookups.json'), outputs.lookupsJson);
const sizes = [];
for (const [country, file] of outputs.subdivisionFiles) {
const json = JSON.stringify(file);
writeFileSync(join(subdivisionDir, `${country}.json`), json);
sizes.push({
country,
shapes: file.objects.subdivisions.geometries.length,
gzip: gzipSync(json).length,
});
}
writeFileSync(`${SUBDIVISION_LIST_FILE}.staging`, outputs.subdivisionList);
return sizes;
}
/** Swaps the staged assets in; puts the previous ones back if that fails. */
function commitStaged() {
const hadAssets = existsSync(ASSETS_DIR);
if (hadAssets) {
renameSync(ASSETS_DIR, PREVIOUS_DIR);
}
try {
renameSync(STAGING_DIR, ASSETS_DIR);
// A failed rename leaves the previous list in place.
renameSync(`${SUBDIVISION_LIST_FILE}.staging`, SUBDIVISION_LIST_FILE);
} catch (error) {
rmSync(ASSETS_DIR, { recursive: true, force: true });
if (hadAssets) {
renameSync(PREVIOUS_DIR, ASSETS_DIR);
}
throw error;
}
rmSync(PREVIOUS_DIR, { recursive: true, force: true });
}
function cleanUpStaging() {
rmSync(STAGING_DIR, { recursive: true, force: true });
rmSync(`${SUBDIVISION_LIST_FILE}.staging`, { force: true });
}
function report(countries, subdivisions, outputs, sizes) {
const totalGzip = sizes.reduce((sum, { gzip }) => sum + gzip, 0);
return {
countries: {
...countries.report,
sizes: {
'countries-50m.json': sizeOf(outputs.countriesJson),
'lookups.json': sizeOf(outputs.lookupsJson),
},
},
subdivisions: {
...subdivisions.report,
countries: sizes.length,
totalGzip: kb(totalGzip),
largest: [...sizes]
.sort((a, b) => b.gzip - a.gzip)
.slice(0, 10)
.map(
({ country, shapes, gzip }) =>
`${country}: ${shapes} shapes, ${kb(gzip)} gzip`,
),
},
};
}
async function main() {
recoverInterruptedSwap();
assertOnlyGeneratedEntries();
const [countrySource, subdivisionSource] = await Promise.all([
downloadFeatures(COUNTRIES_URL),
downloadFeatures(SUBDIVISIONS_URL),
]);
const countries = buildCountries(countrySource);
const subdivisions = buildSubdivisions(subdivisionSource);
validate(countries, subdivisions);
const outputs = {
countriesJson: JSON.stringify(countries.topology),
lookupsJson: JSON.stringify(countries.lookups),
subdivisionFiles: subdivisions.files,
subdivisionList: subdivisionListSource([...subdivisions.files.keys()]),
};
try {
const sizes = stage(outputs);
commitStaged();
process.stdout.write(
`${JSON.stringify(report(countries, subdivisions, outputs, sizes), null, 2)}\n`,
);
} finally {
cleanUpStaging();
}
}
main().catch((error) => {
process.stderr.write(`Geo outlines build failed: ${error.message}\n`);
process.exitCode = 1;
});

View File

@@ -1,181 +0,0 @@
// Inputs and tuning for the Geo Map outlines build. Tables only; no logic.
// Read by every other module here; not run on its own.
//
// Edit this file to bump Natural Earth (the pinned version below), retune
// simplification, or fix a region, alias or merge; then run
// pnpm build:geo-outlines and commit the rebuilt assets.
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const NATURAL_EARTH_BASE =
'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson';
export const COUNTRIES_URL = `${NATURAL_EARTH_BASE}/ne_50m_admin_0_countries.geojson`;
export const SUBDIVISIONS_URL = `${NATURAL_EARTH_BASE}/ne_10m_admin_1_states_provinces.geojson`;
const GEO_MAP_DIR = join(
dirname(fileURLToPath(import.meta.url)),
'../../src/lib/visualization/charts/GeoMap',
);
export const ASSETS_DIR = join(GEO_MAP_DIR, 'assets');
export const SUBDIVISION_LIST_FILE = join(
GEO_MAP_DIR,
'geo/subdivisionCountries.ts',
);
export const COUNTRY_QUANTIZATION = 1e5;
// Simplification drops every point whose triangle with its neighbours is
// smaller than this, in square degrees. A fixed size, unlike a share of all
// points, still leaves a small island a few points of its own.
export const COUNTRY_MIN_WEIGHT = 3e-3;
// 10m is street-level detail; a country view needs far less.
export const SUBDIVISION_QUANTIZATION = 1e4;
export const SUBDIVISION_MIN_WEIGHT = 1e-3;
// A shape this many times the minimum weight or smaller could lose every polygon.
export const PROTECTED_SHAPE_FACTOR = 10;
// A country view needs at least this many coded states to be worth drawing.
export const MIN_SUBDIVISIONS = 2;
// ISO 3166-2 codes that changed after Natural Earth v5.1.2, or older spellings
// still in GeoIP data, mapped to the code the shape carries.
export const SUBDIVISION_ALIASES = {
IN: {
'IN-CG': 'IN-CT',
'IN-UK': 'IN-UT',
'IN-TS': 'IN-TG',
'IN-OD': 'IN-OR',
'IN-DD': 'IN-DH',
'IN-DN': 'IN-DH',
},
// Natural Earth carries Metro Manila under its retired code.
PH: { 'PH-00': 'PH-MNL' },
};
// Shapes Natural Earth still splits along retired lines, merged into the codes
// GeoIP reports now; the retired codes become aliases. Northern Ireland's 26
// districts became 11 councils in 2015, each a union of old districts.
// Current code → [current name, retired codes].
export const SUBDIVISION_MERGES = {
GB: {
'GB-ANN': ['Antrim and Newtownabbey', ['GB-ANT', 'GB-NTA']],
'GB-AND': ['Ards and North Down', ['GB-ARD', 'GB-NDN']],
'GB-ABC': [
'Armagh City, Banbridge and Craigavon',
['GB-ARM', 'GB-BNB', 'GB-CGV'],
],
'GB-BFS': ['Belfast', ['GB-BFS']],
'GB-CCG': [
'Causeway Coast and Glens',
['GB-BLY', 'GB-CLR', 'GB-LMV', 'GB-MYL'],
],
'GB-DRS': ['Derry City and Strabane', ['GB-DRY', 'GB-STB']],
'GB-FMO': ['Fermanagh and Omagh', ['GB-FER', 'GB-OMH']],
'GB-LBC': ['Lisburn and Castlereagh', ['GB-LSB', 'GB-CSR']],
'GB-MEA': ['Mid and East Antrim', ['GB-BLA', 'GB-CKF', 'GB-LRN']],
'GB-MUL': ['Mid Ulster', ['GB-CKT', 'GB-DGN', 'GB-MFT']],
'GB-NMD': ['Newry, Mourne and Down', ['GB-NYM', 'GB-DOW']],
},
};
// Natural Earth puts these islands in "Seven seas (open ocean)".
export const OPEN_OCEAN_REGION = {
Africa: 'africa',
Asia: 'asia',
Americas: 'south_america',
};
export const CONTINENT_REGION = {
Africa: 'africa',
Asia: 'asia',
Europe: 'europe',
'North America': 'north_america',
'South America': 'south_america',
Oceania: 'oceania',
};
// Transcontinental countries belong to every region they span.
export const EXTRA_REGIONS = {
RU: ['asia'],
TR: ['europe'],
KZ: ['europe'],
GE: ['europe'],
AM: ['europe'],
AZ: ['europe'],
CY: ['europe'],
EG: ['asia'],
};
// ISO codes GeoIP emits for places Natural Earth draws inside another country.
export const COUNTRY_ALIASES = {
GF: 'FR',
GP: 'FR',
MQ: 'FR',
RE: 'FR',
YT: 'FR',
BQ: 'NL',
SJ: 'NO',
BV: 'NO',
CX: 'AU',
CC: 'AU',
HM: 'AU',
UM: 'US',
TK: 'NZ',
AC: 'SH',
TA: 'SH',
DG: 'IO',
CP: 'FR',
FX: 'FR',
EA: 'ES',
IC: 'ES',
CQ: 'GB',
GI: 'GB',
// Retired or reserved codes still seen in older data.
UK: 'GB',
SU: 'RU',
YU: 'RS',
CS: 'RS',
TP: 'TL',
BU: 'MM',
ZR: 'CD',
DD: 'DE',
VD: 'VN',
YD: 'YE',
RH: 'ZW',
NH: 'VU',
HV: 'BF',
DY: 'BJ',
AN: 'CW',
};
export const COUNTRY_NAME_ALIASES = {
usa: 'US',
'united states of america': 'US',
america: 'US',
uk: 'GB',
'great britain': 'GB',
britain: 'GB',
england: 'GB',
russia: 'RU',
'south korea': 'KR',
'north korea': 'KP',
czechia: 'CZ',
'czech republic': 'CZ',
'ivory coast': 'CI',
turkiye: 'TR',
türkiye: 'TR',
burma: 'MM',
'cape verde': 'CV',
swaziland: 'SZ',
macedonia: 'MK',
'east timor': 'TL',
vatican: 'VA',
};
// Alpha-2 codes Intl names that aren't countries, so none needs a shape.
export const NON_COUNTRY_CODES = new Set([
'EU',
'EZ',
'UN',
'ZZ',
'QO',
'XA',
'XB',
'AQ',
]);

View File

@@ -1,190 +0,0 @@
// Natural Earth admin-0 → the countries topology and the lookup tables.
// Called by build.mjs; not run on its own.
//
// Merges each country's parts into one shape by ISO alpha-2, drops Antarctica,
// assigns view regions and builds the alpha-3/name/alias lookups
// normalizeCountry reads. Returns the topology, the lookups and a report.
import { geoArea, geoBounds } from 'd3-geo';
import { feature } from 'topojson-client';
import {
CONTINENT_REGION,
COUNTRY_ALIASES,
COUNTRY_MIN_WEIGHT,
COUNTRY_NAME_ALIASES,
COUNTRY_QUANTIZATION,
EXTRA_REGIONS,
NON_COUNTRY_CODES,
OPEN_OCEAN_REGION,
} from './config.mjs';
import {
polygonsOf,
round,
roundBounds,
simplifyAndQuantize,
} from './geometry.mjs';
export const isCountryCode = (value) => /^[A-Z]{2}$/.test(value ?? '');
function regionsOf(props, iso2) {
const base = props.CONTINENT.startsWith('Seven seas')
? OPEN_OCEAN_REGION[props.REGION_UN]
: CONTINENT_REGION[props.CONTINENT];
return [...new Set([base, ...(EXTRA_REGIONS[iso2] ?? [])].filter(Boolean))];
}
// Group features by code so a country's overseas parts (Australia's Indian
// Ocean territories) become one shape that one data row colours.
function groupByCode(sourceFeatures, report) {
const groups = new Map();
for (const f of sourceFeatures) {
const p = f.properties;
if (p.CONTINENT === 'Antarctica') {
report.dropped.push(p.NAME);
continue;
}
const iso2 = isCountryCode(p.ISO_A2_EH) ? p.ISO_A2_EH : null;
const key = iso2 ?? `uncoded:${p.NAME}`;
if (!iso2) {
report.uncoded.push(p.NAME);
}
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(f);
}
return groups;
}
function toCountryFeature(key, members, report) {
// The sovereign part carries the name, label point and region.
const primary =
members.find((f) => f.properties.ISO_A2 === f.properties.ISO_A2_EH) ??
members.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
const p = primary.properties;
const iso2 = key.startsWith('uncoded:') ? null : key;
if (members.length > 1) {
report.merged.push(
`${iso2}: ${members.map((f) => f.properties.NAME).join(' + ')}`,
);
}
const polygons = members.flatMap((f) => polygonsOf(f.geometry));
const geometry = { type: 'MultiPolygon', coordinates: polygons };
const mainland = polygons
.map((coordinates) => ({ type: 'Polygon', coordinates }))
.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
return {
type: 'Feature',
id: iso2 ?? p.NAME,
properties: {
code: iso2,
iso3: /^[A-Z]{3}$/.test(p.ISO_A3_EH) ? p.ISO_A3_EH : null,
name: p.NAME,
label: [round(p.LABEL_X), round(p.LABEL_Y)],
mainland: roundBounds(geoBounds(mainland)),
bounds: roundBounds(geoBounds(geometry)),
regions: regionsOf(p, iso2 ?? ''),
},
geometry,
};
}
/** Alpha-3 codes and English names → alpha-2, for normalising data. */
function buildLookups(sourceFeatures) {
const alpha3 = {};
const names = { ...COUNTRY_NAME_ALIASES };
for (const { properties: p } of sourceFeatures) {
if (!isCountryCode(p.ISO_A2_EH) || p.CONTINENT === 'Antarctica') {
continue;
}
if (/^[A-Z]{3}$/.test(p.ISO_A3_EH)) {
alpha3[p.ISO_A3_EH] = p.ISO_A2_EH;
}
for (const name of [
p.NAME,
p.NAME_LONG,
p.ADMIN,
p.NAME_EN,
p.BRK_NAME,
p.NAME_SORT,
p.NAME_CIAWF,
]) {
if (name) {
names[name.toLowerCase()] ??= p.ISO_A2_EH;
}
}
}
return { alpha3, names, aliases: COUNTRY_ALIASES };
}
/** ISO alpha-2 codes Intl knows that neither a shape nor an alias covers. */
function findUncoveredCodes(drawn) {
const display = new Intl.DisplayNames(['en'], {
type: 'region',
fallback: 'none',
});
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const uncovered = [];
for (const a of letters) {
for (const b of letters) {
const code = a + b;
const name = display.of(code);
if (
name &&
!NON_COUNTRY_CODES.has(code) &&
!drawn.has(code) &&
!COUNTRY_ALIASES[code]
) {
uncovered.push(`${code} ${name}`);
}
}
}
return uncovered;
}
/** Natural Earth admin-0 GeoJSON → `{ topology, lookups, report }`. */
export function buildCountries(source) {
const report = { dropped: [], uncoded: [], merged: [] };
const features = [...groupByCode(source.features, report)]
.map(([key, members]) => toCountryFeature(key, members, report))
.sort((a, b) => String(a.id).localeCompare(String(b.id)));
const { topo, flipped, collapsed, emptied } = simplifyAndQuantize(
'countries',
features,
COUNTRY_MIN_WEIGHT,
COUNTRY_QUANTIZATION,
);
const drawn = new Set(features.map((f) => f.properties.code).filter(Boolean));
// Lets data be checked against the drawn codes without decoding the outlines.
const lookups = { codes: [...drawn].sort(), ...buildLookups(source.features) };
const regionCounts = {};
for (const f of features) {
for (const region of f.properties.regions) {
regionCounts[region] = (regionCounts[region] ?? 0) + 1;
}
}
return {
topology: topo,
lookups,
report: {
features: features.length,
decodedFeatures: feature(topo, topo.objects.countries).features.length,
droppedFlippedIslands: flipped,
droppedCollapsedPolygons: collapsed,
emptied: emptied.join(' '),
regionCounts,
...report,
lookupCounts: {
alpha3: Object.keys(lookups.alpha3).length,
names: Object.keys(lookups.names).length,
aliases: Object.keys(lookups.aliases).length,
},
uncoveredIsoCodes: findUncoveredCodes(drawn),
},
};
}

View File

@@ -1,118 +0,0 @@
// Geometry helpers and the simplification shared by countries and states.
// Used by countries.mjs and subdivisions.mjs; not run on its own.
//
// Simplification protects small shapes so islands keep an outline, and drops
// polygons that collapse to slivers or flip inside out after quantizing.
import { geoArea } from 'd3-geo';
import { topology } from 'topojson-server';
import { presimplify, simplify } from 'topojson-simplify';
import { feature, quantize } from 'topojson-client';
import { PROTECTED_SHAPE_FACTOR } from './config.mjs';
export const round = (n) => Math.round(n * 1e3) / 1e3;
export const roundBounds = (bounds) =>
bounds.map(([x, y]) => [round(x), round(y)]);
export function polygonsOf(geometry) {
if (geometry.type === 'Polygon') {
return [geometry.coordinates];
}
if (geometry.type === 'MultiPolygon') {
return geometry.coordinates;
}
return [];
}
/** Area of a lon/lat ring in square degrees, the unit of the simplify weights. */
function planarRingArea(ring) {
let twice = 0;
ring.forEach(([x, y], i) => {
const [nx, ny] = ring[(i + 1) % ring.length];
twice += x * ny - nx * y;
});
return Math.abs(twice) / 2;
}
// Weights every point of a small shape's largest outline as Infinity, which
// simplify never removes, so a city-state or city-sized province (Monaco, a
// London borough) still has an outline to colour. Neighbours share those arcs,
// so their common border stays in step.
function protectSmallShapes(topo, objectName, features, minWeight) {
topo.objects[objectName].geometries.forEach((geometry, i) => {
const polygons = polygonsOf(features[i].geometry);
const areas = polygons.map(([outer]) => planarRingArea(outer));
const total = areas.reduce((sum, area) => sum + area, 0);
if (polygons.length === 0 || total > minWeight * PROTECTED_SHAPE_FACTOR) {
return;
}
const largest = areas.indexOf(Math.max(...areas));
const rings =
geometry.type === 'Polygon' ? geometry.arcs : geometry.arcs[largest];
rings[0].forEach((index) => {
topo.arcs[index < 0 ? ~index : index].forEach((point) => {
point[2] = Infinity;
});
});
});
}
const isCollapsed = ([outer]) =>
new Set(outer.map((point) => point.join())).size < 3;
// Simplifying can collapse a tiny island until its ring runs the other way; d3
// then reads it as "the whole globe except this island" and floods the map.
const isInverted = (coordinates) =>
geoArea({ type: 'Polygon', coordinates }) > 2 * Math.PI;
/**
* One feature collection to a simplified, quantized topology under
* `objectName`. Polygons that collapse to a sliver or flip inside out are
* dropped and the topology rebuilt without them.
*/
export function simplifyAndQuantize(
objectName,
features,
minWeight,
quantization,
) {
let topo = presimplify(
topology({ [objectName]: { type: 'FeatureCollection', features } }),
);
protectSmallShapes(topo, objectName, features, minWeight);
topo = simplify(topo, minWeight);
// presimplify stores each point's weight as a third coordinate and simplify
// keeps it, so it is dropped before quantizing (which would carry it through).
topo = { ...topo, arcs: topo.arcs.map((arc) => arc.map(([x, y]) => [x, y])) };
topo = quantize(topo, quantization);
let flipped = 0;
let collapsed = 0;
const cleaned = feature(topo, topo.objects[objectName]).features.map((f) => {
const kept = polygonsOf(f.geometry).filter((coordinates) => {
if (isCollapsed(coordinates)) {
collapsed += 1;
return false;
}
if (isInverted(coordinates)) {
flipped += 1;
return false;
}
return true;
});
return { ...f, geometry: { type: 'MultiPolygon', coordinates: kept } };
});
const emptied = cleaned
.filter((f) => f.geometry.coordinates.length === 0)
.map((f) => f.properties.code ?? f.properties.name);
if (flipped > 0 || collapsed > 0) {
topo = quantize(
topology({
[objectName]: { type: 'FeatureCollection', features: cleaned },
}),
quantization,
);
}
return { topo, flipped, collapsed, emptied };
}

View File

@@ -1,202 +0,0 @@
// Natural Earth admin-1 → one states/provinces topology per country.
// Called by build.mjs; not run on its own.
//
// Skips countries with fewer than MIN_SUBDIVISIONS coded states, merges shapes
// split along retired lines, and records aliases for renamed codes. Returns one
// file per country and a report of what was skipped, merged or dropped.
import { geoArea } from 'd3-geo';
import { topology } from 'topojson-server';
import { merge } from 'topojson-client';
import {
MIN_SUBDIVISIONS,
SUBDIVISION_ALIASES,
SUBDIVISION_MERGES,
SUBDIVISION_MIN_WEIGHT,
SUBDIVISION_QUANTIZATION,
} from './config.mjs';
import { isCountryCode } from './countries.mjs';
import { round, simplifyAndQuantize } from './geometry.mjs';
const SUBDIVISION_CODE = /^[A-Z]{2}-[A-Z0-9]{1,3}$/;
/** Retired code → `[current code, current name]`, from `SUBDIVISION_MERGES`. */
const RECODES = new Map(
Object.values(SUBDIVISION_MERGES).flatMap((merges) =>
Object.entries(merges).flatMap(([code, [name, retired]]) =>
retired.map((old) => [old, [code, name]]),
),
),
);
/** A country's aliases: the hand-written ones, then each merge's retired codes. */
function aliasesOf(country) {
const aliases = { ...SUBDIVISION_ALIASES[country] };
for (const [code, [, retired]] of Object.entries(
SUBDIVISION_MERGES[country] ?? {},
)) {
for (const old of retired) {
if (old !== code) {
aliases[old] = code;
}
}
}
return aliases;
}
// Shapes without an ISO 3166-2 code can't be matched to data, and a code under
// another country's prefix (Puerto Rico's `US-PR`) belongs to that country's
// file. Retired codes are rewritten to the current ones here, so the merge
// below dissolves them.
function groupByCountry(sourceFeatures) {
const byCountry = new Map();
const uncoded = {};
const recoded = new Set();
for (const f of sourceFeatures) {
const country = f.properties.iso_a2;
if (!isCountryCode(country)) {
continue;
}
const code = f.properties.iso_3166_2;
if (!SUBDIVISION_CODE.test(code ?? '') || !code.startsWith(`${country}-`)) {
uncoded[country] = (uncoded[country] ?? 0) + 1;
continue;
}
if (!byCountry.has(country)) {
byCountry.set(country, []);
}
const recode = RECODES.get(code);
if (recode) {
recoded.add(code);
}
byCountry.get(country).push(
recode
? {
...f,
properties: {
...f.properties,
iso_3166_2: recode[0],
name: recode[1],
},
}
: f,
);
}
return { byCountry, uncoded, recoded };
}
// Natural Earth splits some codes across shapes (Dublin's four councils are all
// `IE-D`). Merging them through a topology drops the borders between the parts,
// so one code is one shape with one outline.
function mergeByCode(features) {
const byCode = new Map();
for (const f of features) {
const code = f.properties.iso_3166_2;
if (!byCode.has(code)) {
byCode.set(code, []);
}
byCode.get(code).push(f);
}
const topo = topology({ parts: { type: 'FeatureCollection', features } });
const { geometries } = topo.objects.parts;
let merged = 0;
const shapes = [...byCode].map(([code, members]) => {
// The largest part carries the name and label point.
const primary = members.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
let geometry = primary.geometry;
if (members.length > 1) {
merged += members.length - 1;
geometry = merge(
topo,
geometries.filter((_, i) => features[i].properties.iso_3166_2 === code),
);
}
return {
type: 'Feature',
id: code,
properties: {
code,
name: primary.properties.name,
label: [
round(primary.properties.longitude),
round(primary.properties.latitude),
],
},
geometry,
};
});
return { shapes: shapes.sort((a, b) => a.id.localeCompare(b.id)), merged };
}
/**
* Lower-cased English names → code, for data that names a state. A main name
* outranks a neighbour's alternate spelling of it.
*/
function namesOf(members) {
const names = {};
const mainNames = new Set();
for (const { properties: p } of members) {
const main = p.name?.toLowerCase();
if (main && !mainNames.has(main)) {
mainNames.add(main);
names[main] = p.iso_3166_2;
}
for (const name of [p.name_en, p.gn_name, p.woe_name]) {
if (name) {
names[name.toLowerCase()] ??= p.iso_3166_2;
}
}
}
return names;
}
/**
* Natural Earth admin-1 GeoJSON → `{ files, report }`, where `files` maps each
* country with enough coded states to its outlines file, in code order.
*/
export function buildSubdivisions(source) {
const { byCountry, uncoded, recoded } = groupByCountry(source.features);
const files = new Map();
const report = {
skippedUnderMinimum: [],
mergedParts: {},
uncodedShapes: uncoded,
droppedFlippedIslands: {},
droppedCollapsedPolygons: 0,
emptiedShapes: [],
// Merge entries whose retired code Natural Earth no longer has.
unmatchedRetiredCodes: [...RECODES.keys()].filter(
(code) => !recoded.has(code),
),
};
const countries = [...byCountry.keys()].sort((a, b) => a.localeCompare(b));
for (const country of countries) {
const members = byCountry.get(country);
const { shapes, merged } = mergeByCode(members);
if (shapes.length < MIN_SUBDIVISIONS) {
report.skippedUnderMinimum.push(country);
continue;
}
if (merged) {
report.mergedParts[country] = merged;
}
const { topo, flipped, collapsed, emptied } = simplifyAndQuantize(
'subdivisions',
shapes,
SUBDIVISION_MIN_WEIGHT,
SUBDIVISION_QUANTIZATION,
);
if (flipped) {
report.droppedFlippedIslands[country] = flipped;
}
report.droppedCollapsedPolygons += collapsed;
report.emptiedShapes.push(...emptied);
files.set(country, {
...topo,
aliases: aliasesOf(country),
names: namesOf(members),
});
}
return { files, report };
}

View File

@@ -1,114 +0,0 @@
// Invariants the chart relies on, checked before anything is written. A
// failure names every problem; the committed assets are left untouched.
// Called by build.mjs; not run on its own.
//
// Checks shape counts, that no shape is emptied or drawn twice, and that every
// code, alias and name resolves to a drawn shape.
import { feature } from 'topojson-client';
import { MIN_SUBDIVISIONS } from './config.mjs';
// Natural Earth v5.1.2 yields 239 countries and 198 countries with states. A
// drop below these means a changed or truncated download, not real geography.
const MIN_COUNTRIES = 230;
const MIN_SUBDIVISION_COUNTRIES = 190;
function duplicatesOf(values) {
const seen = new Set();
return values.filter((value) => seen.has(value) || !seen.add(value));
}
function checkCountries({ topology, lookups, report }, problems) {
const shapes = feature(topology, topology.objects.countries).features;
const codes = shapes.map((shape) => shape.properties.code).filter(Boolean);
const drawn = new Set(codes);
if (shapes.length < MIN_COUNTRIES) {
problems.push(
`only ${shapes.length} countries (expected ≥ ${MIN_COUNTRIES})`,
);
}
if (report.emptied) {
problems.push(`countries left with no outline: ${report.emptied}`);
}
for (const code of duplicatesOf(codes)) {
problems.push(`country code ${code} is drawn twice`);
}
if (lookups.codes.join() !== [...drawn].sort().join()) {
problems.push('lookups.codes differs from the drawn country codes');
}
for (const [alias, target] of Object.entries(lookups.aliases)) {
if (!drawn.has(target)) {
problems.push(`country alias ${alias} → ${target}, which has no shape`);
}
}
for (const [alpha3, target] of Object.entries(lookups.alpha3)) {
if (!drawn.has(target)) {
problems.push(`alpha-3 ${alpha3} → ${target}, which has no shape`);
}
}
}
function checkSubdivisionFile(country, file, problems) {
const codes = file.objects.subdivisions.geometries.map(
(geometry) => geometry.properties.code,
);
const known = new Set(codes);
if (codes.length < MIN_SUBDIVISIONS) {
problems.push(
`${country}: ${codes.length} states (expected ≥ ${MIN_SUBDIVISIONS})`,
);
}
for (const code of duplicatesOf(codes)) {
problems.push(`${country}: state code ${code} is drawn twice`);
}
for (const code of codes) {
if (!code?.startsWith(`${country}-`)) {
problems.push(`${country}: state code ${code} is outside the country`);
}
}
for (const [alias, target] of Object.entries(file.aliases)) {
if (!known.has(target)) {
problems.push(`${country}: alias ${alias} → ${target}, which has no shape`);
}
}
for (const [name, code] of Object.entries(file.names)) {
if (!known.has(code)) {
problems.push(`${country}: name "${name}" → ${code}, which has no shape`);
}
}
}
function checkSubdivisions({ files, report }, problems) {
if (files.size < MIN_SUBDIVISION_COUNTRIES) {
problems.push(
`only ${files.size} countries with states (expected ≥ ${MIN_SUBDIVISION_COUNTRIES})`,
);
}
if (report.emptiedShapes.length > 0) {
problems.push(
`states left with no outline: ${report.emptiedShapes.join(' ')}`,
);
}
if (report.unmatchedRetiredCodes.length > 0) {
problems.push(
`merge codes not found in Natural Earth: ${report.unmatchedRetiredCodes.join(' ')}`,
);
}
for (const [country, file] of files) {
checkSubdivisionFile(country, file, problems);
}
}
/** Throws one error listing every broken invariant. */
export function validate(countries, subdivisions) {
const problems = [];
checkCountries(countries, problems);
checkSubdivisions(subdivisions, problems);
if (problems.length > 0) {
throw new Error(
`${problems.length} problem(s) in the generated outlines:\n- ${problems.join('\n- ')}`,
);
}
}

View File

@@ -13,7 +13,6 @@ import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
import { OrgPreference } from 'types/api/preferences/preference';
import { USER_ROLES } from 'types/roles';
import { isSignozAdminEmail } from 'utils/app';
import {
routePermission,
routeWithInitialAuthZSupport,
@@ -26,8 +25,6 @@ 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 {
@@ -68,16 +65,9 @@ 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) && canListUsers,
enabled: !isEmpty(orgData) && user.role === 'ADMIN',
},
});
@@ -85,7 +75,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const users = usersData?.data || [];
const remainingUsers = (Array.isArray(users) ? users : []).filter(
(u) => !isSignozAdminEmail(u.email),
(user) => user.email !== 'admin@signoz.cloud',
);
return remainingUsers.length === 1;
@@ -171,9 +161,10 @@ 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.MY_SETTINGS));
(pathname === ROUTES.ORG_SETTINGS ||
pathname === ROUTES.MEMBERS_SETTINGS ||
pathname === ROUTES.MY_SETTINGS));
if (
pathname !== ROUTES.WORKSPACE_LOCKED &&
@@ -212,7 +203,6 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const isFirstUser = checkFirstTimeUser();
if (
isFirstUser &&
!isSignozAdminEmail(user.email) &&
!isOnboardingComplete &&
!ROUTES_NOT_TO_BE_OVERRIDEN.includes(pathname) &&
pathname !== ROUTES.ONBOARDING

View File

@@ -2,18 +2,9 @@ import { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
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 {
@@ -785,7 +776,7 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should allow VIEWER to access members settings when workspace is blocked', () => {
it('should redirect VIEWER to workspace locked when trying to access members settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.MEMBERS_SETTINGS,
appContext: {
@@ -798,7 +789,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should redirect VIEWER to workspace locked when trying to access my-settings', async () => {
@@ -1098,99 +1089,6 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.ONBOARDING);
});
it('should not redirect the signoz admin to onboarding while the first user has not completed it', async () => {
mockUsersData = [
{ email: 'test@example.com' },
{ email: SIGNOZ_ADMIN_EMAIL },
];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false),
user: createMockUser({
role: USER_ROLES.ADMIN as ROLES,
email: SIGNOZ_ADMIN_EMAIL,
}),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
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

@@ -5660,13 +5660,6 @@ export interface DashboardtypesBasicVisualizationDTO {
timePreference?: DashboardtypesTimePreferenceDTO;
}
/**
* @minimum 1
* @maximum 64
* @nullable
*/
export type DashboardtypesBubbleRadiusDTO = number | null;
export interface Querybuildertypesv5LogAggregationDTO {
/**
* @type string
@@ -6950,246 +6943,6 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesScatterPlotPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTOKind {
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
}
/**
* Radius of the largest circle, in CSS pixels from 1 to 64. Null means 8 on the points layer, 28 otherwise.
*/
export type DashboardtypesGeoMapBubblesDTOMaxRadius = DashboardtypesBubbleRadiusDTO | null;
/**
* Radius of the smallest circle, in CSS pixels from 1 to 64. Null means 2 on the points layer, 3 otherwise.
*/
export type DashboardtypesGeoMapBubblesDTOMinRadius = DashboardtypesBubbleRadiusDTO | null;
export interface DashboardtypesGeoMapBubblesDTO {
/**
* @description Radius of the largest circle, in CSS pixels from 1 to 64. Null means 8 on the points layer, 28 otherwise.
*/
maxRadius?: DashboardtypesGeoMapBubblesDTOMaxRadius;
/**
* @description Radius of the smallest circle, in CSS pixels from 1 to 64. Null means 2 on the points layer, 3 otherwise.
*/
minRadius?: DashboardtypesGeoMapBubblesDTOMinRadius;
}
export interface DashboardtypesGeoMapColorsDTO {
/**
* @type string
* @description The hex color varied in opacity mode. Empty uses the default fill.
*/
fill?: string;
/**
* @type number,null
* @description The value mapped to the highest color. Null uses the highest value in the data.
*/
max?: number | null;
/**
* @type number,null
* @description The value mapped to the lowest color. Null uses the lowest value in the data. Must not exceed max.
*/
min?: number | null;
/**
* @description How values are colored: palette (default) picks a hue from palette, opacity varies the opacity of fill.
*/
mode?: DashboardtypesHeatmapColorModeDTO;
/**
* @description The named color ramp used in palette mode, such as lava (default), ice or ember.
*/
palette?: DashboardtypesHeatmapPaletteDTO;
/**
* @description How values map onto the color range: log (default), sqrt or linear.
*/
scale?: DashboardtypesHeatmapColorScaleDTO;
/**
* @type integer
* @description The number of distinct color steps, 2 to 128. 0 uses the chart default.
*/
steps?: number;
}
export interface DashboardtypesGeoMapChartAppearanceDTO {
/**
* @description The circle radius range of the bubbles and points layers.
*/
bubbles?: DashboardtypesGeoMapBubblesDTO;
/**
* @description The color scale applied to the colorBy values.
*/
colors?: DashboardtypesGeoMapColorsDTO;
/**
* @type boolean,null
* @description Shows country and state names once each fits inside its shape. Null shows them.
*/
labels?: boolean | null;
}
export enum DashboardtypesGeoMapCountryFormatDTO {
auto = 'auto',
alpha2 = 'alpha2',
alpha3 = 'alpha3',
name = 'name',
}
export enum DashboardtypesGeoMapLocationModeDTO {
auto = 'auto',
country = 'country',
subdivision = 'subdivision',
coordinates = 'coordinates',
}
export interface DashboardtypesGeoMapLocationDTO {
/**
* @type string
* @description Group-by key holding the country, for the country and subdivision modes. Empty detects it by name, such as geo.country.iso_code.
*/
country?: string;
/**
* @description How country values are written: auto (default) detects it, alpha2, alpha3 or name.
*/
countryFormat: DashboardtypesGeoMapCountryFormatDTO;
/**
* @type string
* @description Group-by key holding the latitude, for the coordinates mode. Empty detects it by name.
*/
lat?: string;
/**
* @type string
* @description Group-by key holding the longitude, for the coordinates mode. Empty detects it by name.
*/
lon?: string;
/**
* @description How rows are placed: auto (default) detects it from the group-by keys, country, subdivision or coordinates.
*/
mode: DashboardtypesGeoMapLocationModeDTO;
/**
* @type string
* @description Group-by key holding the ISO 3166-2 region code (e.g. geo.region.iso_code), for the subdivision mode. Empty detects it by name.
*/
region?: string;
}
export enum DashboardtypesGeoMapLayerDTO {
regions = 'regions',
bubbles = 'bubbles',
points = 'points',
}
export enum DashboardtypesGeoMapProjectionDTO {
mercator = 'mercator',
equal_earth = 'equal_earth',
natural_earth = 'natural_earth',
}
export enum DashboardtypesGeoMapViewDTO {
world = 'world',
fit = 'fit',
africa = 'africa',
asia = 'asia',
europe = 'europe',
north_america = 'north_america',
south_america = 'south_america',
oceania = 'oceania',
country = 'country',
}
export interface DashboardtypesGeoMapSettingsDTO {
/**
* @type string
* @description Value column key, as in a Table panel, that sets the color. Empty uses the first value column.
*/
colorBy?: string;
/**
* @description What is drawn: regions (default) fills each shape, bubbles draws a circle per region, points a circle per coordinate.
*/
layer: DashboardtypesGeoMapLayerDTO;
/**
* @description The map projection: mercator (default), equal_earth or natural_earth.
*/
projection: DashboardtypesGeoMapProjectionDTO;
/**
* @type string
* @description Value column key, as in a Table panel, that sets the bubble or point size. Empty uses colorBy.
*/
sizeBy?: string;
/**
* @description The area shown: world (default), fit to the data, a continent, or country with viewCountry.
*/
view: DashboardtypesGeoMapViewDTO;
/**
* @type string
* @description Uppercase ISO 3166-1 alpha-2 code of the country the country view shows.
*/
viewCountry?: string;
}
export interface DashboardtypesGeoMapThresholdDTO {
/**
* @type string
* @description The CSS color of the shape, bubble or point while the threshold is active, for example #F1575F; CSS named colors such as red also work.
*/
color: string;
/**
* @description The comparison that activates the threshold: above (default), below, above_or_equal, below_or_equal, equal or not_equal.
*/
operator?: DashboardtypesComparisonOperatorDTO;
/**
* @type string
* @description The unit id of value, such as ms or percent. Empty means the colorBy column's unit.
*/
unit?: string;
/**
* @type number
* @format double
* @description The value compared against, in unit.
*/
value: number;
}
export interface DashboardtypesGeoMapPanelSpecDTO {
/**
* @description Color scale, bubble size and labels.
*/
chartAppearance?: DashboardtypesGeoMapChartAppearanceDTO;
/**
* @description Per-column units and decimal precision.
*/
formatting?: DashboardtypesTableFormattingDTO;
/**
* @description Legend placement.
*/
legend?: DashboardtypesLegendDTO;
/**
* @description The group-by columns that place each row on the map.
*/
location?: DashboardtypesGeoMapLocationDTO;
/**
* @description Layer, view, projection and the value columns drawn.
*/
map?: DashboardtypesGeoMapSettingsDTO;
/**
* @type array,null
* @description Rules that recolor a shape, bubble or point when its value compares to a threshold as specified.
*/
thresholds?: DashboardtypesGeoMapThresholdDTO[] | null;
/**
* @description The time range the values are computed over.
*/
visualization?: DashboardtypesBasicVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO {
/**
* @enum signoz/GeoMapPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesGeoMapPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7201,8 +6954,7 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -8489,7 +8241,6 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/TextPanel' = 'signoz/TextPanel',
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.
@@ -13156,7 +12907,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}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* 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.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13273,7 +13024,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}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @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.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13306,7 +13057,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}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* 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.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13365,7 +13116,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}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @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.
*/
labels?: RuletypesRuleDTOLabels;
/**

View File

@@ -54,7 +54,6 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
case PANEL_TYPES.SCATTER:
case PANEL_TYPES.PIE:
case PANEL_TYPES.VALUE:
case PANEL_TYPES.GEO_MAP:
return 'scalar';
case PANEL_TYPES.TRACE:
return 'trace';
@@ -278,8 +277,7 @@ export function createAggregation(
(panelType === PANEL_TYPES.TABLE ||
panelType === PANEL_TYPES.SCATTER ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.GEO_MAP);
panelType === PANEL_TYPES.VALUE);
if (queryData.dataSource === DataSource.METRICS) {
return [

View File

@@ -1,6 +1,5 @@
import { useCallback, useMemo, useState } from 'react';
import { Row, Select, Spin } from 'antd';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import {
@@ -18,7 +17,6 @@ export interface SelectOptionConfig {
placeholder: string;
queryParam: QueryParams;
filterType: string | string[];
fieldContext?: TelemetrytypesFieldContextDTO;
shouldSetQueryParams?: boolean;
onChange?: (value: string | string[]) => void;
values?: string | string[];
@@ -29,16 +27,13 @@ export function FilterSelect({
placeholder,
queryParam,
filterType,
fieldContext,
values,
shouldSetQueryParams,
onChange,
isMultiple,
}: SelectOptionConfig): JSX.Element {
const { handleSearch, isFetching, options } = useCeleryFilterOptions(
filterType,
fieldContext,
);
const { handleSearch, isFetching, options } =
useCeleryFilterOptions(filterType);
const urlQuery = useUrlQuery();
const location = useAppLocation();
@@ -123,7 +118,6 @@ export function FilterSelect({
}
FilterSelect.defaultProps = {
fieldContext: undefined,
shouldSetQueryParams: true,
onChange: (): void => {},
values: [],
@@ -135,14 +129,12 @@ function CeleryOverviewConfigOptions(): JSX.Element {
{
placeholder: 'Service Name',
queryParam: QueryParams.service,
filterType: 'service.name',
fieldContext: TelemetrytypesFieldContextDTO.resource,
filterType: 'serviceName',
},
{
placeholder: 'Span Name',
queryParam: QueryParams.spanName,
filterType: 'name',
fieldContext: TelemetrytypesFieldContextDTO.span,
},
{
placeholder: 'Msg System',
@@ -170,7 +162,6 @@ function CeleryOverviewConfigOptions(): JSX.Element {
placeholder={config.placeholder}
queryParam={config.queryParam}
filterType={config.filterType}
fieldContext={config.fieldContext}
/>
))}
</Row>

View File

@@ -1,37 +0,0 @@
import type { GetFieldsValues200 } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, waitFor } from 'tests/test-utils';
import CeleryOverviewConfigOptions from '../CeleryOverviewConfigOptions';
const emptyValues: GetFieldsValues200 = {
status: 'success',
data: { complete: true, values: { stringValues: [] } },
};
describe('CeleryOverviewConfigOptions', () => {
it('scopes the service and span name lookups to their field context', async () => {
const contextByKey = new Map<string, string | null>();
server.use(
rest.get('*/api/v1/fields/values', (req, res, ctx) => {
contextByKey.set(
req.url.searchParams.get('name') ?? '',
req.url.searchParams.get('fieldContext'),
);
return res(ctx.status(200), ctx.json(emptyValues));
}),
);
render(<CeleryOverviewConfigOptions />);
await waitFor(() => expect(contextByKey.size).toBe(6));
expect(Object.fromEntries(contextByKey)).toStrictEqual({
'service.name': 'resource',
name: 'span',
'messaging.system': null,
'messaging.destination.name': null,
'messaging.destination': null,
kind_string: null,
});
});
});

View File

@@ -1,21 +1,23 @@
import { useQuery } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import type { DefaultOptionType } from 'antd/es/select';
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
import { FIELD_API_CACHE_TIME } from 'constants/queryCacheTime';
import { getAttributesValues } from 'api/queryBuilder/getAttributesValues';
import { DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { toFieldValues } from 'hooks/querySuggestions/useFieldValuesSuggestion';
import { AppState } from 'store/reducers';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DATA_SOURCE_TO_SIGNAL, DataSource } from 'types/common/queryBuilder';
import { getValuesForDataType } from 'utils/fieldValues';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
export interface Filters {
searchText: string;
attributeKey: string | string[];
aggregateOperator?: string;
dataSource?: DataSource;
metricName?: string;
aggregateAttribute?: string;
filterAttributeKeyDataType?: DataTypes;
fieldContext?: TelemetrytypesFieldContextDTO;
tagType?: string;
}
export interface GetAllFiltersResponse {
@@ -27,41 +29,54 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
const {
searchText,
attributeKey,
aggregateOperator,
dataSource,
metricName,
aggregateAttribute,
filterAttributeKeyDataType,
fieldContext,
tagType,
} = props;
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const { data, isLoading } = useQuery(
[
REACT_QUERY_KEY.GET_ATTRIBUTE_VALUES,
dataSource,
metricName,
attributeKey,
fieldContext,
searchText,
minTime,
maxTime,
],
async () => {
const keys = Array.isArray(attributeKey) ? attributeKey : [attributeKey];
const responses = await Promise.all(
keys.map((key) =>
getFieldValueSuggestions({
signal: DATA_SOURCE_TO_SIGNAL[dataSource || DataSource.TRACES],
name: key,
fieldContext,
getAttributesValues({
aggregateOperator: aggregateOperator || 'noop',
dataSource: dataSource || DataSource.TRACES,
aggregateAttribute: aggregateAttribute || '',
attributeKey: key,
searchText: searchText ?? '',
metricName,
filterAttributeKeyDataType:
filterAttributeKeyDataType || DataTypes.String,
tagType: tagType || 'tag',
}),
),
);
const uniqueValues = [
...new Set(
responses.flatMap((response) =>
getValuesForDataType(toFieldValues(response), filterAttributeKeyDataType),
),
responses.flatMap(({ payload }) => {
if (!payload) {
return [];
}
const dataType = filterAttributeKeyDataType || DataTypes.String;
const key = DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY[dataType];
return key ? payload[key] || [] : [];
}),
),
];
@@ -70,7 +85,6 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
value: val,
}));
},
{ staleTime: FIELD_API_CACHE_TIME },
);
return { options: data ?? [], isFetching: isLoading };

View File

@@ -8,9 +8,12 @@ import { CardContainer } from 'container/WidgetCard/styles';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { ChevronDown, ChevronUp } from '@signozhq/icons';
import { AppState } from 'store/reducers';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import { CaptureDataProps } from '../CeleryTaskDetail/CeleryTaskDetail';
import { useCeleryFilterOptions } from '../useCeleryFilterOptions';
import CeleryTaskBar from './CeleryTaskBar';
import CeleryTaskGraph from './CeleryTaskGraph';
import {
@@ -20,7 +23,6 @@ import {
celeryTasksByWorkerWidgetData,
} from './CeleryTaskGraphUtils';
import CeleryTaskLatencyGraph from './CeleryTaskLatencyGraph';
import { useCeleryWorkerCount } from './useCeleryWorkerCount';
import './CeleryTaskGraph.style.scss';
@@ -69,7 +71,14 @@ export default function CeleryTaskGraphGrid({
'Latency by worker',
];
const { data: workerCount } = useCeleryWorkerCount();
const { options } = useCeleryFilterOptions(
'worker',
'rate',
DataSource.METRICS,
'flower_task_runtime_seconds_sum',
DataTypes.String,
'tag',
);
const isDarkMode = useIsDarkMode();
const [collapsedSections, setCollapsedSections] = useState<{
@@ -142,11 +151,8 @@ export default function CeleryTaskGraphGrid({
</Typography.Text>
</div>
<div className="worker-count-text-container">
<Typography.Text
className="celery-task-graph-worker-count-text"
data-testid="celery-worker-count"
>
{workerCount ?? '-'}
<Typography.Text className="celery-task-graph-worker-count-text">
{options.filter((option) => option.value).length}
</Typography.Text>
</div>
</Card>

View File

@@ -1,12 +1,3 @@
import {
MetrictypesSpaceAggregationDTO,
MetrictypesTimeAggregationDTO,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
type Querybuildertypesv5QueryRangeRequestDTO,
Querybuildertypesv5ReduceToDTO,
Querybuildertypesv5RequestTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
@@ -1051,34 +1042,3 @@ export const celeryRetryStateCountWidgetData = getWidgetQueryBuilder(
],
}),
);
// One row per worker that reported in the range; the card counts the rows.
export const getCeleryWorkerCountRequest = (
startTime: number,
endTime: number,
): Querybuildertypesv5QueryRangeRequestDTO => ({
schemaVersion: 'v1',
start: Math.floor(startTime / 1e6),
end: Math.floor(endTime / 1e6),
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
compositeQuery: {
queries: [
{
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
spec: {
name: 'A',
signal: MetricSignal.metrics,
aggregations: [
{
metricName: 'flower_task_runtime_seconds_sum',
timeAggregation: MetrictypesTimeAggregationDTO.count,
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
reduceTo: Querybuildertypesv5ReduceToDTO.sum,
},
],
groupBy: [{ name: 'worker' }],
},
},
],
},
});

View File

@@ -1,93 +0,0 @@
import {
Querybuildertypesv5ColumnTypeDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import store from 'store';
import { render, screen, waitFor } from 'tests/test-utils';
import CeleryTaskGraphGrid from '../CeleryTaskGraphGrid';
const workerCountResponse = (workers: string[]): QueryRangeV5200 => ({
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: {
results: [
{
columns: [
{
name: 'worker',
queryName: 'A',
columnType: Querybuildertypesv5ColumnTypeDTO.group,
},
{
name: '__result_0',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
},
],
data: workers.map((worker) => [worker, 4]),
},
],
},
},
});
describe('CeleryTaskGraphGrid worker count', () => {
let requests: Querybuildertypesv5QueryRangeRequestDTO[];
beforeEach(() => {
requests = [];
server.use(
rest.post('*/api/v5/query_range', async (req, res, ctx) => {
requests.push(await req.json());
return res(
ctx.status(200),
ctx.json(workerCountResponse(['worker-a', 'worker-b', ''])),
);
}),
);
});
it('counts the workers that reported in the selected range', async () => {
render(<CeleryTaskGraphGrid onClick={jest.fn()} queryEnabled={false} />);
await waitFor(() =>
expect(screen.getByTestId('celery-worker-count')).toHaveTextContent('2'),
);
const { minTime, maxTime } = store.getState().globalTime;
expect(requests).toStrictEqual([
{
schemaVersion: 'v1',
start: Math.floor(minTime / 1e6),
end: Math.floor(maxTime / 1e6),
requestType: 'scalar',
compositeQuery: {
queries: [
{
type: 'builder_query',
spec: {
name: 'A',
signal: 'metrics',
aggregations: [
{
metricName: 'flower_task_runtime_seconds_sum',
timeAggregation: 'count',
spaceAggregation: 'sum',
reduceTo: 'sum',
},
],
groupBy: [{ name: 'worker' }],
},
},
],
},
},
]);
});
});

View File

@@ -1,31 +0,0 @@
import { useMemo } from 'react';
import { useQuery, UseQueryResult } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { queryRangeV5 } from 'api/generated/services/querier';
import type { QueryRangeV5200 } from 'api/generated/services/sigNoz.schemas';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
import { getCeleryWorkerCountRequest } from './CeleryTaskGraphUtils';
export function useCeleryWorkerCount(): UseQueryResult<number, Error> {
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const request = useMemo(
() => getCeleryWorkerCountRequest(minTime, maxTime),
[minTime, maxTime],
);
return useQuery<QueryRangeV5200, Error, number>({
queryKey: [REACT_QUERY_KEY.GET_CELERY_WORKER_COUNT, request],
queryFn: ({ signal }) => queryRangeV5(request, signal),
select: (response) =>
(getScalarResults(response)[0]?.data ?? []).filter(([worker]) => worker)
.length,
});
}

View File

@@ -1,13 +1,18 @@
import { useState } from 'react';
import type { DefaultOptionType } from 'antd/es/select';
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource } from 'types/common/queryBuilder';
import { useGetAllFilters } from './CeleryTaskConfigOptions/useGetCeleryFilters';
export const useCeleryFilterOptions = (
type: string | string[],
fieldContext?: TelemetrytypesFieldContextDTO,
aggregateOperator?: string,
dataSource?: DataSource,
aggregateAttribute?: string,
filterAttributeKeyDataType?: DataTypes,
tagType?: string,
): {
searchText: string;
handleSearch: (value: string) => void;
@@ -18,7 +23,11 @@ export const useCeleryFilterOptions = (
const { isFetching, options } = useGetAllFilters({
attributeKey: type,
searchText,
fieldContext,
aggregateOperator,
dataSource,
aggregateAttribute,
filterAttributeKeyDataType,
tagType,
});
const handleDebouncedSearch = useDebouncedFn((searchText): void => {
setSearchText(searchText as string);

View File

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

View File

@@ -17,16 +17,6 @@ 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';
@@ -178,6 +168,7 @@ function renderDrawer(
return render(
<EditMemberDrawer
member={activeMember}
open
onClose={jest.fn()}
onComplete={jest.fn()}
{...props}
@@ -185,16 +176,6 @@ 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();
@@ -205,7 +186,6 @@ describe('EditMemberDrawer', () => {
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
),
setupAuthzAdmin(),
);
(useGetUser as jest.Mock).mockReturnValue({
data: mockFetchedUser,
@@ -263,33 +243,15 @@ describe('EditMemberDrawer', () => {
server.resetHandlers();
});
it('renders active member details and disables Save when form is not dirty', async () => {
it('renders active member details and disables Save when form is not dirty', () => {
renderDrawer();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.toBeInTheDocument();
expect(screen.getByDisplayValue('Alice Smith')).toBeInTheDocument();
expect(screen.getByText('alice@signoz.io')).toBeInTheDocument();
expect(screen.getByText('ACTIVE')).toBeInTheDocument();
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 } },
),
);
expect(
screen.getByRole('button', { name: /save member details/i }),
).toHaveAttribute('aria-disabled', 'true');
});
it('enables Save after editing name and calls updateUser on confirm', async () => {
@@ -304,8 +266,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Alice Smith');
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -331,8 +292,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onClose });
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Alice Smith');
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -363,7 +323,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
// signoz-admin is already selected; add signoz-editor on top
await user.click(await screen.findByLabelText('Roles'));
await user.click(screen.getByLabelText('Roles'));
await user.click(await screen.findByTitle('signoz-editor'));
const saveBtn = screen.getByRole('button', { name: /save member details/i });
@@ -421,7 +381,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /delete member/i }));
await expect(
screen.findByText(/are you sure you want to delete/i),
@@ -438,11 +398,9 @@ describe('EditMemberDrawer', () => {
});
});
it('shows revoke invite and copy invite link for invited members; hides Last Modified', async () => {
it('shows revoke invite and copy invite link for invited members; hides Last Modified', () => {
renderDrawer({ member: invitedMember });
await screen.findByText('Invited On');
expect(
screen.getByRole('button', { name: /revoke invite/i }),
).toBeInTheDocument();
@@ -456,7 +414,7 @@ describe('EditMemberDrawer', () => {
expect(screen.queryByText('Last Modified')).not.toBeInTheDocument();
});
it('shows "Regenerate Invite Link" when token is expired', async () => {
it('shows "Regenerate Invite Link" when token is expired', () => {
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
data: {
data: {
@@ -471,12 +429,12 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
await expect(
screen.findByRole('button', { name: /regenerate invite link/i }),
).resolves.toBeInTheDocument();
expect(
screen.getByRole('button', { name: /regenerate invite link/i }),
).toBeInTheDocument();
});
it('shows "Generate Invite Link" when no token exists', async () => {
it('shows "Generate Invite Link" when no token exists', () => {
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
data: undefined,
isLoading: false,
@@ -485,88 +443,9 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
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',
);
expect(
screen.getByRole('button', { name: /generate invite link/i }),
).toBeInTheDocument();
});
it('calls deleteUser after confirming revoke invite for invited members', async () => {
@@ -582,7 +461,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember, onComplete });
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
await expect(
screen.findByText(/Are you sure you want to revoke the invite/i),
@@ -629,8 +508,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: { ...invitedMember, name: 'Bob' }, onComplete });
const nameInput = await screen.findByDisplayValue('Bob');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Bob');
await user.clear(nameInput);
await user.type(nameInput, 'Bob Updated');
@@ -668,8 +546,7 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Alice Smith');
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -698,7 +575,7 @@ describe('EditMemberDrawer', () => {
renderDrawer();
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /delete member/i }));
const confirmBtns = screen.getAllByRole('button', {
name: /delete member/i,
});
@@ -729,7 +606,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
const confirmBtns = screen.getAllByRole('button', {
name: /revoke invite/i,
});
@@ -768,86 +645,16 @@ describe('EditMemberDrawer', () => {
).not.toBeInTheDocument();
});
it('keeps name input enabled when viewing own profile', async () => {
it('keeps name input enabled when viewing own profile', () => {
renderDrawer({ member: selfMember });
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.not.toBeDisabled();
expect(screen.getByDisplayValue('Alice Smith')).not.toBeDisabled();
});
it('keeps Reset Link button enabled when viewing own profile', async () => {
it('keeps Reset Link button enabled when viewing own profile', () => {
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.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',
);
screen.getByRole('button', { name: /generate password reset link/i }),
).not.toHaveAttribute('aria-disabled', 'true');
});
});
@@ -860,11 +667,9 @@ describe('EditMemberDrawer', () => {
});
});
it('disables name input for root user', async () => {
it('disables name input for root user', () => {
renderDrawer();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.toBeDisabled();
expect(screen.getByDisplayValue('Alice Smith')).toBeDisabled();
});
it('disables Delete button for root user', () => {
@@ -921,11 +726,9 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
await user.click(
screen.getByRole('button', { name: /generate password reset link/i }),
);
await user.click(resetBtn);
const dialog = await screen.findByRole('dialog', {
name: /password reset link/i,
@@ -944,11 +747,9 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
await user.click(
screen.getByRole('button', { name: /generate password reset link/i }),
);
await user.click(resetBtn);
const dialog = await screen.findByRole('dialog', {
name: /password reset link/i,

View File

@@ -1,68 +0,0 @@
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,7 +1,5 @@
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';
@@ -17,12 +15,7 @@ export function useCreatorOptions({
currentUserEmail,
fallbackEmails,
}: Args): CreatorOption[] {
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 } });
const { data } = useListUsers();
return useMemo<CreatorOption[]>(() => {
const users = data?.data ?? [];

View File

@@ -6,7 +6,6 @@ const SCALAR_PANEL_TYPES: ReadonlySet<string> = new Set<string>([
PANEL_TYPES.SCATTER,
PANEL_TYPES.PIE,
PANEL_TYPES.VALUE,
PANEL_TYPES.GEO_MAP,
]);
export function isScalarPanelType(panelType?: string | null): boolean {

View File

@@ -1,5 +1,5 @@
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { fieldContextToAttributeType } from 'utils/fieldContext';
import { fieldDataTypeToDataType } from 'utils/fieldDataType';
import { FiltersType, IQuickFiltersConfig } from './types';
@@ -14,6 +14,19 @@ const FILTER_TYPE_MAP: Record<string, FiltersType> = {
duration_nano: FiltersType.DURATION,
};
// The map below exists only for the old v3 attribute-values fetch
// (useCheckboxFilterValues), the sole reader of attributeKey.dataType/type.
// Once the values fetch moves to fields/values, remove this and reduce
// attributeKey to { id, key }.
const FIELD_CONTEXT_TO_ATTRIBUTE_TYPE: Record<string, string> = {
[TelemetrytypesFieldContextDTO.attribute]: 'tag',
[TelemetrytypesFieldContextDTO.resource]: 'resource',
};
const mapFieldContext = (fieldContext?: string): string =>
(fieldContext && FIELD_CONTEXT_TO_ATTRIBUTE_TYPE[fieldContext]) || '';
const getFilterName = (str: string): string => {
if (FILTER_TITLE_MAP[str]) {
return FILTER_TITLE_MAP[str];
@@ -48,15 +61,11 @@ export const getFilterConfig = (
({
type: getFilterType(att),
title: getFilterName(att.name),
// The type mapping below exists only for the old v3 attribute-values fetch
// (useCheckboxFilterValues), the sole reader of attributeKey.dataType/type.
// Once the values fetch moves to fields/values, remove this and reduce
// attributeKey to { id, key }.
attributeKey: {
id: att.name,
key: att.name,
dataType: fieldDataTypeToDataType(att.fieldDataType),
type: fieldContextToAttributeType(att.fieldContext),
type: mapFieldContext(att.fieldContext),
},
defaultOpen: index < 2,
}) as IQuickFiltersConfig,

View File

@@ -15,5 +15,3 @@ export const DASHBOARD_TIME_IN_DURATION = 'refreshInterval';
export const DEFAULT_ENTITY_VERSION = 'v3';
export const ENTITY_VERSION_V4 = 'v4';
export const ENTITY_VERSION_V5 = 'v5';
export const SIGNOZ_ADMIN_EMAIL = 'admin@signoz.cloud';

View File

@@ -34,7 +34,6 @@ export const getComponentForPanelType = (
[PANEL_TYPES.HISTOGRAM]: Uplot,
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
[PANEL_TYPES.TEXT]: null,
[PANEL_TYPES.SCATTER]: null,

View File

@@ -340,7 +340,6 @@ export enum PANEL_TYPES {
PIE = 'pie',
HISTOGRAM = 'histogram',
HEATMAP = 'heatmap',
GEO_MAP = 'geo_map',
TEXT = 'text',
EMPTY_WIDGET = 'EMPTY_WIDGET',
}

View File

@@ -109,9 +109,6 @@ export const REACT_QUERY_KEY = {
// Field Values Suggestion Query Keys
FIELD_VALUES_SUGGESTION: 'FIELD_VALUES_SUGGESTION',
// Celery Query Keys
GET_CELERY_WORKER_COUNT: 'GET_CELERY_WORKER_COUNT',
// AI Assistant Query Keys
AI_ASSISTANT_EMPTY_STATE_CHIPS: 'AI_ASSISTANT_EMPTY_STATE_CHIPS',
} as const;

View File

@@ -20,7 +20,8 @@ export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO>
*Summary:* {{ .Annotations.summary }}
*Description:* {{ .Annotations.description }}
{{ template "signoz.relatedLinks.slack" . }}
*RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}
*RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}
*Details:*
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
@@ -140,7 +141,11 @@ export const JsmOpsInitialConfig: Partial<AlertmanagertypesChannelJSMOpsConfigDT
{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ end }}`,
{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
{{ end }}{{ end }}`,
priority:
'{{ if eq (index .Alerts 0).Labels.severity "critical" }}P1{{ else if eq (index .Alerts 0).Labels.severity "warning" }}P2{{ else if eq (index .Alerts 0).Labels.severity "info" }}P3{{ else }}P4{{ end }}',
tags: 'signoz-alert',
@@ -163,7 +168,11 @@ export const IncidentIOInitialConfig: Partial<AlertmanagertypesChannelIncidentIO
{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ end }}`,
{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
{{ end }}{{ end }}`,
};
export const EmailInitialConfig: Partial<AlertmanagertypesChannelEmailConfigDTO> =

View File

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

View File

@@ -6,25 +6,15 @@ 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;
@@ -33,12 +23,6 @@ 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);
@@ -48,18 +32,7 @@ function MembersSettings(): JSX.Element {
);
const [selectedMember, setSelectedMember] = useState<MemberRow | null>(null);
const canListUsers =
!!authzError || (authzPermissions?.[UserListPermission]?.isGranted ?? false);
const {
data: usersData,
isLoading,
refetch: refetchUsers,
isError,
error,
} = useListUsers({ query: { enabled: canListUsers } });
const controlsDisabled = !canListUsers || isAuthZLoading;
const { data: usersData, isLoading, refetch: refetchUsers } = useListUsers();
const allMembers = useMemo(
(): MemberRow[] =>
@@ -203,89 +176,57 @@ function MembersSettings(): JSX.Element {
</div>
<div className="members-settings__controls">
<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>
<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>
<div className="members-settings__search">
<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>
<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"
/>
</div>
<AuthZButton
<Button
size="md"
variant="solid"
color="primary"
checks={[UserCreatePermission]}
onClick={(): void => void setIsInviteModalOpen(true)}
prefix={<Plus size={12} />}
testId="invite-member-btn"
>
Invite member
</AuthZButton>
</Button>
</div>
</div>
<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>
<MembersTable
data={filteredMembers}
loading={isLoading}
total={filteredMembers.length}
currentPage={currentPage}
pageSize={PAGE_SIZE}
searchQuery={searchQuery}
onPageChange={setPage}
onRowClick={handleRowClick}
/>
<InviteMembersModal
open={isInviteModalOpen}
@@ -295,6 +236,7 @@ function MembersSettings(): JSX.Element {
<EditMemberDrawer
member={selectedMember}
open={selectedMember !== null}
onClose={handleDrawerClose}
onComplete={handleMemberEditComplete}
/>

View File

@@ -1,11 +1,7 @@
import type { TypesUserDTO } from 'api/generated/services/sigNoz.schemas';
import userEvent from '@testing-library/user-event';
import { rest, server } from 'mocks-server/server';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
import { fireEvent, render, screen } from 'tests/test-utils';
import MembersSettings from '../MembersSettings';
@@ -61,7 +57,6 @@ describe('MembersSettings (integration)', () => {
rest.get(USERS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockUsers })),
),
setupAuthzAdmin(),
);
});
@@ -128,22 +123,10 @@ 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 />);
const inviteBtn = await screen.findByTestId('invite-member-btn');
await waitFor(() =>
expect(inviteBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await userEvent.click(inviteBtn);
fireEvent.click(screen.getByRole('button', { name: /invite member/i }));
await expect(
screen.findAllByPlaceholderText('e.g. john@signoz.io'),

View File

@@ -4,8 +4,6 @@ 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';
@@ -60,21 +58,18 @@ function InviteMembersModal({
Cancel
</Button>
<AuthZButton
<Button
size="md"
variant="solid"
color="primary"
onClick={submit}
disabled={!canSubmit}
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
disabledTooltip="Add at least one team member to invite"
loading={isSubmitting}
testId="invite-submit-btn"
>
{isSubmitting ? 'Inviting...' : 'Invite Team Members'}
</AuthZButton>
</Button>
</div>
)}
/>

View File

@@ -1,11 +1,5 @@
import { toast } from '@signozhq/ui/sonner';
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 { render, screen, userEvent } from 'tests/test-utils';
import InviteMembersModal from '../InviteMembersModal';
@@ -61,7 +55,6 @@ describe('InviteMembersModal', () => {
beforeEach(() => {
jest.clearAllMocks();
mockInviteMembersProps = null;
server.use(setupAuthzAdmin());
});
describe('rendering', () => {
@@ -141,7 +134,7 @@ describe('InviteMembersModal', () => {
const { unmount } = renderComponent();
unmount();
const { getByTestId } = render(
const { getByRole } = render(
mockInviteMembersProps?.renderFooter({
submit: mockSubmit,
canSubmit: true,
@@ -149,27 +142,10 @@ describe('InviteMembersModal', () => {
}) as JSX.Element,
);
const submit = getByTestId('invite-submit-btn');
await waitFor(() =>
expect(submit).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(submit);
await user.click(getByRole('button', { name: /invite team members/i }));
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,6 +58,22 @@
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 } from '@signozhq/icons';
import { Check, FileTerminal, Mail, User } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
@@ -129,9 +129,13 @@ function UserInfo(): JSX.Element {
</div>
<div className="user-info-subsection">
<div className="user-email" data-testid="user-info-email">
<div className="user-email">
<Mail size={16} /> {user.email}
</div>
<div className="user-role">
<User size={16} /> {user.role.toLowerCase()}
</div>
</div>
</div>

View File

@@ -168,13 +168,6 @@ 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);
@@ -471,34 +464,3 @@ 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,8 +6,6 @@ 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';
@@ -120,22 +118,20 @@ function InviteTeamMembers({
return (
<div className="onboarding-buttons-container">
<AuthZButton
<Button
size="md"
variant="solid"
color="primary"
width="100%"
onClick={submit}
loading={isButtonDisabled}
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
testId="send-invites-button"
suffix={<ArrowRight size={12} />}
>
Send Invites
</AuthZButton>
</Button>
<Button
size="md"
variant="ghost"

View File

@@ -1,78 +0,0 @@
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,8 +22,6 @@ 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';
@@ -713,7 +711,6 @@ 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} />}
>
@@ -1188,7 +1185,7 @@ function OnboardingAddDataSource(): JSX.Element {
>
Cancel
</SignozButton>
<AuthZButton
<SignozButton
size="md"
color="primary"
variant="solid"
@@ -1199,16 +1196,13 @@ function OnboardingAddDataSource(): JSX.Element {
);
void submit();
}}
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
loading={isSubmitting}
suffix={<ArrowRight size={14} />}
testId="onboarding-send-invites-btn"
>
Send Invites
</AuthZButton>
</SignozButton>
</div>
)}
/>

View File

@@ -1,61 +0,0 @@
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,88 +0,0 @@
import { Form } from 'antd';
import QueryBuilderSearchV2 from 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2';
import { server } from 'mocks-server/server';
import { act, render, waitFor } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import type { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import type {
BaseBuilderQuery,
QueryRangePayloadV5,
} from 'types/api/v5/queryRange';
import { pipelineFields } from '../../../../config';
import { queryRangeV5Handler } from '../../../../Preview/__tests__/fixtures';
import FilterInput from '..';
jest.mock(
'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2',
() => ({ __esModule: true, default: jest.fn(() => null) }),
);
const filterField = pipelineFields.find((field) => field.name === 'filter');
const v5Filter: TagFilter = {
op: 'AND',
items: [
{
id: 'attribute-pill',
key: { key: 'http.method', dataType: DataTypes.String, type: 'attribute' },
op: '=',
value: 'GET',
},
{
id: 'log-pill',
key: { key: 'severity_text', dataType: DataTypes.String, type: 'log' },
op: '=',
value: 'ERROR',
},
],
};
describe('Pipeline FilterInput', () => {
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 onValuesChange={onValuesChange}>
{filterField && <FilterInput fieldData={filterField} />}
</Form>,
);
const { onChange } = jest.mocked(QueryBuilderSearchV2).mock.calls[0][0];
act(() => onChange(v5Filter));
expect(
onValuesChange.mock.lastCall?.[0].filter.items.map((item) => [
item.key?.key,
item.key?.type,
]),
).toStrictEqual([
['http.method', 'tag'],
['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

@@ -4,7 +4,6 @@ import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
import QueryBuilderSearchV2 from 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2';
import isEqual from 'lodash-es/isEqual';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { toLegacyLogsFilter } from 'utils/fieldContext';
import { ProcessorFormField } from '../../../AddNewProcessor/config';
import { formValidationRules } from '../../../config';
@@ -23,10 +22,9 @@ function TagFilterInput({
}
const onQueryChange = (newValue: TagFilter): void => {
const legacyValue = toLegacyLogsFilter(newValue);
// Avoid unnecessary onChange calls
if (!isEqual(legacyValue, query.filters)) {
onChange(legacyValue);
if (!isEqual(newValue, query.filters)) {
onChange(newValue);
}
};

View File

@@ -1,64 +0,0 @@
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

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

View File

@@ -1,63 +0,0 @@
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 { ENTITY_VERSION_V5 } from 'constants/app';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import {
initialFilters,
initialQueriesMap,
@@ -34,26 +34,18 @@ function LogsCountInInterval({
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: timeInterval,
},
ENTITY_VERSION_V5,
DEFAULT_ENTITY_VERSION,
);
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"
data-testid="pipeline-filter-preview-count"
>
<div className="logs-filter-preview-matched-logs-count">
{count} matches in
</div>
);

View File

@@ -4,7 +4,6 @@ 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';
@@ -30,8 +29,6 @@ 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 { ENTITY_VERSION_V5 } from 'constants/app';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import {
initialFilters,
initialQueriesMap,
@@ -50,7 +50,7 @@ const useSampleLogs = ({
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: timeInterval,
},
ENTITY_VERSION_V5,
DEFAULT_ENTITY_VERSION,
);
const { isFetching: isLoading, data } = response;

View File

@@ -10,6 +10,7 @@ import {
userEvent,
waitFor,
} from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { pipelineApiResponseMockData } from '../mocks/pipeline';
import PipelineListsView from '../PipelineListsView';
@@ -84,7 +85,7 @@ jest.mock('providers/preferences/sync/usePreferenceSync', () => ({
}));
const BASE_URL = ENVIRONMENT.baseURL;
const fieldKeysURL = `${BASE_URL}/api/v1/fields/keys`;
const attributeKeysURL = `${BASE_URL}/api/v3/filter_suggestions`;
describe('PipelinePage container test', () => {
beforeAll(() => {
@@ -338,41 +339,42 @@ describe('PipelinePage container test', () => {
expect(screen.queryAllByText('source = nginx')).toHaveLength(2);
server.use(
rest.get(fieldKeysURL, (_req, res, ctx) =>
rest.get(attributeKeysURL, (_req, res, ctx) =>
res(
ctx.status(200),
ctx.json({
status: 'success',
data: {
complete: true,
keys: {
otelServiceName: [
{
name: 'otelServiceName',
fieldContext: 'attribute',
fieldDataType: 'string',
},
],
'service.name': [
{
name: 'service.name',
fieldContext: 'resource',
fieldDataType: 'string',
},
{
name: 'service.name',
fieldContext: 'attribute',
fieldDataType: 'string',
},
],
'service.instance.id': [
{
name: 'service.instance.id',
fieldContext: 'resource',
fieldDataType: 'string',
},
],
},
attributes: [
{
key: 'otelServiceName',
dataType: DataTypes.String,
type: 'tag',
isColumn: false,
isJSON: false,
},
{
key: 'service.name',
dataType: DataTypes.String,
type: 'resource',
isColumn: false,
isJSON: false,
},
{
key: 'service.instance.id',
dataType: DataTypes.String,
type: 'resource',
isColumn: false,
isJSON: false,
},
{
key: 'service.name',
dataType: DataTypes.String,
type: 'tag',
isColumn: false,
isJSON: false,
},
],
},
}),
),

View File

@@ -10,9 +10,9 @@ import {
} from 'react';
import { type RefSelectProps, Select, Spin } from 'antd';
import { Pill } from '@signozhq/ui/pill';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import cx from 'classnames';
import {
DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY,
OperatorConfigKeys,
OPERATORS,
QUERY_BUILDER_OPERATORS_BY_TYPES,
@@ -22,14 +22,23 @@ import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { LogsExplorerShortcuts } from 'constants/shortcuts/logsExplorerShortcuts';
import { useDynamicVariableSuggestions } from 'hooks/dashboard/useDynamicVariableSuggestions';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
import { useGetAggregateValues } from 'hooks/queryBuilder/useGetAggregateValues';
import { useGetAttributeSuggestions } from 'hooks/queryBuilder/useGetAttributeSuggestions';
import { validationMapper } from 'hooks/queryBuilder/useIsValidTag';
import { operatorTypeMapper } from 'hooks/queryBuilder/useOperatorType';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useRunQueryWithFilterItems } from 'hooks/queryBuilder/useRunQueryWithFilterItems';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import { useFieldValuesSuggestion } from 'hooks/querySuggestions/useFieldValuesSuggestion';
import useDebounceValue from 'hooks/useDebounce';
import { isArray, isEmpty, isEqual, isObject, isUndefined } from 'lodash-es';
import {
cloneDeep,
isArray,
isEmpty,
isEqual,
isObject,
isUndefined,
unset,
} from 'lodash-es';
import { ChevronDown, ChevronUp } from '@signozhq/icons';
import {
BaseAutocompleteData,
@@ -39,13 +48,7 @@ import {
IBuilderQuery,
TagFilter,
} from 'types/api/queryBuilder/queryBuilderData';
import {
DATA_SOURCE_TO_SIGNAL,
DataSource,
QUERY_SOURCE_TO_FIELD_SOURCE,
} from 'types/common/queryBuilder';
import { attributeTypeToFieldContext } from 'utils/fieldContext';
import { getValuesForDataType } from 'utils/fieldValues';
import { DataSource } from 'types/common/queryBuilder';
import { useSelectPopupContainer } from 'utils/selectPopupContainer';
import { v4 as uuid } from 'uuid';
@@ -58,8 +61,7 @@ import {
getTagToken,
isInNInOperator,
} from './utils';
import { toAttributeKey } from '../GroupByFilter/utils';
import { filterByOperatorConfig, getMetricNameForQuery } from '../utils';
import { filterByOperatorConfig } from '../utils';
import QueryBuilderSearchDropdown from './QueryBuilderSearchDropdown';
import SpanScopeSelector from './SpanScopeSelector';
import Suggestions from './Suggestions';
@@ -73,8 +75,6 @@ export interface ITag {
value: (string | number | boolean)[] | string | number | boolean;
}
const SPAN_SEARCH_SCOPE_KEYS = ['isRoot', 'isEntryPoint'];
interface CustomTagProps {
label: React.ReactNode;
value: string;
@@ -186,14 +186,69 @@ function QueryBuilderSearchV2(
[query.dataSource],
);
const debouncedKeySearchText = useDebounceValue(
searchValue?.split(' ')[0] ?? '',
DEBOUNCE_DELAY,
const memoizedSearchParams = useMemo(
() => [
searchValue,
query.dataSource,
query.aggregateOperator,
query.aggregateAttribute?.key,
],
[
searchValue,
query.dataSource,
query.aggregateOperator,
query.aggregateAttribute?.key,
],
);
const valueSearchText = isArray(currentFilterItem?.value)
? String(currentFilterItem?.value?.[currentFilterItem.value.length - 1] ?? '')
: currentFilterItem?.value?.toString() || '';
const queryFiltersWithoutId = useMemo(
() => ({
...query.filters,
items: query.filters?.items.map((item) => {
const filterWithoutId = cloneDeep(item);
unset(filterWithoutId, 'id');
return filterWithoutId;
}),
}),
[query.filters],
);
const memoizedSuggestionsParams = useMemo(
() => [searchValue, query.dataSource, queryFiltersWithoutId],
[query.dataSource, queryFiltersWithoutId, searchValue],
);
const memoizedValueParams = useMemo(
() => [
query.aggregateOperator,
query.dataSource,
query.aggregateAttribute?.key,
currentFilterItem?.key?.key || '',
currentFilterItem?.key?.dataType,
currentFilterItem?.key?.type ?? '',
isArray(currentFilterItem?.value)
? currentFilterItem?.value?.[currentFilterItem.value.length - 1]
: currentFilterItem?.value,
],
[
query.aggregateOperator,
query.dataSource,
query.aggregateAttribute?.key,
currentFilterItem?.key?.key,
currentFilterItem?.key?.dataType,
currentFilterItem?.key?.type,
currentFilterItem?.value,
],
);
const searchParams = useDebounceValue(memoizedSearchParams, DEBOUNCE_DELAY);
const valueParams = useDebounceValue(memoizedValueParams, DEBOUNCE_DELAY);
const suggestionsParams = useDebounceValue(
memoizedSuggestionsParams,
DEBOUNCE_DELAY,
);
const isQueryEnabled = useMemo(() => {
if (currentState === DropdownState.ATTRIBUTE_KEY) {
@@ -207,76 +262,53 @@ function QueryBuilderSearchV2(
const dashboardDynamicVariables = useDynamicVariableSuggestions();
const signal = DATA_SOURCE_TO_SIGNAL[query.dataSource];
const source = QUERY_SOURCE_TO_FIELD_SOURCE[query.source ?? ''];
const metricName = getMetricNameForQuery(query);
const { data: fieldKeys, isFetching } = useFieldKeysSuggestion(
const { data, isFetching } = useGetAggregateKeys(
{
signal,
source,
metricName,
fieldContext: attributeTypeToFieldContext(query.aggregateAttribute?.type),
searchText: debouncedKeySearchText,
searchText: searchValue?.split(' ')[0],
dataSource: query.dataSource,
aggregateOperator: query.aggregateOperator || '',
aggregateAttribute: query.aggregateAttribute?.key || '',
tagType: query.aggregateAttribute?.type ?? null,
},
query.builderQueryType,
{
enabled: isQueryEnabled && !hardcodedAttributeKeys,
keepPreviousData: true,
queryKey: [searchParams],
enabled: isQueryEnabled && !isLogsDataSource && !hardcodedAttributeKeys,
},
);
// The legacy traces builder checks `exists` on the column only for keys marked as columns.
// Body JSON keys come back as bare paths, which the legacy builders read as top-level fields,
// and the span search scope selectors are not columns the legacy filter builder can read.
const attributeKeys = useMemo(
() =>
(fieldKeys ?? [])
.filter(
(fieldKey) =>
fieldKey.fieldContext !== TelemetrytypesFieldContextDTO.body &&
!(
fieldKey.fieldContext === TelemetrytypesFieldContextDTO.span &&
SPAN_SEARCH_SCOPE_KEYS.includes(fieldKey.name)
),
)
.map((fieldKey) => ({
...toAttributeKey(fieldKey),
isColumn:
fieldKey.fieldContext === TelemetrytypesFieldContextDTO.span ||
fieldKey.fieldContext === TelemetrytypesFieldContextDTO.log,
})),
[fieldKeys],
);
const { data: suggestionsData, isFetching: isFetchingSuggestions } =
useGetAttributeSuggestions(
{
searchText: searchValue?.split(' ')[0],
dataSource: query.dataSource,
filters: query.filters || { items: [], op: 'AND' },
},
{
queryKey: [suggestionsParams],
enabled: isQueryEnabled && isLogsDataSource,
},
);
const fieldValuesConfig = useMemo(
() => ({
signal,
source,
metricName,
name: currentFilterItem?.key?.key || '',
fieldContext: attributeTypeToFieldContext(currentFilterItem?.key?.type),
searchText: valueSearchText,
}),
[
signal,
source,
metricName,
currentFilterItem?.key?.key,
currentFilterItem?.key?.type,
valueSearchText,
],
);
const debouncedFieldValuesConfig = useDebounceValue(
fieldValuesConfig,
DEBOUNCE_DELAY,
);
const { data: fieldValues, isFetching: isFetchingAttributeValues } =
useFieldValuesSuggestion(debouncedFieldValuesConfig, query.builderQueryType, {
enabled: currentState === DropdownState.ATTRIBUTE_VALUE,
});
const { data: attributeValues, isFetching: isFetchingAttributeValues } =
useGetAggregateValues(
{
aggregateOperator: query.aggregateOperator || '',
dataSource: query.dataSource,
aggregateAttribute: query.aggregateAttribute?.key || '',
attributeKey: currentFilterItem?.key?.key || '',
filterAttributeKeyDataType:
currentFilterItem?.key?.dataType ?? DataTypes.EMPTY,
tagType: currentFilterItem?.key?.type ?? '',
searchText: isArray(currentFilterItem?.value)
? String(currentFilterItem?.value?.[currentFilterItem.value.length - 1]) ||
''
: currentFilterItem?.value?.toString() || '',
},
{
enabled: currentState === DropdownState.ATTRIBUTE_VALUE,
queryKey: [valueParams],
},
);
const handleDropdownSelect = useCallback(
(value: string) => {
@@ -501,14 +533,16 @@ function QueryBuilderSearchV2(
if (tagKey && isUndefined(currentFilterItem?.key)) {
let currentRunningAttributeKey;
const isSuggestedKeyInAutocomplete =
isLogsDataSource &&
attributeKeys.some((value) => value.key === tagKey.split(' ')[0]);
if (isSuggestedKeyInAutocomplete) {
const allAttributesMatchingTheKey = attributeKeys.filter(
suggestionsData?.payload?.attributes?.some(
(value) => value.key === tagKey.split(' ')[0],
);
if (isSuggestedKeyInAutocomplete) {
const allAttributesMatchingTheKey =
suggestionsData?.payload?.attributes?.filter(
(value) => value.key === tagKey.split(' ')[0],
) || [];
if (allAttributesMatchingTheKey?.length === 1) {
[currentRunningAttributeKey] = allAttributesMatchingTheKey;
}
@@ -614,10 +648,9 @@ function QueryBuilderSearchV2(
currentFilterItem,
currentFilterItem?.key,
currentFilterItem?.op,
attributeKeys,
isLogsDataSource,
suggestionsData?.payload?.attributes,
searchValue,
isFetching,
isFetchingSuggestions,
currentState,
]);
@@ -629,7 +662,9 @@ function QueryBuilderSearchV2(
// add the user typed option in the dropdown to select that and move ahead irrespective of the matches and all
setDropdownOptions([
...(!isEmpty(tagKey) &&
!attributeKeys.some((val) => isEqual(val.key, tagKey))
!suggestionsData?.payload?.attributes?.some((val) =>
isEqual(val.key, tagKey),
)
? [
{
label: tagKey,
@@ -641,10 +676,10 @@ function QueryBuilderSearchV2(
},
]
: []),
...attributeKeys.map((key) => ({
...(suggestionsData?.payload?.attributes?.map((key) => ({
label: key.key,
value: key,
})),
})) || []),
]);
} else if (hardcodedAttributeKeys) {
const filteredKeys = hardcodedAttributeKeys.filter((key) =>
@@ -662,7 +697,7 @@ function QueryBuilderSearchV2(
setDropdownOptions([
// Add user typed option if it doesn't exist in the payload
...(tagKey.trim().length > 0 &&
!attributeKeys.some((val) => val.key === tagKey)
!data?.payload?.attributeKeys?.some((val) => val.key === tagKey)
? [
{
label: tagKey,
@@ -675,10 +710,10 @@ function QueryBuilderSearchV2(
]
: []),
// Map existing attribute keys from payload
...attributeKeys.map((key) => ({
...(data?.payload?.attributeKeys?.map((key) => ({
label: key.key,
value: key,
})),
})) || []),
]);
}
}
@@ -743,10 +778,10 @@ function QueryBuilderSearchV2(
values.push(tagValue);
}
if (fieldValues) {
values.push(
...getValuesForDataType(fieldValues, currentFilterItem?.key?.dataType),
);
if (attributeValues?.payload) {
const dataType = currentFilterItem?.key?.dataType || DataTypes.String;
const key = DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY[dataType];
values.push(...(attributeValues?.payload?.[key] || []));
// here we want to suggest the variable name matching with the key here, we will go over the dynamic variables for the keys
const variableName = dashboardDynamicVariables.find(
@@ -770,12 +805,13 @@ function QueryBuilderSearchV2(
}
}, [
hardcodedAttributeKeys,
fieldValues,
attributeValues?.payload,
currentFilterItem?.key?.dataType,
currentState,
attributeKeys,
data?.payload?.attributeKeys,
isLogsDataSource,
searchValue,
suggestionsData?.payload?.attributes,
operatorConfigKey,
currentFilterItem?.key?.key,
dashboardDynamicVariables,
@@ -844,8 +880,8 @@ function QueryBuilderSearchV2(
}, [deregisterShortcut, isLastQuery, registerShortcut]);
const loading = useMemo(
() => isFetching || isFetchingAttributeValues,
[isFetching, isFetchingAttributeValues],
() => isFetching || isFetchingAttributeValues || isFetchingSuggestions,
[isFetching, isFetchingAttributeValues, isFetchingSuggestions],
);
const isMetricsDataSource = useMemo(
@@ -955,7 +991,7 @@ function QueryBuilderSearchV2(
setTags((prev) => [...prev, ...(val.items as ITag[])]);
}}
searchValue={searchValue}
exampleQueries={[]}
exampleQueries={suggestionsData?.payload?.example_queries || []}
tags={tags}
currentFilterItem={currentFilterItem}
isLogsDataSource={isLogsDataSource}

View File

@@ -1,23 +1,13 @@
import { QueryClient, QueryClientProvider } from 'react-query';
import {
render,
RenderResult,
screen,
waitFor,
within,
} from '@testing-library/react';
import { render, RenderResult, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
initialQueriesMap,
initialQueryBuilderFormValues,
} from 'constants/queryBuilder';
import { TelemetrytypesTelemetryFieldValuesDTO } from 'api/generated/services/sigNoz.schemas';
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import { useFieldValuesSuggestion } from 'hooks/querySuggestions/useFieldValuesSuggestion';
import { QueryBuilderContext } from 'providers/QueryBuilder';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { FieldDataType, TelemetryFieldKey } from 'types/api/v5/queryRange';
import { DataSource } from 'types/common/queryBuilder';
import QueryBuilderSearchV2 from '../QueryBuilderSearchV2';
@@ -98,34 +88,57 @@ const renderWithContext = (props = {}): RenderResult => {
const getSearchCombobox = (): HTMLElement =>
within(screen.getByTestId('qb-search-select')).getByRole('combobox');
const mockFieldKeys: TelemetryFieldKey[] = [
{ name: 'http.status', fieldContext: 'attribute', fieldDataType: 'string' },
{ name: 'service.name', fieldContext: 'attribute', fieldDataType: 'string' },
{ name: 'name', fieldContext: 'span', fieldDataType: 'string' },
{ name: 'user.id', fieldContext: 'body', fieldDataType: 'string' },
{ name: 'isRoot', fieldContext: 'span', fieldDataType: 'bool' },
{
name: 'unmapped.attribute',
fieldContext: 'attribute',
fieldDataType: 'not-a-real-data-type' as FieldDataType,
},
];
// Constants to fix linter errors
const TYPE_TAG = 'tag';
const IS_COLUMN_FALSE = false;
const IS_JSON_FALSE = false;
jest.mock('hooks/querySuggestions/useFieldKeysSuggestion', () => ({
useFieldKeysSuggestion: jest.fn(() => ({
data: mockFieldKeys,
const mockAggregateKeysData = {
payload: {
attributeKeys: [
{
key: 'http.status',
dataType: DataTypes.String,
type: TYPE_TAG,
id: 'http.status--string--tag--false',
},
{
key: 'service.name',
dataType: DataTypes.String,
type: TYPE_TAG,
isColumn: IS_COLUMN_FALSE,
isJSON: IS_JSON_FALSE,
id: 'service.name--string--tag--false',
},
{
key: 'unmapped.attribute',
dataType: 'not-a-real-data-type' as unknown as DataTypes,
type: TYPE_TAG,
isColumn: IS_COLUMN_FALSE,
isJSON: IS_JSON_FALSE,
id: 'unmapped.attribute--String--tag--false',
},
],
},
};
jest.mock('hooks/queryBuilder/useGetAggregateKeys', () => ({
useGetAggregateKeys: jest.fn(() => ({
data: mockAggregateKeysData,
isFetching: false,
})),
}));
const mockFieldValues: TelemetrytypesTelemetryFieldValuesDTO = {
stringValues: ['200', '404', '500'],
numberValues: [200, 404, 500],
const mockAggregateValuesData = {
payload: {
stringAttributeValues: ['200', '404', '500'],
numberAttributeValues: [200, 404, 500],
},
};
jest.mock('hooks/querySuggestions/useFieldValuesSuggestion', () => ({
useFieldValuesSuggestion: jest.fn(() => ({
data: mockFieldValues,
jest.mock('hooks/queryBuilder/useGetAggregateValues', () => ({
useGetAggregateValues: jest.fn(() => ({
data: mockAggregateValuesData,
isFetching: false,
})),
}));
@@ -183,11 +196,7 @@ describe('Suggestion Key -> Operator -> Value Flow', () => {
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({
key: 'http.status',
type: 'attribute',
dataType: 'string',
}),
key: expect.objectContaining({ key: 'http.status' }),
op: '=',
value: '200',
}),
@@ -283,7 +292,7 @@ describe('Filter chips', () => {
key: {
key: 'http.status',
dataType: DataTypes.String,
type: 'tag',
type: TYPE_TAG,
id: 'http.status--string--tag--false',
},
op: '=',
@@ -323,87 +332,3 @@ describe('Filter chips', () => {
expect(getSearchCombobox()).toHaveDisplayValue(CHIP_LABEL);
});
});
describe('Key fetch context', () => {
it('limits keys to the aggregate attribute context, as the resource filter needs', () => {
renderWithContext({
query: {
...defaultProps.query,
aggregateAttribute: {
...defaultProps.query.aggregateAttribute,
type: 'resource',
},
},
});
expect(useFieldKeysSuggestion).toHaveBeenLastCalledWith(
expect.objectContaining({ fieldContext: 'resource' }),
undefined,
expect.anything(),
);
});
it('fetches keys from every context when the aggregate attribute has no type', () => {
renderWithContext();
expect(useFieldKeysSuggestion).toHaveBeenLastCalledWith(
expect.objectContaining({ fieldContext: undefined }),
undefined,
expect.anything(),
);
});
});
describe('Keys the legacy filter builders cannot read', () => {
it('does not suggest body JSON keys or span search scope selectors', async () => {
const user = userEvent.setup({ delay: null });
renderWithContext();
const combobox = getSearchCombobox();
await user.click(combobox);
await user.type(combobox, 'user');
await screen.findByRole('listbox');
await expect(screen.findByText('http.status')).resolves.toBeInTheDocument();
expect(screen.queryByText('user.id')).not.toBeInTheDocument();
expect(screen.queryByText('isRoot')).not.toBeInTheDocument();
});
});
describe('Span field keys', () => {
it('marks span fields as columns and looks up their values in the span context', async () => {
const user = userEvent.setup({ delay: null });
renderWithContext();
const combobox = getSearchCombobox();
await user.click(combobox);
await user.type(combobox, 'nam');
await screen.findByRole('listbox');
await user.click(await screen.findByText('name'));
await user.click(screen.getByText('='));
await waitFor(() =>
expect(jest.mocked(useFieldValuesSuggestion)).toHaveBeenLastCalledWith(
expect.objectContaining({ name: 'name', fieldContext: 'span' }),
undefined,
expect.anything(),
),
);
await user.click(screen.getByText('200'));
expect(mockOnChange).toHaveBeenLastCalledWith(
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({
key: 'name',
type: 'span',
isColumn: true,
}),
}),
]),
}),
);
});
});

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

View File

@@ -150,21 +150,6 @@ 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,6 +526,14 @@ 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;
@@ -608,6 +616,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
isAdmin,
isChatSupportEnabled,
isPremiumSupportEnabled,
isCloudUser,

View File

@@ -1,51 +0,0 @@
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

@@ -32,7 +32,6 @@ export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityP
PIE: false,
HISTOGRAM: false,
HEATMAP: false,
GEO_MAP: false,
TEXT: false,
EMPTY_WIDGET: false,
};

View File

@@ -24,5 +24,4 @@ export const PanelTypeVsPanelWrapper = {
[PANEL_TYPES.HISTOGRAM]: HistogramPanel,
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
};

View File

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

View File

@@ -85,25 +85,6 @@ 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({
@@ -138,10 +119,6 @@ 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,8 +14,6 @@ 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,11 +13,6 @@ export default {
type: 'metaresource',
allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
},
{
kind: 'factor-password',
type: 'metaresource',
allowedVerbs: ['create', 'list', 'read'],
},
{
kind: 'license',
type: 'metaresource',
@@ -98,35 +93,16 @@ 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', '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'],
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'],
},
},
} as const;

View File

@@ -12,9 +12,3 @@ 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,6 +17,12 @@ 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

@@ -1,29 +0,0 @@
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

@@ -17,7 +17,6 @@ export type PartialPanelTypes = {
[PANEL_TYPES.SCATTER]: 'scatter';
[PANEL_TYPES.HISTOGRAM]: 'histogram';
[PANEL_TYPES.HEATMAP]: 'heatmap';
[PANEL_TYPES.GEO_MAP]: 'geo_map';
};
export type BuilderField = keyof IBuilderQuery;
@@ -153,7 +152,6 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.TABLE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.GEO_MAP]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.VALUE]: bySource(SINGLE_VALUE, SINGLE_VALUE_METRICS),
[PANEL_TYPES.LIST]: bySource(RAW_ROWS, RAW_ROWS_METRICS),
};

View File

@@ -72,32 +72,3 @@
var(--muted-foreground) 2px 3px
);
}
.vertical {
display: flex;
gap: 10px;
height: 100%;
min-height: 0;
.track {
flex: 0 0 8px;
width: 8px;
height: auto;
}
.marker {
top: auto;
right: -3px;
left: -3px;
width: auto;
height: 2px;
transform: translateY(1px);
}
}
.scale {
display: flex;
flex-direction: column;
justify-content: space-between;
min-width: 0;
}

View File

@@ -14,8 +14,6 @@ export interface ColorBarProps {
label?: string;
/** Keys the one state a ramp cannot express: a hatched data gap. */
showNoDataKey?: boolean;
/** Vertical runs low to high from the bottom, with labels to the right. */
orientation?: 'horizontal' | 'vertical';
'data-testid'?: string;
}
@@ -27,10 +25,8 @@ export default function ColorBar({
markerPosition = null,
label,
showNoDataKey = false,
orientation = 'horizontal',
'data-testid': testId = 'color-bar',
}: ColorBarProps): JSX.Element | null {
const isVertical = orientation === 'vertical';
const gradient = useMemo(() => {
if (ramp.length === 0) {
return undefined;
@@ -43,8 +39,8 @@ export default function ColorBar({
const to = ((index + 1) / ramp.length) * 100;
return [`${color} ${from}%`, `${color} ${to}%`];
});
return `linear-gradient(to ${isVertical ? 'top' : 'right'}, ${stops.join(', ')})`;
}, [ramp, isVertical]);
return `linear-gradient(to right, ${stops.join(', ')})`;
}, [ramp]);
if (gradient === undefined) {
return null;
@@ -53,26 +49,6 @@ export default function ColorBar({
const clampedMarker =
markerPosition === null ? null : Math.min(Math.max(markerPosition, 0), 1);
if (isVertical) {
return (
<div className={Styles.vertical} data-testid={testId}>
<div className={Styles.track} style={{ background: gradient }}>
{clampedMarker !== null && (
<span
className={Styles.marker}
style={{ bottom: `${clampedMarker * 100}%` }}
data-testid={`${testId}-marker`}
/>
)}
</div>
<div className={Styles.scale}>
<span className={Styles.label}>{maxLabel}</span>
<span className={Styles.label}>{minLabel}</span>
</div>
</div>
);
}
return (
<div className={Styles.container} data-testid={testId}>
{label && <span className={Styles.caption}>{label}</span>}

View File

@@ -1,4 +1,4 @@
import { render, screen } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import ColorBar from '../ColorBar';
@@ -35,13 +35,12 @@ describe('ColorBar', () => {
});
it('clamps a marker outside the ramp to its ends', () => {
const { unmount } = render(
const { rerender } = render(
<ColorBar ramp={RAMP} minLabel="0" maxLabel="10" markerPosition={-2} />,
);
expect(screen.getByTestId('color-bar-marker')).toHaveStyle({ left: '0%' });
unmount();
render(
rerender(
<ColorBar ramp={RAMP} minLabel="0" maxLabel="10" markerPosition={4} />,
);
expect(screen.getByTestId('color-bar-marker')).toHaveStyle({ left: '100%' });
@@ -83,20 +82,4 @@ describe('ColorBar', () => {
'linear-gradient(to right, #111111 0%, #111111 50%, #dddddd 50%, #dddddd 100%)',
});
});
it('runs low to high from the bottom when vertical', () => {
render(
<ColorBar
ramp={['#000', '#fff']}
minLabel="0.18%"
maxLabel="14.2%"
markerPosition={0.25}
orientation="vertical"
/>,
);
const labels = screen.getAllByText(/%$/).map((label) => label.textContent);
expect(labels).toStrictEqual(['14.2%', '0.18%']);
expect(screen.getByTestId('color-bar-marker')).toHaveStyle({ bottom: '25%' });
});
});

View File

@@ -0,0 +1,290 @@
import { Color } from '@signozhq/design-tokens';
import {
clampColorSteps,
createHeatmapColorResolver,
DEFAULT_COLOR_STEPS,
DEFAULT_HEATMAP_COLORS,
getMaxCount,
getSmallestPositiveCount,
MAX_COLOR_STEPS,
MIN_OPACITY_ALPHA,
normalizeCount,
resolveCountDomain,
} from '../colorScale';
import { HeatmapColorMode, HeatmapColorScale } from '../types';
const SERIES_COLOR = '#4e74f8';
describe('getMaxCount', () => {
it('ignores null cells', () => {
expect(
getMaxCount([
[1, null, 9],
[null, 4],
]),
).toBe(9);
});
it('returns 0 for an empty or all-null grid', () => {
expect(getMaxCount([])).toBe(0);
expect(getMaxCount([[null, null]])).toBe(0);
});
it('ignores non-finite counts', () => {
expect(getMaxCount([[3, Number.POSITIVE_INFINITY, Number.NaN]])).toBe(3);
});
});
describe('getSmallestPositiveCount', () => {
it('ignores nulls, zeros and non-finite counts', () => {
expect(
getSmallestPositiveCount([
[0, null, 4],
[Number.NaN, 2, -3],
]),
).toBe(2);
});
it('returns null when nothing is above zero', () => {
expect(getSmallestPositiveCount([[0, null]])).toBeNull();
});
});
describe('resolveCountDomain', () => {
it('floors at 0 on auto so a zero count sits at the bottom of the scale', () => {
expect(
resolveCountDomain({ minCount: null, maxCount: null }, [[5, 20]]),
).toStrictEqual({
min: 0,
max: 20,
logFloor: 5,
});
});
it('honours explicit clamps', () => {
expect(
resolveCountDomain({ minCount: 10, maxCount: 100 }, [[5, 20]]),
).toStrictEqual({
min: 10,
max: 100,
logFloor: 5,
});
});
it('collapses a max at or below min', () => {
expect(
resolveCountDomain({ minCount: 50, maxCount: 10 }, [[5]]),
).toStrictEqual({
min: 50,
max: 50,
logFloor: 5,
});
});
it('takes the log floor from the smallest positive count, below 1 included', () => {
expect(
resolveCountDomain({ minCount: null, maxCount: null }, [[0, 0.02, 0.8]])
.logFloor,
).toBeCloseTo(0.02, 6);
});
it('keeps the log floor within MAX_LOG_DECADES of the max', () => {
expect(
resolveCountDomain({ minCount: null, maxCount: null }, [[1, 1e9]]).logFloor,
).toBe(1e3);
});
it('falls back to a floor of 1 for a grid without a positive count', () => {
expect(
resolveCountDomain({ minCount: null, maxCount: null }, [[null, 0]]).logFloor,
).toBe(1);
});
});
describe('normalizeCount', () => {
const domain = { min: 0, max: 1000, logFloor: 1 };
it('spreads low counts on a log scale where a linear one washes them out', () => {
const log = (count: number): number =>
normalizeCount({ count, domain, scale: HeatmapColorScale.Log });
expect(log(10)).toBeCloseTo(1 / 3, 5);
expect(log(20)).toBeCloseTo(Math.log10(20) / 3, 5);
expect(
normalizeCount({ count: 10, domain, scale: HeatmapColorScale.Linear }),
).toBeCloseTo(0.01, 5);
});
it('puts 0 and 1 at the bottom of a log scale', () => {
expect(
normalizeCount({ count: 0, domain, scale: HeatmapColorScale.Log }),
).toBe(0);
expect(
normalizeCount({ count: 1, domain, scale: HeatmapColorScale.Log }),
).toBe(0);
});
it('reaches the top of the scale at max on every scale', () => {
[
HeatmapColorScale.Log,
HeatmapColorScale.Sqrt,
HeatmapColorScale.Linear,
].forEach((scale) => {
expect(normalizeCount({ count: 1000, domain, scale })).toBeCloseTo(1, 6);
});
});
it('takes the square root of the linear position on a sqrt scale', () => {
expect(
normalizeCount({
count: 250,
domain: { min: 0, max: 1000, logFloor: 1 },
scale: HeatmapColorScale.Sqrt,
}),
).toBeCloseTo(0.5, 6);
});
it('clamps counts outside the domain', () => {
const scale = HeatmapColorScale.Linear;
expect(normalizeCount({ count: -5, domain, scale })).toBe(0);
expect(normalizeCount({ count: 5000, domain, scale })).toBe(1);
});
it('returns the bottom of the scale when min equals max', () => {
expect(
normalizeCount({
count: 7,
domain: { min: 7, max: 7, logFloor: 1 },
scale: HeatmapColorScale.Log,
}),
).toBe(0);
});
it('spreads a log domain that sits entirely below a count of 1', () => {
const fractional = { min: 0, max: 1, logFloor: 0.001 };
const log = (count: number): number =>
normalizeCount({
count,
domain: fractional,
scale: HeatmapColorScale.Log,
});
expect(log(0.001)).toBe(0);
expect(log(0.1)).toBeCloseTo(2 / 3, 5);
expect(log(1)).toBeCloseTo(1, 6);
});
it('reads a log scale linearly when the floor reaches the top of the domain', () => {
const domainAtFloor = { min: 0, max: 1, logFloor: 1 };
expect(
normalizeCount({
count: 1,
domain: domainAtFloor,
scale: HeatmapColorScale.Log,
}),
).toBe(1);
expect(
normalizeCount({
count: 0.5,
domain: domainAtFloor,
scale: HeatmapColorScale.Log,
}),
).toBe(0.5);
});
});
describe('clampColorSteps', () => {
it('clamps to the supported range', () => {
expect(clampColorSteps(1)).toBe(2);
expect(clampColorSteps(500)).toBe(MAX_COLOR_STEPS);
expect(clampColorSteps(32)).toBe(32);
});
it('falls back to the default for a non-finite value', () => {
expect(clampColorSteps(Number.NaN)).toBe(DEFAULT_COLOR_STEPS);
});
});
describe('createHeatmapColorResolver', () => {
const build = (
overrides: Partial<typeof DEFAULT_HEATMAP_COLORS> = {},
isDarkMode = true,
): ReturnType<typeof createHeatmapColorResolver> =>
createHeatmapColorResolver({
options: { ...DEFAULT_HEATMAP_COLORS, ...overrides },
domain: { min: 0, max: 1000, logFloor: 1 },
isDarkMode,
seriesColor: SERIES_COLOR,
});
it('leaves null cells uncoloured so they can be hatched', () => {
const resolver = build();
expect(resolver.colorFor(null)).toBeNull();
expect(resolver.positionOf(null)).toBeNull();
});
it('recedes a zero count into the surface, not the null treatment', () => {
const dark = build();
const light = build({}, false);
expect(dark.colorFor(0)).toBe(Color.BG_INK_500);
expect(light.colorFor(0)).toBe(Color.BG_VANILLA_100);
});
it('keeps the bottom of the ramp for the smallest count that occurred', () => {
const resolver = build();
// Zero and the floor both sit at position 0; only the floor takes a colour.
expect(resolver.colorFor(1)).toBe(resolver.ramp[0]);
});
it('colours zero off the ramp once an explicit minimum lifts it off the bottom', () => {
const resolver = createHeatmapColorResolver({
options: { ...DEFAULT_HEATMAP_COLORS, minCount: 5 },
domain: { min: 5, max: 1000, logFloor: 5 },
isDarkMode: true,
seriesColor: SERIES_COLOR,
});
expect(resolver.colorFor(0)).toBe(resolver.ramp[0]);
});
it('emits one ramp entry per step', () => {
expect(build({ steps: 8 }).ramp).toHaveLength(8);
});
it('maps the max count to the top of the ramp', () => {
const resolver = build({ steps: 8 });
expect(resolver.colorFor(1000)).toBe(resolver.ramp[7]);
});
it('picks different stops per theme so low counts stay near the surface', () => {
expect(build({}, true).ramp[0]).not.toBe(build({}, false).ramp[0]);
});
it('varies alpha in opacity mode, never below the visibility floor', () => {
const resolver = build({ mode: HeatmapColorMode.Opacity, steps: 4 });
expect(resolver.ramp[0]).toBe(`rgba(78, 116, 248, ${MIN_OPACITY_ALPHA})`);
// `color` drops the alpha channel from the string once it reaches 1.
expect(resolver.ramp[3]).toBe('rgb(78, 116, 248)');
});
it('prefers an explicit opacity fill over the series colour', () => {
const resolver = build({
mode: HeatmapColorMode.Opacity,
fill: '#e5484d',
steps: 2,
});
expect(resolver.ramp[1]).toBe('rgb(229, 72, 77)');
});
it('reports the domain it applied', () => {
expect(build().domain).toStrictEqual({ min: 0, max: 1000, logFloor: 1 });
});
});

View File

@@ -1,6 +1,6 @@
import type uPlot from 'uplot';
import { DEFAULT_COLOR_RAMP_OPTIONS } from 'lib/visualization/colorRamp/colorScale';
import { DEFAULT_HEATMAP_COLORS } from '../colorScale';
import { resolveHeatmapYAxis } from '../geometry';
import { createHeatmapHooks } from '../heatmapPlugin';
import { HeatmapAxisScale, HeatmapCell } from '../types';
@@ -103,7 +103,7 @@ function createHooks(
return createHeatmapHooks({
yAxis: Y_AXIS,
step: STEP,
colors: DEFAULT_COLOR_RAMP_OPTIONS,
colors: DEFAULT_HEATMAP_COLORS,
isDarkMode: true,
seriesColor: '#4e74f8',
dimOnHover,

View File

@@ -1,7 +1,7 @@
import { getPaletteStops } from '../palettes';
import { ColorRampPalette } from '../types';
import { HeatmapColorPalette } from '../types';
const ALL_PALETTES = Object.values(ColorRampPalette);
const ALL_PALETTES = Object.values(HeatmapColorPalette);
/** Perceived brightness, good enough to tell a ramp's ends apart. */
function luminance(hex: string): number {
@@ -49,14 +49,14 @@ describe('getPaletteStops', () => {
});
it('never mutates the stored ramp when reversing it', () => {
const first = getPaletteStops(ColorRampPalette.Lava, false);
const second = getPaletteStops(ColorRampPalette.Lava, false);
const first = getPaletteStops(HeatmapColorPalette.Lava, false);
const second = getPaletteStops(HeatmapColorPalette.Lava, false);
expect(first).toStrictEqual(second);
});
it('offers a neutral ramp for panels that already spend colour elsewhere', () => {
const stops = getPaletteStops(ColorRampPalette.Graphite, true);
const stops = getPaletteStops(HeatmapColorPalette.Graphite, true);
// Every stop is a grey: red, green and blue channels stay equal.
stops.forEach((stop) => {

View File

@@ -0,0 +1,257 @@
import { Color as DesignToken } from '@signozhq/design-tokens';
import Color from 'color';
import { DEFAULT_HEATMAP_PALETTE, getPaletteStops } from './palettes';
import {
HeatmapColorMode,
HeatmapColorOptions,
HeatmapColorScale,
} from './types';
export const MIN_COLOR_STEPS = 2;
export const MAX_COLOR_STEPS = 128;
export const DEFAULT_COLOR_STEPS = 64;
/** Without a floor, the lowest counts read as "no data". */
export const MIN_OPACITY_ALPHA = 0.1;
/** Log's bottom when the grid holds no positive count to take it from. */
const DEFAULT_LOG_FLOOR = 1;
/** Widest span a single ramp is stretched over on a log scale. */
const MAX_LOG_DECADES = 6;
/** Used when neither an explicit fill nor a series colour is available. */
export const DEFAULT_OPACITY_FILL = DesignToken.BG_ROBIN_500;
/** Zero takes the panel surface so an empty stretch recedes, leaving the ramp's
* bottom to the smallest count that did occur — on a log scale the two collapse. */
const ZERO_FILL: Record<'dark' | 'light', string> = {
dark: DesignToken.BG_INK_500,
light: DesignToken.BG_VANILLA_100,
};
export const DEFAULT_HEATMAP_COLORS: HeatmapColorOptions = {
mode: HeatmapColorMode.Palette,
scale: HeatmapColorScale.Log,
minCount: null,
maxCount: null,
palette: DEFAULT_HEATMAP_PALETTE,
steps: DEFAULT_COLOR_STEPS,
fill: '',
};
export interface CountDomain {
min: number;
max: number;
/** Bottom decade of the log scale: the smallest count it separates from zero.
* Always positive, since log has no bottom otherwise. */
logFloor: number;
}
/** Highest count, ignoring `null`. 0 for an empty grid. */
export function getMaxCount(counts: Array<Array<number | null>>): number {
let max = 0;
for (const row of counts) {
for (const count of row) {
if (count !== null && Number.isFinite(count) && count > max) {
max = count;
}
}
}
return max;
}
/** Smallest count above zero, ignoring `null`. `null` for a grid without one. */
export function getSmallestPositiveCount(
counts: Array<Array<number | null>>,
): number | null {
let smallest: number | null = null;
for (const row of counts) {
for (const count of row) {
if (
count !== null &&
Number.isFinite(count) &&
count > 0 &&
(smallest === null || count < smallest)
) {
smallest = count;
}
}
}
return smallest;
}
/**
* The grid's own resolution: whole counts floor at 1, while a heatmap of rates or
* ratios can live entirely below it, where a fixed floor of 1 would flatten every
* cell onto the bottom colour. Capped at `MAX_LOG_DECADES` so one stray tiny cell
* cannot stretch the ramp over a range nothing else occupies.
*/
function resolveLogFloor(
counts: Array<Array<number | null>>,
max: number,
): number {
const smallest = getSmallestPositiveCount(counts) ?? DEFAULT_LOG_FLOOR;
return Math.max(smallest, max / 10 ** MAX_LOG_DECADES);
}
/** Explicit clamps win; otherwise 0 to the grid's highest count. */
export function resolveCountDomain(
options: Pick<HeatmapColorOptions, 'minCount' | 'maxCount'>,
counts: Array<Array<number | null>>,
): CountDomain {
const min = options.minCount ?? 0;
const max = options.maxCount ?? getMaxCount(counts);
const logFloor = resolveLogFloor(counts, max);
return max > min ? { min, max, logFloor } : { min, max: min, logFloor };
}
/** Position on the colour scale, 0..1. A degenerate domain collapses to 0 so an
* all-zero grid renders at the bottom rather than disappearing. */
export function normalizeCount({
count,
domain,
scale,
}: {
count: number;
domain: CountDomain;
scale: HeatmapColorScale;
}): number {
const { min, max } = domain;
if (!(max > min)) {
return 0;
}
const clamped = Math.min(Math.max(count, min), max);
if (scale === HeatmapColorScale.Log) {
// Anything at or below the floor sits at the bottom; log cannot place it.
const bottom = Math.max(min, domain.logFloor);
const logMin = Math.log10(bottom);
const logMax = Math.log10(max);
if (logMax > logMin) {
return (Math.log10(Math.max(clamped, bottom)) - logMin) / (logMax - logMin);
}
// The floor already reaches the top of the domain, so there is no span to
// spread logarithmically. Fall through rather than flatten the whole grid.
}
const linear = (clamped - min) / (max - min);
return scale === HeatmapColorScale.Sqrt ? Math.sqrt(linear) : linear;
}
export function clampColorSteps(steps: number): number {
if (!Number.isFinite(steps)) {
return DEFAULT_COLOR_STEPS;
}
return Math.min(Math.max(Math.round(steps), MIN_COLOR_STEPS), MAX_COLOR_STEPS);
}
/** Colour at `t` (0..1) along a multi-stop ramp. */
function sampleStops(stops: string[], t: number): string {
if (stops.length === 0) {
return 'transparent';
}
if (stops.length === 1) {
return stops[0];
}
const scaled = Math.min(Math.max(t, 0), 1) * (stops.length - 1);
const lower = Math.min(Math.floor(scaled), stops.length - 2);
return Color(stops[lower])
.mix(Color(stops[lower + 1]), scaled - lower)
.hex();
}
/**
* Colour the densest cells are drawn with — the palette's extreme, or the opacity
* fill at full strength. Depends only on the options, not on the data, so callers
* can read it before a grid exists.
*/
export function resolveExtremeColor({
options,
isDarkMode,
seriesColor,
}: {
options: HeatmapColorOptions;
isDarkMode: boolean;
seriesColor: string;
}): string {
if (options.mode === HeatmapColorMode.Opacity) {
return options.fill || seriesColor || DEFAULT_OPACITY_FILL;
}
const stops = getPaletteStops(options.palette, isDarkMode);
return stops[stops.length - 1] ?? DEFAULT_OPACITY_FILL;
}
export interface HeatmapColorResolver {
/** `null` for a `null` count, which must be hatched. */
colorFor: (count: number | null) => string | null;
/** 0..1, or `null` for a `null` count. */
positionOf: (count: number | null) => number | null;
/** Low to high. The colour bar renders exactly these. */
ramp: string[];
domain: CountDomain;
}
/** Palette mode walks a sequential ramp; opacity mode varies the alpha of one
* fill, so the grid matches its group's legend swatch. */
export function createHeatmapColorResolver({
options,
domain,
isDarkMode,
seriesColor,
}: {
options: HeatmapColorOptions;
domain: CountDomain;
isDarkMode: boolean;
/** Opacity-mode fill when `options.fill` is empty. */
seriesColor: string;
}): HeatmapColorResolver {
const steps = clampColorSteps(options.steps);
const positions = Array.from({ length: steps }, (_, index) =>
steps === 1 ? 0 : index / (steps - 1),
);
let ramp: string[];
if (options.mode === HeatmapColorMode.Opacity) {
const base = Color(options.fill || seriesColor || DEFAULT_OPACITY_FILL);
ramp = positions.map((t) =>
base
.alpha(MIN_OPACITY_ALPHA + t * (1 - MIN_OPACITY_ALPHA))
.rgb()
.string(),
);
} else {
const stops = getPaletteStops(options.palette, isDarkMode);
ramp = positions.map((t) => sampleStops(stops, t));
}
const positionOf = (count: number | null): number | null => {
if (count === null || !Number.isFinite(count)) {
return null;
}
return normalizeCount({ count, domain, scale: options.scale });
};
// An explicit `minCount` above zero makes it a clamped value like any other.
const zeroFill =
domain.min <= 0 ? ZERO_FILL[isDarkMode ? 'dark' : 'light'] : null;
return {
positionOf,
colorFor: (count): string | null => {
if (count === 0 && zeroFill !== null) {
return zeroFill;
}
const t = positionOf(count);
if (t === null) {
return null;
}
const index = Math.min(Math.floor(t * steps), steps - 1);
return ramp[index];
},
ramp,
domain,
};
}

View File

@@ -1,10 +1,10 @@
import uPlot from 'uplot';
import {
createColorRampResolver,
ColorRampResolver,
resolveColorDomain,
} from 'lib/visualization/colorRamp/colorScale';
createHeatmapColorResolver,
HeatmapColorResolver,
resolveCountDomain,
} from './colorScale';
import { resolveColumnIndex, resolveRowIndex } from './geometry';
import {
createHoverOverlay,
@@ -12,14 +12,13 @@ import {
showHoverOverlay,
} from './hoverOverlay';
import { createHatchPattern, drawCells, drawOverflowBoundary } from './paint';
import { HeatmapCell, HeatmapYAxis } from './types';
import { ColorRampOptions } from 'lib/visualization/colorRamp/types';
import { HeatmapCell, HeatmapColorOptions, HeatmapYAxis } from './types';
export interface HeatmapRenderOptions {
yAxis: HeatmapYAxis;
/** Column width in seconds. */
step: number;
colors: ColorRampOptions;
colors: HeatmapColorOptions;
isDarkMode: boolean;
/** Opacity-mode fill when `colors.fill` is empty. */
seriesColor: string;
@@ -59,15 +58,15 @@ export function createHeatmapHooks({
// config-build time. Resolving lazily keeps a refetch on uPlot's `setData` path
// rather than forcing a rebuild.
let cachedData: uPlot.AlignedData | null = null;
let cachedResolver: ColorRampResolver | null = null;
let cachedResolver: HeatmapColorResolver | null = null;
function getResolver(u: uPlot): ColorRampResolver {
function getResolver(u: uPlot): HeatmapColorResolver {
if (cachedResolver && cachedData === u.data) {
return cachedResolver;
}
cachedResolver = createColorRampResolver({
cachedResolver = createHeatmapColorResolver({
options: colors,
domain: resolveColorDomain(
domain: resolveCountDomain(
colors,
u.data.slice(1) as Array<Array<number | null>>,
),

View File

@@ -1,7 +1,7 @@
import { Color } from '@signozhq/design-tokens';
import uPlot from 'uplot';
import { ColorRampResolver } from 'lib/visualization/colorRamp/colorScale';
import { HeatmapColorResolver } from './colorScale';
import { HeatmapYAxis } from './types';
/** Cells at least this wide/tall keep a hairline separator. */
@@ -54,7 +54,7 @@ export function drawCells({
u: uPlot;
yAxis: HeatmapYAxis;
step: number;
resolver: ColorRampResolver;
resolver: HeatmapColorResolver;
hatchPattern: CanvasPattern | null;
}): void {
const { ctx } = u;

View File

@@ -1,6 +1,6 @@
import { ColorRampPalette } from './types';
import { HeatmapColorPalette } from './types';
export const DEFAULT_COLOR_RAMP_PALETTE = ColorRampPalette.Lava;
export const DEFAULT_HEATMAP_PALETTE = HeatmapColorPalette.Lava;
interface PaletteDefinition {
/** Evenly spaced, one end of the ramp to the other. */
@@ -13,8 +13,8 @@ interface PaletteDefinition {
* Stop values come from the long-established public palette families —
* ColorBrewer for the hue ramps, matplotlib's perceptual set for the rest.
*/
const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
[ColorRampPalette.Ice]: {
const PALETTES: Record<HeatmapColorPalette, PaletteDefinition> = {
[HeatmapColorPalette.Ice]: {
darkFirst: false,
stops: [
'#f7fbff',
@@ -28,7 +28,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#08306b',
],
},
[ColorRampPalette.Moss]: {
[HeatmapColorPalette.Moss]: {
darkFirst: false,
stops: [
'#f7fcf5',
@@ -42,7 +42,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#00441b',
],
},
[ColorRampPalette.Rust]: {
[HeatmapColorPalette.Rust]: {
darkFirst: false,
stops: [
'#fff5f0',
@@ -56,7 +56,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#67000d',
],
},
[ColorRampPalette.Graphite]: {
[HeatmapColorPalette.Graphite]: {
darkFirst: false,
stops: [
'#ffffff',
@@ -70,7 +70,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#000000',
],
},
[ColorRampPalette.Ember]: {
[HeatmapColorPalette.Ember]: {
darkFirst: false,
stops: [
'#ffffcc',
@@ -84,7 +84,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#800026',
],
},
[ColorRampPalette.Lagoon]: {
[HeatmapColorPalette.Lagoon]: {
darkFirst: false,
stops: [
'#ffffd9',
@@ -98,7 +98,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#081d58',
],
},
[ColorRampPalette.Orchid]: {
[HeatmapColorPalette.Orchid]: {
darkFirst: false,
stops: [
'#fff7f3',
@@ -112,7 +112,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#49006a',
],
},
[ColorRampPalette.Verdant]: {
[HeatmapColorPalette.Verdant]: {
darkFirst: true,
stops: [
'#440154',
@@ -126,7 +126,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#fde725',
],
},
[ColorRampPalette.Lava]: {
[HeatmapColorPalette.Lava]: {
darkFirst: true,
stops: [
'#000004',
@@ -140,7 +140,7 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
'#fcfdbf',
],
},
[ColorRampPalette.Beacon]: {
[HeatmapColorPalette.Beacon]: {
darkFirst: true,
stops: [
'#002051',
@@ -156,10 +156,10 @@ const PALETTES: Record<ColorRampPalette, PaletteDefinition> = {
},
};
/** Stops oriented low end first for the active theme. At the wrong polarity,
* the emptiest values become the loudest thing on screen. */
/** Stops oriented low-count first for the active theme. At the wrong polarity,
* empty cells become the loudest thing on screen. */
export function getPaletteStops(
palette: ColorRampPalette,
palette: HeatmapColorPalette,
isDarkMode: boolean,
): string[] {
const definition = PALETTES[palette];

View File

@@ -1,3 +1,44 @@
export enum HeatmapColorScale {
Log = 'log',
Sqrt = 'sqrt',
Linear = 'linear',
}
export enum HeatmapColorMode {
Palette = 'palette',
Opacity = 'opacity',
}
/** Sequential ramps only: colour means "count", so a midpoint or hue cycle would
* read as a threshold that does not exist. */
export enum HeatmapColorPalette {
Ice = 'ice',
Moss = 'moss',
Rust = 'rust',
Graphite = 'graphite',
Ember = 'ember',
Lagoon = 'lagoon',
Orchid = 'orchid',
Verdant = 'verdant',
Lava = 'lava',
Beacon = 'beacon',
}
export interface HeatmapColorOptions {
mode: HeatmapColorMode;
scale: HeatmapColorScale;
/** `null` derives it, which is always 0 — a count of 0 belongs at the bottom. */
minCount: number | null;
/** `null` derives it from the grid's highest count. */
maxCount: number | null;
palette: HeatmapColorPalette;
/** Colour steps the ramp is quantised into, 2..128. Unrelated to `step`, the
* column width in seconds. */
steps: number;
/** Opacity mode. Empty falls back to the caller's series colour. */
fill: string;
}
/** Row-height distribution of the bucket axis. */
export enum HeatmapAxisScale {
/** Whichever of the three below the boundaries admit: log when they are all

View File

@@ -1,35 +0,0 @@
// Same theme hooks as the SVG chart; canvas reads them through readPalette().
.wrapper {
--geo-no-data: var(--l3-background);
--geo-context: var(--l2-background);
--geo-border: var(--l1-background);
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
overflow: hidden;
}
.wrapper[data-legend-position='right'] {
flex-direction: row;
gap: 12px;
}
.mapArea {
position: relative;
flex: 1 1 auto;
min-width: 0;
min-height: 0;
}
.canvas {
position: absolute;
inset: 0;
}
.tooltip {
position: absolute;
pointer-events: none;
z-index: 9999;
}

View File

@@ -1,251 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTooltip, useTooltipInPortal } from '@visx/tooltip';
import { useResizeObserver } from 'hooks/useDimensions';
import { LegendPosition } from 'lib/uPlotV2/components/types';
import CountryTooltip from './components/CountryTooltip/CountryTooltip';
import MapLegend from './components/MapLegend/MapLegend';
import MapStatus from './components/MapStatus/MapStatus';
import ZoomControls from './components/ZoomControls/ZoomControls';
import { useGeoMapScales } from './hooks/useGeoMapScales';
import { useGeoMapShapes } from './hooks/useGeoMapShapes';
import { formatCoordinates } from './utils/coordinates';
import { findShapeAt } from './utils/olFeatures';
import { pointAsDatum } from './utils/scales';
import { GeoMapProps } from './types';
import { useOlLayers } from './hooks/useOlLayers';
import { useOlMap } from './hooks/useOlMap';
import { useOlPointer } from './hooks/useOlPointer';
import { useOlPointsLayer } from './hooks/useOlPointsLayer';
import { useOlView } from './hooks/useOlView';
import { OlPalette, readPalette } from './utils/olStyles';
import styles from './GeoMap.module.scss';
export default function GeoMap({
data,
points,
view,
country,
projection,
layer,
colors,
bubbleRadius,
formatValue,
valueLabel,
sizeMetric,
showLabels = true,
colorKeys,
legendPosition = LegendPosition.BOTTOM,
isDarkMode,
onSelect,
renderTooltipFooter,
}: GeoMapProps): JSX.Element {
const wrapperRef = useRef<HTMLDivElement>(null);
const mapAreaRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLDivElement>(null);
const { width, height } = useResizeObserver(mapAreaRef, 100);
const [palette, setPalette] = useState<OlPalette | null>(null);
const {
tooltipOpen,
tooltipLeft,
tooltipTop,
tooltipData,
showTooltip,
hideTooltip,
} = useTooltip<string>();
const { containerRef, TooltipInPortal } = useTooltipInPortal({
scroll: true,
detectBounds: true,
});
// On the points layer the scales colour and size points, keyed by point id.
const scaleData = useMemo(
() => (layer === 'points' ? (points ?? []).map(pointAsDatum) : data),
[layer, points, data],
);
const { resolver, valueByCode, sizeByCode, radiusFor, fillFor } =
useGeoMapScales(
scaleData,
colors,
bubbleRadius,
isDarkMode,
Boolean(sizeMetric),
);
const maxSize = useMemo(
() => [...sizeByCode.values()].reduce((max, size) => Math.max(max, size), 0),
[sizeByCode],
);
const { shapes, status, retry } = useGeoMapShapes(view, country);
const handle = useOlMap(canvasRef);
const pointsLayer = useOlPointsLayer(handle, layer === 'points');
useEffect(() => {
if (wrapperRef.current) {
setPalette(readPalette(wrapperRef.current));
}
}, [isDarkMode]);
const handleHover = useCallback(
(code: string | null, clientX: number, clientY: number): void => {
const rect = mapAreaRef.current?.getBoundingClientRect();
if (!code || !rect || !valueByCode.has(code)) {
hideTooltip();
return;
}
showTooltip({
tooltipData: code,
tooltipLeft: clientX - rect.left,
tooltipTop: clientY - rect.top,
});
},
[valueByCode, showTooltip, hideTooltip],
);
const pointById = useMemo(
() =>
new Map(
(layer === 'points' ? (points ?? []) : []).map((point) => [
point.id,
point,
]),
),
[layer, points],
);
const handleSelect = useCallback(
(code: string, clientX: number, clientY: number): void => {
const datum = valueByCode.get(code);
if (datum && onSelect) {
hideTooltip();
onSelect({ datum, point: pointById.get(code), clientX, clientY });
}
},
[valueByCode, pointById, onSelect, hideTooltip],
);
const hovered =
tooltipOpen && tooltipData ? valueByCode.get(tooltipData) : undefined;
const hoveredPoint = hovered ? pointById.get(hovered.code) : undefined;
// A point without a label is named by the shape it falls in.
const hoveredPlace = useMemo(() => {
if (!hoveredPoint || hoveredPoint.label || !handle || !shapes) {
return undefined;
}
const code = findShapeAt(
[handle.layers.members.getSource(), handle.layers.context.getSource()],
[hoveredPoint.lon, hoveredPoint.lat],
projection,
);
return code ? shapes.nameOf(code) : undefined;
}, [hoveredPoint, handle, shapes, projection]);
useOlLayers({
handle,
shapes,
projection,
data,
points,
pointsLayer,
layer,
palette,
fillFor,
sizeByCode,
radiusFor,
hasSizeMetric: Boolean(sizeMetric),
showLabels,
hoveredCode: hovered?.code ?? null,
});
const zoom = useOlView(
handle,
view,
projection,
country,
data,
width,
height,
layer === 'points' ? points : undefined,
);
useOlPointer(handle, handleHover, handleSelect, pointsLayer.layer);
return (
<div
className={styles.wrapper}
ref={wrapperRef}
data-geo-map
data-legend-position={legendPosition}
data-testid="geo-map"
>
<div
className={styles.mapArea}
ref={(node): void => {
(mapAreaRef as React.MutableRefObject<HTMLDivElement | null>).current =
node;
containerRef(node);
}}
>
<div
ref={canvasRef}
className={styles.canvas}
data-testid="geo-map-canvas"
/>
{status !== 'ready' && <MapStatus status={status} onRetry={retry} />}
{status === 'ready' && (
<ZoomControls
canZoomIn={zoom.canZoomIn}
canZoomOut={zoom.canZoomOut}
onZoomIn={zoom.zoomIn}
onZoomOut={zoom.zoomOut}
onReset={zoom.reset}
/>
)}
{hovered && (
<TooltipInPortal
left={tooltipLeft}
top={tooltipTop}
className={styles.tooltip}
unstyled
applyPositionStyle
>
<CountryTooltip
datum={hovered}
name={
hoveredPoint
? hoveredPoint.label ||
hoveredPlace ||
formatCoordinates(hoveredPoint.lat, hoveredPoint.lon)
: (shapes?.nameOf(hovered.code) ?? hovered.code)
}
place={
hoveredPoint && formatCoordinates(hoveredPoint.lat, hoveredPoint.lon)
}
color={fillFor(hovered.code) ?? resolver.colorFor(hovered.value)}
formatValue={formatValue}
valueLabel={valueLabel}
sizeMetric={sizeMetric}
footer={renderTooltipFooter?.()}
/>
</TooltipInPortal>
)}
</div>
<MapLegend
resolver={resolver}
scale={colors.scale}
formatValue={formatValue}
markerValue={hovered?.value ?? null}
valueLabel={valueLabel}
colorKeys={colorKeys}
position={legendPosition}
size={
sizeMetric && {
label: sizeMetric.label,
maxSize,
radiusFor,
formatValue: sizeMetric.formatValue,
}
}
/>
</div>
);
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
{"type":"Topology","bbox":[1.406456,42.428677,1.765091,42.649362],"transform":{"scale":[0.00003586708670867087,0.000022070707070707384],"translate":[1.406456,42.428677]},"objects":{"subdivisions":{"type":"GeometryCollection","geometries":[{"type":"Polygon","arcs":[[0,1,2]],"id":"AD-02","properties":{"code":"AD-02","name":"Canillo","label":[1.605,42.584]}},{"type":"Polygon","arcs":[[3,4,5,-2]],"id":"AD-03","properties":{"code":"AD-03","name":"Encamp","label":[1.644,42.538]}},{"type":"Polygon","arcs":[[6,-6,7,8,9]],"id":"AD-04","properties":{"code":"AD-04","name":"La Massana","label":[1.471,42.55]}},{"type":"Polygon","arcs":[[-3,-7,10]],"id":"AD-05","properties":{"code":"AD-05","name":"Ordino","label":[1.524,42.604]}},{"type":"Polygon","arcs":[[-9,11,12,13]],"id":"AD-06","properties":{"code":"AD-06","name":"Sant Julià de Lòria","label":[1.48,42.451]}},{"type":"Polygon","arcs":[[14,-12,-8]],"id":"AD-07","properties":{"code":"AD-07","name":"Andorra la Vella","label":[1.511,42.513]}},{"type":"Polygon","arcs":[[15,-13,-15,-5]],"id":"AD-08","properties":{"code":"AD-08","name":"Escaldes-Engordany","label":[1.594,42.495]}}]}},"arcs":[[[5322,8756],[306,-172],[3169,-375],[-242,-920],[450,-342],[648,-241],[235,-409],[111,-194],[-700,-79],[-510,-594],[-128,-391]],[[8661,5039],[-190,223],[-269,202],[-291,168],[-103,573],[-104,404],[-394,-202],[-539,0],[-581,-101],[-663,-168],[-539,0],[-394,0],[-436,-68]],[[4158,6070],[63,539],[186,438],[291,337],[373,135],[290,135],[0,404],[-39,698]],[[8661,5039],[-181,-551],[-100,-1130],[-266,-377],[-311,-175],[-337,-5],[-331,146],[-72,140],[-78,38]],[[6985,3125],[-90,553],[-352,371],[-332,202],[-580,67],[-436,-101],[-373,236],[-83,404],[-207,135],[-353,-34]],[[4179,4958],[0,641],[-21,471]],[[1253,7855],[231,-235],[311,0],[290,-67],[145,-236],[166,-573],[249,-303],[394,-135],[477,-135],[373,-67],[269,-34]],[[4179,4958],[-352,0],[-332,-168],[-394,-101],[-415,-337],[-435,-303]],[[2251,4049],[-394,-135],[-373,-236],[-271,-262]],[[1213,3416],[-95,717],[-490,524],[-628,-101],[92,516],[461,959],[3,175],[-233,190],[34,427],[156,458],[124,272],[616,302]],[[1253,7855],[430,1786],[882,-55],[818,376],[426,37],[1513,-1243]],[[2251,4049],[41,-405],[21,-269],[104,-438],[166,-202]],[[2583,2735],[477,-135],[373,-169],[518,101],[456,68],[291,-68],[-187,-404],[41,-472],[82,-551]],[[4634,1105],[-787,-123],[-156,-213],[-121,-260],[-176,-257],[-322,-215],[-228,-37],[-1688,270],[-320,286],[0,568],[-804,1508],[472,258],[159,50],[550,476]],[[4179,4958],[-186,-370],[-311,-371],[-146,-236],[-165,-370],[-229,-472],[-331,-236],[-228,-168]],[[6985,3125],[-84,-51],[-101,-141],[-302,-1223],[-893,-453],[-971,-152]]],"aliases":{},"names":{"ordino":"AD-05","parroquia d'ordino":"AD-05","canillo":"AD-02","encamp":"AD-03","parroquia d'encamp":"AD-03","la massana":"AD-04","parroquia de la massana":"AD-04","massana":"AD-04","sant julià de lòria":"AD-06","parroquia de sant julia de loria":"AD-06","sant juliã  de lã²ria":"AD-06","escaldes-engordany":"AD-08","parroquia d'escaldes-engordany":"AD-08","andorra la vella":"AD-07","parroquia d'andorra la vella":"AD-07"}}

View File

@@ -1 +0,0 @@
{"type":"Topology","bbox":[51.569347,22.620946,56.383155522852284,26.07341032343234],"transform":{"scale":[0.0004814289951847469,0.0003452809604392781],"translate":[51.569347,22.620946]},"objects":{"subdivisions":{"type":"GeometryCollection","geometries":[{"type":"MultiPolygon","arcs":[[[0,1]]],"id":"AE-AJ","properties":{"code":"AE-AJ","name":"Ajman","label":[55.541,25.397]}},{"type":"MultiPolygon","arcs":[[[2,3,4]],[[5]],[[6]],[[7]],[[8]],[[9]],[[10]],[[11]],[[12]]],"id":"AE-AZ","properties":{"code":"AE-AZ","name":"Abu Dhabi","label":[54.082,23.524]}},{"type":"MultiPolygon","arcs":[[[13,14]],[[15,-4,16]]],"id":"AE-DU","properties":{"code":"AE-DU","name":"Dubay","label":[55.344,24.951]}},{"type":"MultiPolygon","arcs":[[[17,18,19,20,21,22,23]],[[24,25,26,27,28,29]],[[30,31,32]]],"id":"AE-FU","properties":{"code":"AE-FU","name":"Fujayrah","label":[56.222,25.475]}},{"type":"MultiPolygon","arcs":[[[33,-23,34,-31,35,-15,36,37,-26]],[[-28,38,39,40]]],"id":"AE-RK","properties":{"code":"AE-RK","name":"Ras Al Khaymah","label":[55.979,25.696]}},{"type":"MultiPolygon","arcs":[[[41,-30,42,-18]],[[-20,43]],[[44,-5,-16,45,-2,46,47,-39,-27,-38]],[[-22,48,-32,-35]]],"id":"AE-SH","properties":{"code":"AE-SH","name":"Sharjah","label":[55.779,25.172]}},{"type":"MultiPolygon","arcs":[[[49,-40,-48]]],"id":"AE-UQ","properties":{"code":"AE-UQ","name":"Umm Al Qaywayn","label":[55.722,25.522]}}]}},"arcs":[[[8008,8033],[140,190]],[[8148,8223],[291,-136],[-72,-155],[-175,12],[-184,89]],[[8788,6001],[38,-144],[-122,-246],[31,-384],[68,-246],[-107,-320],[190,-55],[178,27],[135,-403],[-397,-214],[-92,60],[-240,-9],[-395,-179],[153,-257],[16,-303],[-124,-272],[-69,-359],[-145,-240],[-113,-562],[-198,-446],[-71,-365],[13,-422],[-23,-423],[-169,-239],[-5240,898],[-92,68],[-1963,3255],[-42,143],[-8,372],[44,82],[-34,231],[103,-72],[22,-326],[79,148],[95,-159],[84,195],[49,-145],[-21,-185],[78,-509],[445,-37],[90,-70],[326,30],[243,97],[485,419],[13,137],[110,-28],[75,-131],[351,21],[225,-40],[109,80],[140,-127],[165,-1],[-9,129],[152,-71],[79,-124],[381,61],[171,-66],[129,-140],[252,64],[314,-25],[202,121],[357,118],[134,171],[136,50],[146,144],[124,-47],[132,179],[82,209],[0,169],[113,-41],[-85,160],[-170,137],[142,100],[57,-158],[143,-20],[113,259],[-42,68],[113,130],[-62,192],[138,208],[620,480]],[[7138,6803],[275,-965],[130,-121],[440,23],[537,307]],[[8520,6047],[268,-46]],[[4336,4453],[-61,39],[198,168],[242,100],[260,-266],[-92,-95],[-178,36],[-194,-54],[-175,72]],[[5446,4652],[-163,129],[51,160],[106,-143],[6,-146]],[[2088,4990],[76,85],[78,-185],[-118,-162],[-75,155],[39,107]],[[3642,4755],[-283,38],[363,217],[115,180],[63,-96],[-40,-148],[-200,-116],[-18,-75]],[[5844,5267],[-99,85],[127,156],[1,-114],[152,-136],[-181,9]],[[5603,4847],[-173,59],[102,124],[71,-183]],[[5726,5074],[-35,-171],[-62,146],[97,25]],[[1538,5556],[61,-110],[-116,-13],[55,123]],[[9559,6381],[-110,-258],[-87,-15],[61,262]],[[9423,6370],[136,11]],[[7801,7779],[257,0],[316,-309],[58,-104],[60,-317],[-79,-161],[86,-300],[42,-367],[-21,-174]],[[7138,6803],[159,136],[449,700],[55,140]],[[9928,7742],[71,79]],[[9999,7821],[-43,-733]],[[9956,7088],[-160,30],[42,-168],[-49,-200]],[[9789,6750],[-24,-36]],[[9765,6714],[-35,110],[-186,221]],[[9544,7045],[4,482],[85,20]],[[9633,7547],[60,-45],[225,160],[10,80]],[[9745,7849],[-57,-54]],[[9688,7795],[-147,65],[25,-142],[-137,-196],[-255,21]],[[9174,7543],[-18,164],[12,144],[38,142]],[[9206,7993],[158,-109],[116,62],[-86,153],[75,140],[-49,100],[-253,-14],[-35,235],[214,188],[174,48]],[[9520,8796],[143,-128],[120,39],[126,-66],[63,-229],[-11,-296]],[[9961,8116],[-216,-267]],[[9774,6520],[-45,66]],[[9729,6586],[47,55]],[[9776,6641],[-2,-121]],[[9688,7795],[-55,-248]],[[9544,7045],[35,-379],[150,-80]],[[9774,6520],[-215,-139]],[[9423,6370],[-167,180],[-103,260]],[[9153,6810],[-52,324],[58,177],[-53,93],[68,139]],[[9206,7993],[-152,-96]],[[9054,7897],[-99,133],[-75,231],[-88,442],[-116,106]],[[8676,8809],[274,225],[283,402],[-14,81],[145,446],[177,36],[43,-170],[-27,-399],[-54,-113],[48,-174],[-55,-130],[24,-217]],[[9928,7742],[-183,107]],[[9961,8116],[38,-295]],[[9956,7088],[43,-261],[-210,-77]],[[9153,6810],[-164,-10],[-140,-138],[-85,-191],[24,-470]],[[7801,7779],[207,254]],[[8148,8223],[48,153]],[[8196,8376],[512,-417],[94,-240],[202,26],[50,152]],[[9765,6714],[11,-73]],[[8196,8376],[231,67],[64,178],[185,188]]],"aliases":{},"names":{"fujayrah":"AE-FU","emirate of fujairah":"AE-FU","al fujayrah":"AE-FU","sharjah":"AE-SH","emirate of sharjah":"AE-SH","ash shariqah":"AE-SH","ras al khaymah":"AE-RK","emirate of ras al khaimah":"AE-RK","ra's al khaymah":"AE-RK","dubay":"AE-DU","emirate of dubai":"AE-DU","dubayy":"AE-DU","abu dhabi":"AE-AZ","emirate of abu dhabi":"AE-AZ","abu zaby":"AE-AZ","umm al qaywayn":"AE-UQ","emirate of umm al quwain":"AE-UQ","ajman":"AE-AJ","emirate of ajman":"AE-AJ","`ajman":"AE-AJ"}}

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
{"type":"Topology","bbox":[-62.34826,16.93197,-61.667592,17.727688],"transform":{"scale":[0.0000680736073607365,0.00007957975797579766],"translate":[-62.34826,16.93197]},"objects":{"subdivisions":{"type":"GeometryCollection","geometries":[{"type":"Polygon","arcs":[[0,1,2]],"id":"AG-03","properties":{"code":"AG-03","name":"Saint George","label":[-61.78,17.108]}},{"type":"Polygon","arcs":[[3,-3,4,5,6]],"id":"AG-04","properties":{"code":"AG-04","name":"Saint John","label":[-61.824,17.11]}},{"type":"Polygon","arcs":[[7,-7,8]],"id":"AG-05","properties":{"code":"AG-05","name":"Saint Mary","label":[-61.857,17.037]}},{"type":"Polygon","arcs":[[9,-9,-6,10,11]],"id":"AG-06","properties":{"code":"AG-06","name":"Saint Paul","label":[-61.767,17.035]}},{"type":"Polygon","arcs":[[12,13,-11,-5,-2]],"id":"AG-07","properties":{"code":"AG-07","name":"Saint Peter","label":[-61.74,17.094]}},{"type":"Polygon","arcs":[[14,-12,-14]],"id":"AG-08","properties":{"code":"AG-08","name":"Saint Philip","label":[-61.702,17.06]}},{"type":"Polygon","arcs":[[15]],"id":"AG-10","properties":{"code":"AG-10","name":"Barbuda","label":[-61.792,17.616]}},{"type":"Polygon","arcs":[[16]],"id":"AG-11","properties":{"code":"AG-11","name":"Redonda","label":[-62.347,16.934]}}]}},"arcs":[[[8151,2928],[187,-224],[112,-259],[244,-156]],[[8694,2289],[-81,-75],[75,-103],[15,-128],[-165,-51],[-105,-180]],[[8433,1752],[-105,39],[-210,115],[30,141],[-45,270],[-120,89],[-15,257],[210,13],[-27,252]],[[7081,1946],[-105,34],[-305,138],[162,125],[260,92],[339,83],[-119,166],[24,149],[134,131],[212,112],[468,-48]],[[8433,1752],[0,-141]],[[8433,1611],[-150,26],[-330,-77],[-120,-102]],[[7833,1458],[-75,141],[-225,-206],[60,321],[75,141],[-15,38],[-255,52],[-134,102],[-183,-101]],[[7994,947],[-202,-30],[-306,-1],[-192,35],[-469,234],[-99,115],[100,171],[64,144],[-52,122],[5,108],[238,101]],[[7833,1458],[105,-167],[-45,-141],[101,-203]],[[9138,1338],[-115,-45],[-5,-114],[69,-309],[-110,-150],[-240,95],[-239,178],[-104,95],[-99,-21],[-301,-120]],[[8433,1611],[375,0],[224,52]],[[9032,1663],[106,-325]],[[8694,2289],[14,112],[40,74],[139,158],[83,-107],[114,-63],[144,-20],[168,18],[-71,-66],[-41,-47],[-63,-34],[-134,-25],[67,-180],[151,-84]],[[9305,2025],[-198,-119],[-75,-243]],[[9305,2025],[194,4],[199,89],[109,0],[75,-62],[51,-62],[66,-141],[-100,6],[-202,-12],[-100,6],[137,-140],[126,-67],[71,-68],[-32,-147],[-166,-217],[-166,-10],[-190,80],[-239,54]],[[7482,8311],[-501,1474],[1745,-526],[375,-802],[-616,-747],[-1003,601]],[[39,90],[15,16],[22,6],[2,-32],[-2,-41],[-20,-32],[-38,-7],[-18,21],[14,47],[25,22]]],"aliases":{},"names":{"saint paul":"AG-06","parish of saint paul":"AG-06","saint philip":"AG-08","parish of saint philip":"AG-08","saint peter":"AG-07","parish of saint peter":"AG-07","saint george":"AG-03","parish of saint george":"AG-03","saint john":"AG-04","parish of saint john":"AG-04","saint mary":"AG-05","parish of saint mary":"AG-05","barbuda":"AG-10","redonda":"AG-11"}}

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
{"type":"Topology","bbox":[43.436294,38.863701,46.602612,41.290452],"transform":{"scale":[0.00031666346634663504,0.000242699369936994],"translate":[43.436294,38.863701]},"objects":{"subdivisions":{"type":"GeometryCollection","geometries":[{"type":"Polygon","arcs":[[0,1,2,3,4,5]],"id":"AM-AG","properties":{"code":"AM-AG","name":"Aragatsotn","label":[44.074,40.321]}},{"type":"Polygon","arcs":[[6,7,8,9,10,11]],"id":"AM-AR","properties":{"code":"AM-AR","name":"Ararat","label":[44.73,39.92]}},{"type":"Polygon","arcs":[[-6,12,-8,13]],"id":"AM-AV","properties":{"code":"AM-AV","name":"Armavir","label":[44.046,40.099]}},{"type":"Polygon","arcs":[[-9,-13,-5,14]],"id":"AM-ER","properties":{"code":"AM-ER","name":"Erevan","label":[44.533,40.147]}},{"type":"MultiPolygon","arcs":[[[15,16,-11,17,18]],[[19]]],"id":"AM-GR","properties":{"code":"AM-GR","name":"Gegharkunik","label":[45.385,40.278]}},{"type":"Polygon","arcs":[[20,-18,-10,-15,-4,21]],"id":"AM-KT","properties":{"code":"AM-KT","name":"Kotayk","label":[44.719,40.375]}},{"type":"Polygon","arcs":[[22,-22,-3,23,24]],"id":"AM-LO","properties":{"code":"AM-LO","name":"Lori","label":[44.452,40.935]}},{"type":"Polygon","arcs":[[-24,-2,25]],"id":"AM-SH","properties":{"code":"AM-SH","name":"Shirak","label":[43.818,40.819]}},{"type":"Polygon","arcs":[[26,27]],"id":"AM-SU","properties":{"code":"AM-SU","name":"Syunik","label":[46.152,39.248]}},{"type":"Polygon","arcs":[[-19,-21,-23,28],[29],[30]],"id":"AM-TV","properties":{"code":"AM-TV","name":"Tavush","label":[45.176,40.888]}},{"type":"Polygon","arcs":[[31,-28,32,-12,-17]],"id":"AM-VD","properties":{"code":"AM-VD","name":"Vayots Dzor","label":[45.442,39.718]}}]}},"arcs":[[[802,5673],[-303,432],[95,271]],[[594,6376],[257,222],[276,136],[470,-110],[198,64],[137,-161],[478,263],[-59,308],[-170,-8],[-148,231],[271,412]],[[2304,7733],[281,-88],[103,91],[354,-129],[59,-116]],[[3101,7491],[33,-282],[393,-202],[-178,-610],[24,-149],[-301,-369],[53,-370]],[[3125,5509],[-24,-47]],[[3101,5462],[-430,202],[-339,18],[-121,-237],[-375,3],[-638,406],[-396,-181]],[[5175,3651],[-131,85],[-336,-188],[-482,-91],[-291,389],[-363,313],[-143,249],[-446,314]],[[2983,4722],[-94,302],[282,290]],[[3171,5314],[123,-234],[240,-172],[291,250]],[[3825,5158],[142,-133],[287,70],[564,255],[214,5]],[[5032,5355],[-47,-346],[217,-544],[82,-336]],[[5284,4129],[-109,-478]],[[3101,5462],[70,-148]],[[2983,4722],[-397,139],[-703,-144],[-380,65],[-346,191],[-433,163],[-41,119],[217,125],[-98,293]],[[3125,5509],[461,117],[146,-140],[-88,-248],[181,-80]],[[6118,7365],[482,-866],[187,-174],[735,-416],[137,-151],[199,21],[172,-176],[-89,-438],[-244,-443],[-220,-22],[-519,87],[-196,-171]],[[6762,4616],[-100,61],[-272,-198],[-624,-43],[-482,-307]],[[5032,5355],[-262,324],[34,208],[-148,546],[-146,155],[7,182],[-184,102],[-37,488]],[[4296,7360],[375,79],[257,-130],[214,68],[106,184],[240,137],[214,-24],[416,-309]],[[6581,7403],[128,-53],[-149,-188],[-108,199],[129,42]],[[4220,7423],[76,-63]],[[3101,7491],[342,74],[500,-143],[277,1]],[[4476,9723],[216,-112],[-121,-322],[165,-227],[-204,-156],[-313,-105],[420,-373],[-195,-356],[-289,-207],[65,-442]],[[2304,7733],[-179,13],[-228,169],[-69,186],[79,215],[127,-30],[134,345],[-205,61],[61,125],[-351,350],[37,313]],[[1710,9480],[397,44],[276,226],[239,-139],[286,65],[309,-130],[195,108],[110,-122],[194,190],[196,-61],[462,-9],[102,71]],[[594,6376],[-192,221],[281,266],[242,609],[-57,431],[-163,289],[-38,255],[-135,204],[-456,245],[-63,345],[399,72],[515,-71],[421,215],[362,23]],[[7493,4069],[167,-192],[370,-149],[209,-333],[318,-203],[191,-208],[433,126],[229,-183],[200,19],[151,-167],[-92,-265],[-292,-93],[-98,-298],[381,-226],[71,-186],[268,-262],[-279,-127],[-303,113],[-70,-196],[263,-205],[57,-252],[-68,-321],[120,-385],[-385,166],[-276,-25],[-323,-189],[-210,-28],[-184,358],[-165,466],[-212,362],[88,343],[-86,155],[-427,291],[-179,47],[114,386],[-47,415],[-250,81]],[[7177,2904],[71,571],[-60,112],[305,482]],[[4476,9723],[-104,206],[424,-44],[150,114],[156,-405],[261,-18],[210,-252],[-421,-65],[-33,-132],[198,3],[321,-268],[359,-85],[265,97],[-9,-231],[384,-352],[193,-55],[-137,-354],[-496,-279],[-79,-238]],[[4988,8898],[10,213],[-184,-62],[174,-151]],[[5601,8670],[0,0]],[[6762,4616],[106,-102],[329,-34],[155,-119],[141,-292]],[[7177,2904],[-387,-95],[-407,-231],[-457,183],[-167,272],[-291,-141],[-74,100],[-10,390],[-209,269]]],"aliases":{},"names":{"tavush":"AM-TV","tavushi marz":"AM-TV","lori":"AM-LO","lorru marz":"AM-LO","shirak":"AM-SH","shiraki marz":"AM-SH","gegharkunik":"AM-GR","geghark'unik'i marz":"AM-GR","vayots dzor":"AM-VD","vayots' dzori marz":"AM-VD","syunik":"AM-SU","syunik'i marz":"AM-SU","ararat":"AM-AR","ararati marz":"AM-AR","aragatsotn":"AM-AG","aragatsotni marz":"AM-AG","armavir":"AM-AV","armaviri marz":"AM-AV","kotayk":"AM-KT","kotayk'i marz":"AM-KT","erevan":"AM-ER","yerevan":"AM-ER"}}

File diff suppressed because one or more lines are too long

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