Compare commits

..

9 Commits

Author SHA1 Message Date
Vinícius Lourenço
0f2391d705 ci(e2e): check every spec folder maps to the pages it opens 2026-11-20 19:42:43 -03:00
Vinícius Lourenço
9cd364fb2d fix(e2e): pass select-specs options through test:changed 2026-11-20 19:42:42 -03:00
Vinícius Lourenço
22c0b0c84c ci(e2e): run only the selected specs on PRs and every spec in the merge queue 2026-11-20 19:42:42 -03:00
Vinícius Lourenço
c7c8a7328f test(e2e): add select-specs to pick the specs a change can affect 2026-11-20 19:42:42 -03:00
Vinícius Lourenço
a33d5523b7 ci(storybook): test the static build and only the stories a change reaches 2026-11-20 19:42:41 -03:00
Vinícius Lourenço
03167f3f13 test(storybook): let a story's requests settle before the next one starts 2026-11-20 19:42:41 -03:00
Vinícius Lourenço
32ea1d6ae3 test(storybook): hover truncated labels twice before expecting their tooltip 2026-11-20 19:42:41 -03:00
Vinícius Lourenço
01be28549e test(storybook): wait for the value panel's aggregation limit 2026-11-20 19:42:41 -03:00
Vinícius Lourenço
9926b6e61a fix(frontend): ship Vite workers as ES modules 2026-11-20 18:41:47 -03:00
22 changed files with 1271 additions and 124 deletions

View File

@@ -88,7 +88,7 @@ Say the numbers plainly: how many screens changed, how many are new, how many ar
- A full capture is hundreds of shots. Scope with `--title "Pages/Alerts"` or `--stories "a,b,c"` (substring match on id or Title/Name, repeatable).
- **On macOS a capture can pin itself to one story at a time.** sbshot picks how many to shoot at once by sampling free memory, and off Linux it reads `os.freemem()`, which counts only truly free pages. macOS parks almost everything in "inactive" instead, which is reclaimable on demand, so the sampler can read ~100 MB on a 25 GB machine and shrink to one forever. `--jobs` does not help: it is only an upper cap. Check `parallelism` in `<run>/events.ndjson`; if it sits at 1 while `vm_stat` shows gigabytes inactive, that is this. A 124-shot run takes about 90 minutes pinned and about 6 minutes at four at a time, so it is worth spotting before a long capture.
- A fresh worktree cannot build Storybook: `i18n-translations-hash.json` is gitignored and generated. Run `node ./i18-generate-hash.cjs` in `<worktree>/frontend`, and symlink `node_modules` from the main checkout.
- `pnpm test:storybook` starts its own server on 6006 and hangs silently if something already holds that port. Free it first.
- `pnpm test:storybook` builds Storybook and serves the build on 6006, and refuses to start if something already holds that port. Free it first.
- ImageMagick on macOS may have no default font, so `--mode green-parallel` fails with ``unable to read font `' ``. Map Helvetica to a real file in `~/.config/ImageMagick/type.xml`.
- `sbshot link <dir> <name>` adds a run from elsewhere into the workspace, but it symlinks. Keep the source directory alive until you have exported.
- The export directory is build output. Delete it when done, or gitignore it.

View File

@@ -35,7 +35,7 @@ jobs:
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)')
CHANGED_FILES=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename | select((((startswith("tests/integration/") and (startswith("tests/integration/testdata/inframonitoring/") | not)) 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
@@ -67,15 +67,55 @@ jobs:
- name: lint
run: |
cd tests/e2e && pnpm lint
- name: spec-pages
run: |
cd tests/e2e && pnpm select-specs --check
# Picks the specs a PR can affect; the merge queue and safe-to-e2e run all of them.
select:
needs: changes
if: needs.changes.outputs.e2e == 'true'
runs-on: ubuntu-latest
outputs:
specs: ${{ steps.select.outputs.specs }}
shards: ${{ steps.select.outputs.shards }}
shard-total: ${{ steps.select.outputs.shard-total }}
steps:
- name: checkout
uses: actions/checkout@v4
with:
# The PR merge commit and its base parent: HEAD^1..HEAD is the PR's diff.
fetch-depth: 2
- name: node
uses: actions/setup-node@v4
with:
node-version: "22"
- name: install-pnpm
uses: pnpm/action-setup@v6
with:
version: 10
- name: install
run: |
cd tests/e2e && pnpm install --frozen-lockfile
- name: select
id: select
env:
FULL: ${{ github.event_name == 'merge_group' || contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
run: |
cd tests/e2e
if [ "$FULL" = "true" ]; then
pnpm select-specs --all --github-output
else
pnpm select-specs --base HEAD^1 --github-output
fi
test:
strategy:
fail-fast: false
matrix:
project:
- chromium
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
needs: changes
if: needs.changes.outputs.e2e == 'true'
shard: ${{ fromJSON(needs.select.outputs.shards) }}
needs: select
if: needs.select.outputs.shard-total != '0'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
@@ -166,9 +206,11 @@ jobs:
- name: wait-playwright-browsers
wait: playwright-browsers
- name: playwright-test
env:
SPECS: ${{ needs.select.outputs.specs }}
run: |
cd tests/e2e && \
pnpm playwright test --project=${{ matrix.project }} --shard=${{ matrix.shard }}/10
pnpm playwright test --project=${{ matrix.project }} --shard=${{ matrix.shard }}/${{ needs.select.outputs.shard-total }} $SPECS
- name: teardown-stack
if: always()
run: |
@@ -189,7 +231,7 @@ jobs:
# 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]
needs: [changes, fmtlint, select, test]
runs-on: ubuntu-latest
steps:
- name: verdict

View File

@@ -79,19 +79,74 @@ jobs:
run: |
cd frontend && pnpm generate:api
git diff --compact-summary --exit-code || (echo; echo "Unexpected difference in generated api clients. Run pnpm generate:api in frontend/ locally and commit."; exit 1)
storybook:
storybook-build:
if: |
github.event_name == 'merge_group' ||
(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
timeout-minutes: 10
outputs:
shards: ${{ steps.select-stories.outputs.shards }}
steps:
- name: self-checkout
uses: actions/checkout@v4
with:
# The pull_request merge commit and its first parent, the base branch.
fetch-depth: 2
- name: install-pnpm
uses: pnpm/action-setup@v6
with:
version: 10
- name: node-install
uses: actions/setup-node@v5
with:
node-version: "22"
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- name: install-frontend
run: cd frontend && pnpm install
- name: build-storybook
run: |
cd frontend
mkdir -p storybook-stats
pnpm storybook:build --quiet --stats-json storybook-stats
- name: select-stories
id: select-stories
env:
EVENT_NAME: ${{ github.event_name }}
run: |
cd frontend
if [ "$EVENT_NAME" = pull_request ]; then
git diff --name-only HEAD^1 HEAD | node scripts/select-stories.mjs storybook-stats/preview-stats.json > storybook-stories.txt
else
node scripts/select-stories.mjs --all storybook-stats/preview-stats.json > storybook-stories.txt
fi
count=$(grep -c . storybook-stories.txt || true)
shard_count=$(( count > 80 ? 4 : (count + 19) / 20 ))
echo "Testing $count story files on $shard_count shards"
cat storybook-stories.txt
echo "shards=[$(seq -s, 1 "$shard_count")]" >> "$GITHUB_OUTPUT"
- name: upload-storybook
if: steps.select-stories.outputs.shards != '[]'
uses: actions/upload-artifact@v4
with:
name: storybook-static
retention-days: 1
path: |
frontend/storybook-static
frontend/storybook-stories.txt
storybook:
needs: storybook-build
if: needs.storybook-build.outputs.shards != '[]'
runs-on: ubuntu-latest
timeout-minutes: 10
container:
image: mcr.microsoft.com/playwright:v1.57.0-noble
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
shard: ${{ fromJSON(needs.storybook-build.outputs.shards) }}
steps:
- name: self-checkout
uses: actions/checkout@v4
@@ -107,8 +162,19 @@ jobs:
cache-dependency-path: frontend/pnpm-lock.yaml
- name: install-frontend
run: cd frontend && pnpm install
- name: download-storybook
uses: actions/download-artifact@v4
with:
name: storybook-static
path: frontend
- name: test-storybook
run: cd frontend && pnpm test:storybook --shard=${{ matrix.shard }}/${{ strategy.job-total }}
shell: bash
env:
STORYBOOK_STATIC_DIR: storybook-static
run: |
cd frontend
mapfile -t stories < storybook-stories.txt
pnpm test:storybook --shard=${{ matrix.shard }}/${{ strategy.job-total }} "${stories[@]}"
web-settings:
if: |
github.event_name == 'merge_group' ||

2
frontend/.gitignore vendored
View File

@@ -32,6 +32,8 @@ e2e/test-plan/user-preferences/
# Storybook
/storybook-static/
/storybook-stats/
/storybook-stories.txt
debug-storybook.log
# Storybook screenshots (sbshot)

View File

@@ -1,6 +1,6 @@
import { getStoryContext } from '@storybook/test-runner';
import type { TestRunnerConfig } from '@storybook/test-runner';
import type { Page } from 'playwright';
import type { Page, Request } from 'playwright';
const IGNORED_MESSAGES = [
// `preview-head.html` swaps a local stylesheet in for Google Fonts, but the
@@ -41,6 +41,31 @@ const PREPARE_TIMEOUT_MS = 180_000;
const messagesByPage = new WeakMap<Page, CapturedMessage[]>();
const SETTLE_TIMEOUT_MS = 1_000;
const requestsByPage = new WeakMap<Page, Set<Request>>();
/**
* The runner opens the next story in this page as soon as the previous one has
* rendered, so what that one still has in flight answers into state both share:
* the Noz store holds a single thread id. Requests held open on purpose never
* end, so the wait gives up and forgets them.
*/
const settleRequests = async (page: Page): Promise<void> => {
const pending = requestsByPage.get(page);
if (!pending) {
return;
}
const deadline = Date.now() + SETTLE_TIMEOUT_MS;
while (pending.size > 0 && Date.now() < deadline) {
await new Promise((resolve) => {
setTimeout(resolve, 25);
});
}
pending.clear();
};
/**
* When the story under test started rendering, stamped by the preview's
* `beforeEach`. Messages captured before it belong to the previous story: the
@@ -71,6 +96,8 @@ const config: TestRunnerConfig = {
});
},
async preVisit(page): Promise<void> {
await settleRequests(page);
const existing = messagesByPage.get(page);
if (existing) {
existing.length = 0;
@@ -79,6 +106,11 @@ const config: TestRunnerConfig = {
const messages: CapturedMessage[] = [];
messagesByPage.set(page, messages);
const pending = new Set<Request>();
requestsByPage.set(page, pending);
page.on('request', (request) => pending.add(request));
page.on('requestfinished', (request) => pending.delete(request));
page.on('requestfailed', (request) => pending.delete(request));
page.on('console', (message) => {
if (
message.type() === 'error' &&

View File

@@ -0,0 +1,116 @@
#!/usr/bin/env node
/**
* Prints the story files a change can affect, one per line, relative to
* `frontend/`. Reads changed paths (relative to the repo root) on stdin and the
* module graph `storybook build --stats-json` writes.
*
* git diff --name-only main...HEAD | node scripts/select-stories.mjs <preview-stats.json>
* node scripts/select-stories.mjs --all <preview-stats.json>
*
* A story is selected when it imports a changed file, directly or through other
* modules. Every story is selected when a changed file reaches
* `.storybook/` (it renders around every story) or the graph cannot see it.
*/
import { readFileSync } from 'node:fs';
const FULL_RUN_PATHS = [
/^\.github\/workflows\/jsci\.yaml$/,
/^frontend\/\.storybook\//,
/^frontend\/public\//,
/^frontend\/(package\.json|pnpm-lock\.yaml|tsconfig\.json)$/,
/^frontend\/scripts\/(test-storybook\.sh|select-stories\.mjs)$/,
];
// Sass partials are compiled inside the `.scss` that uses them, so the graph
// never lists them.
const STYLE_FILE = /\.(scss|sass|css)$/;
const STORY_FILE = /\.stories\.tsx?$/;
const args = process.argv.slice(2);
const selectAllFlag = args.includes('--all');
const statsPath = args.find((arg) => arg !== '--all');
if (!statsPath) {
console.error('Usage: select-stories.mjs [--all] <preview-stats.json>');
process.exit(2);
}
const { modules } = JSON.parse(readFileSync(statsPath, 'utf8'));
const importersById = new Map(
modules.map((module) => [
module.id,
module.reasons.map((reason) => reason.moduleName),
]),
);
const allStories = [...importersById.keys()].filter((id) =>
STORY_FILE.test(id),
);
function selectAll(reason) {
console.error(`Selecting every story: ${reason}`);
return allStories;
}
/**
* Walks importers up from `id`. Returns the stories reached, or the module
* under `.storybook/` that imports it, which means every story is affected.
*/
function findImportingStories(id) {
const stories = [];
const pending = [id];
const seen = new Set(pending);
while (pending.length > 0) {
const current = pending.pop();
if (current.startsWith('./.storybook/')) {
return { storybookModule: current, stories };
}
if (STORY_FILE.test(current)) {
stories.push(current);
}
const importers = (importersById.get(current) ?? []).filter(
(importer) => !seen.has(importer) && !importer.startsWith('/virtual:'),
);
importers.forEach((importer) => seen.add(importer));
pending.push(...importers);
}
return { stories };
}
function select(changedFiles) {
const fullRunFile = changedFiles.find((file) =>
FULL_RUN_PATHS.some((pattern) => pattern.test(file)),
);
if (fullRunFile) {
return selectAll(`${fullRunFile} changed`);
}
const selected = new Set();
const ids = changedFiles
.filter((file) => file.startsWith('frontend/'))
.map((file) => `./${file.slice('frontend/'.length)}`);
for (const id of ids) {
if (!importersById.has(id)) {
if (STYLE_FILE.test(id)) {
return selectAll(`${id} is not in the module graph`);
}
continue;
}
const { storybookModule, stories } = findImportingStories(id);
if (storybookModule) {
return selectAll(`${id} is imported by ${storybookModule}`);
}
stories.forEach((story) => selected.add(story));
}
return [...selected];
}
const changedFiles = selectAllFlag
? []
: readFileSync(0, 'utf8')
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
const stories = selectAllFlag ? selectAll('--all') : select(changedFiles);
const lines = [...stories]
.sort((a, b) => a.localeCompare(b))
.map((story) => `${story.slice('./'.length)}\n`);
process.stdout.write(lines.join(''));

View File

@@ -1,31 +1,38 @@
#!/usr/bin/env bash
# Tests the static Storybook build. Arguments go to test-storybook: runner flags
# and, optionally, the story files to test (all of them when none are given).
# STORYBOOK_STATIC_DIR points at an existing build; without it the script builds
# one into storybook-static/.
set -euo pipefail
story_count=$(find src -name '*.stories.tsx' | wc -l)
if [ "$story_count" -eq 0 ]; then
echo "No *.stories.tsx found under src/" >&2
port=6006
static_dir=${STORYBOOK_STATIC_DIR:-}
if [ -z "$static_dir" ]; then
static_dir=storybook-static
pnpm storybook:build --quiet
fi
if [ ! -f "$static_dir/index.json" ]; then
echo "No Storybook build in $static_dir/" >&2
exit 1
fi
# jest splits the sorted story files into contiguous shards and exits 1 when a
# shard is empty, which happens on every shard above the file count. The runner
# rejects jest's own `--passWithNoTests`, so skip those shards here.
for arg in "$@"; do
if [[ $arg == --shard=* ]]; then
shard_index=${arg#--shard=}
if [ "${shard_index%%/*}" -gt "$story_count" ]; then
echo "Skipping ${arg#--shard=}: only ${story_count} story files"
exit 0
fi
fi
done
if curl -s -o /dev/null "http://127.0.0.1:$port/"; then
echo "Port $port is taken; stop whatever serves it first." >&2
exit 1
fi
pnpm storybook --ci --quiet &
SB_PID=$!
trap 'kill "$SB_PID" 2>/dev/null || true' EXIT
node_modules/.bin/vite preview --outDir "$static_dir" --host 127.0.0.1 --port "$port" --strictPort >/dev/null &
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT
until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; do
until curl -sf "http://127.0.0.1:$port/index.json" >/dev/null 2>&1; do
kill -0 "$SERVER_PID" 2>/dev/null || {
echo "Static server exited" >&2
exit 1
}
sleep 1
done
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 30000 "$@"
# Index-json mode names its tests after story titles, so story file arguments
# would match nothing.
pnpm exec test-storybook --ci --no-index-json --url "http://127.0.0.1:$port" --maxWorkers=2 --testTimeout 30000 "$@"

View File

@@ -3,6 +3,7 @@ import { screen, userEvent } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
import { hoverTruncated } from '@/storybook/play/hoverTruncated';
import { CustomMultiSelect, CustomSelect } from '../index';
@@ -142,7 +143,7 @@ export const TruncatedOption: Story = {
await userEvent.click(
await screen.findByRole('combobox', { name: 'Service' }),
);
await userEvent.hover(
await hoverTruncated(
await screen.findByRole('option', { name: LONG_LABEL_OPTION.label }),
);
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
@@ -156,7 +157,7 @@ export const TruncatedValue: Story = {
value: LONG_LABEL_OPTION.value,
},
play: async (): Promise<void> => {
await userEvent.hover(await screen.findByText(LONG_LABEL_OPTION.label));
await hoverTruncated(await screen.findByText(LONG_LABEL_OPTION.label));
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });
},
};
@@ -173,7 +174,7 @@ export const MultiTruncatedOption: Story = {
await userEvent.click(
await screen.findByRole('combobox', { name: 'Services' }),
);
await userEvent.hover(
await hoverTruncated(
await screen.findByRole('option', { name: LONG_LABEL_OPTION.label }),
);
await screen.findByRole('tooltip', { name: LONG_LABEL_OPTION.label });

View File

@@ -1,5 +1,4 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, waitFor } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
@@ -9,15 +8,18 @@ import { DataSource } from 'types/common/queryBuilder';
import { QueryBuilderV2 } from '../QueryBuilderV2';
import {
addOnToggles,
appendToAggregation,
expectGaugeDefaults,
expectHistogramDefaults,
expectSingleAggregation,
expectTablePanelAddOns,
expectTimeSeriesAddOns,
expectValuePanelAddOns,
} from './__story_mockdata__/queryBuilder.play';
import {
DEFAULT_ARGS,
expectFirstQuery,
PANEL_EDITOR_ARGS,
PANEL_EDITOR_PATH,
payloadIn,
routeWith,
selectMetric,
} from './QueryBuilderV2.stories.mocks';
import QueryProbe from './QueryProbe';
@@ -60,11 +62,7 @@ export const LogsOnValuePanel: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs) },
},
play: async ({ canvasElement }) => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual(['legend_format']),
);
},
play: expectValuePanelAddOns,
};
/** Metrics on a Table: reduce-to is offered; group by lives in the aggregation row. */
@@ -73,17 +71,7 @@ export const MetricsOnTablePanel: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.metrics) },
},
play: async ({ canvasElement }) => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'having',
'order_by',
'limit',
'legend_format',
'reduce_to',
]),
);
},
play: expectTablePanelAddOns,
};
/** Traces on a time series: every add-on, with group by as a toggle. */
@@ -92,54 +80,21 @@ export const TracesOnTimeSeriesPanel: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.traces) },
},
play: async ({ canvasElement }) => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'group_by',
'having',
'order_by',
'limit',
'legend_format',
]),
);
},
play: expectTimeSeriesAddOns,
};
/** Picking a gauge defaults to avg over time and avg across series. */
export const GaugeMetricDefaults: Story = {
args: METRICS_EXPLORER_ARGS,
parameters: { signoz: { route: metricsExplorerRoute } },
play: async ({ canvasElement }) => {
await selectMetric(canvasElement, 'container_cpu_utilization');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'container_cpu_utilization',
timeAggregation: 'avg',
spaceAggregation: 'avg',
}),
],
});
},
play: expectGaugeDefaults,
};
/** Picking a histogram defaults to the p90 across series. */
export const HistogramMetricDefaults: Story = {
args: METRICS_EXPLORER_ARGS,
parameters: { signoz: { route: metricsExplorerRoute } },
play: async ({ canvasElement }) => {
await selectMetric(canvasElement, 'signoz_latency_bucket');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'signoz_latency_bucket',
spaceAggregation: 'p90',
}),
],
});
},
play: expectHistogramDefaults,
};
/** A Value panel takes a single aggregation: a second one is not accepted. */
@@ -148,22 +103,5 @@ export const ValuePanelTakesOneAggregation: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs) },
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
const { before, after } = appendToAggregation(
canvasElement,
', count_distinct(service.name)',
);
await expect(after).toBe(before);
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
await expect(
payloadIn(canvasElement).queries[0].spec.aggregations,
).toHaveLength(1);
},
play: expectSingleAggregation,
};

View File

@@ -3,6 +3,7 @@
* Do not hand-edit: regenerate instead.
*/
import type { TransactionSpec } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
@@ -134,6 +135,40 @@ export const selectMetric = async (
await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull());
};
const aggregationEditor = (canvasElement: HTMLElement): EditorView => {
const content = within(canvasElement)
.getByTestId('query-aggregation-editor')
.querySelector<HTMLElement>('.cm-content');
const view = content ? EditorView.findFromDOM(content) : null;
if (!view) {
throw new Error('aggregation editor not mounted');
}
return view;
};
const appendTo = (view: EditorView, text: string): TransactionSpec => ({
changes: { from: view.state.doc.length, insert: text },
selection: { anchor: view.state.doc.length + text.length },
userEvent: 'input.type',
});
/**
* Waits until query `A`'s aggregation editor refuses `text`. The builder
* applies a panel's limits one commit after mounting, which a fast static
* build can beat. `state.update` runs the editor's filters without changing
* the document.
*/
export const waitForAggregationLimit = async (
canvasElement: HTMLElement,
text: string,
): Promise<void> => {
await waitFor(() => {
const view = aggregationEditor(canvasElement);
const attempt = view.state.update(appendTo(view, text));
return expect(attempt.newDoc.toString()).toBe(view.state.doc.toString());
});
};
/**
* Appends `text` to query `A`'s aggregation editor and returns its document
* before and after. Dispatched as a CodeMirror transaction: `userEvent.type`
@@ -144,19 +179,9 @@ export const appendToAggregation = (
canvasElement: HTMLElement,
text: string,
): { before: string; after: string } => {
const content = within(canvasElement)
.getByTestId('query-aggregation-editor')
.querySelector<HTMLElement>('.cm-content');
const view = content ? EditorView.findFromDOM(content) : null;
if (!view) {
throw new Error('aggregation editor not mounted');
}
const view = aggregationEditor(canvasElement);
const before = view.state.doc.toString();
view.dispatch({
changes: { from: before.length, insert: text },
selection: { anchor: before.length + text.length },
userEvent: 'input.type',
});
view.dispatch(appendTo(view, text));
// Read synchronously: the document is the editor's own verdict, before
// React state catches up.
return { before, after: view.state.doc.toString() };

View File

@@ -15,7 +15,14 @@ import {
ResolvedQueryBuilderField,
resolveQueryBuilderField,
} from '../../queryBuilderFields.utils';
import { expectFirstQuery, payloadIn } from '../QueryBuilderV2.stories.mocks';
import {
addOnToggles,
appendToAggregation,
expectFirstQuery,
payloadIn,
selectMetric,
waitForAggregationLimit,
} from '../QueryBuilderV2.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
@@ -197,3 +204,95 @@ export const hoverAddFunction = async ({
await hoverForLearnMore(button, 'Add new function');
};
export const expectValuePanelAddOns = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual(['legend_format']),
);
};
export const expectTablePanelAddOns = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'having',
'order_by',
'limit',
'legend_format',
'reduce_to',
]),
);
};
export const expectTimeSeriesAddOns = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await waitFor(() =>
expect(addOnToggles(canvasElement)).toStrictEqual([
'group_by',
'having',
'order_by',
'limit',
'legend_format',
]),
);
};
export const expectGaugeDefaults = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await selectMetric(canvasElement, 'container_cpu_utilization');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'container_cpu_utilization',
timeAggregation: 'avg',
spaceAggregation: 'avg',
}),
],
});
};
export const expectHistogramDefaults = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await selectMetric(canvasElement, 'signoz_latency_bucket');
await expectFirstQuery(canvasElement, {
aggregations: [
expect.objectContaining({
metricName: 'signoz_latency_bucket',
spaceAggregation: 'p90',
}),
],
});
};
const SECOND_AGGREGATION = ', count_distinct(service.name)';
export const expectSingleAggregation = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
await waitForAggregationLimit(canvasElement, SECOND_AGGREGATION);
const { before, after } = appendToAggregation(
canvasElement,
SECOND_AGGREGATION,
);
await expect(after).toBe(before);
await expectFirstQuery(canvasElement, {
aggregations: [{ expression: 'count()' }],
});
await expect(
payloadIn(canvasElement).queries[0].spec.aggregations,
).toHaveLength(1);
};

View File

@@ -0,0 +1,31 @@
import { execFileSync } from 'child_process';
import { resolve } from 'path';
const READ_WORKER_FORMAT = `
(async () => {
const { resolveConfig } = await import('vite');
const config = await resolveConfig(
{ configFile: process.argv[1], mode: 'production' },
'build',
);
process.stdout.write(JSON.stringify(config.worker.format));
})();
`;
describe('Monaco worker bundle', () => {
// An iife worker runs as a sloppy script: the minifier renames on the
// assumption of strict mode, and Annex B hoisting then lets the JSON worker's
// block-level `hasDuplicates` replace the schema collector, so validating any
// non-empty array threw `Cannot read properties of undefined (reading 'include')`.
it('ships workers as ES modules, which always run in strict mode', () => {
const output = execFileSync(
process.execPath,
['--eval', READ_WORKER_FORMAT, resolve(process.cwd(), 'vite.config.ts')],
{ cwd: process.cwd(), encoding: 'utf8' },
);
const format: unknown = JSON.parse(output);
expect(format).toBe('es');
}, 60_000);
});

View File

@@ -510,6 +510,11 @@ Wait on a `danger` toast with `findToastText` (or `getToastText` inside
announced through a visually hidden copy of its text, so a bare query finds two
elements.
Hover a label that only shows a tooltip when it is cut off with `hoverTruncated`
from `play/hoverTruncated`, never a bare `userEvent.hover`. The tooltip is
switched on by the hover that measures it, and the static build, which has no
`act`, opens nothing during that first hover.
The play is a named function in `stories/__story_mockdata__/<page>.play.ts`,
collapsed for review with the other AI-owned files, and the story file only names
it. Branch each check on the args it reads, so every control value the page

View File

@@ -0,0 +1,13 @@
import { userEvent } from 'storybook/test';
/**
* Hovers an element whose tooltip is switched on by the hover that finds it
* cut off. `userEvent` dispatches the whole hover before React renders, and a
* production build, which has no `act` to render between its events, leaves the
* tooltip off for all of it. A second pass finds it on.
*/
export const hoverTruncated = async (element: HTMLElement): Promise<void> => {
await userEvent.hover(element);
await userEvent.unhover(element);
await userEvent.hover(element);
};

View File

@@ -189,6 +189,12 @@ export default defineConfig(({ mode }): UserConfig => {
outDir: 'build',
cssMinify: 'esbuild',
},
// An iife worker runs as a sloppy script, where a function declared in a
// block is hoisted as a `var` over the minifier's renamed outer names (the
// JSON worker's validation then throws on every non-empty array).
worker: {
format: 'es',
},
server: {
open: true,
port: 3301,

View File

@@ -155,6 +155,19 @@ Moved to jest:
"It's covered in jest" names nothing a reviewer can check. If nothing replaces
it, the PR says so and why.
## Which specs a PR runs
A PR runs only the specs its diff can affect; the merge queue runs all of them.
`pnpm select-specs` prints the choice and why, and `pnpm test:changed` runs it.
- A frontend file selects the folders under `tests/` whose pages import it,
through `scripts/select-specs/spec-pages.mts`. A file only the app shell
imports, a dependency, a locale or a stack change selects everything.
- A spec, driver or testdata change selects the specs that import it
(Playwright's `--only-changed`).
- A new folder under `tests/` needs an entry in `spec-pages.mts`, naming the
route components it opens. `pnpm select-specs --check` fails without one.
## Commits
Keep driver changes apart from everything else, so the history reads one

View File

@@ -12,6 +12,8 @@
"env:clean": "rm -rf ../tmp ../.pytest_cache .env.local artifacts && echo 'Cleaned. Run docker container prune if needed.'",
"test": "playwright test",
"test:local": "pnpm env:start && pnpm test",
"test:changed": "node scripts/select-specs/cli.mts --run",
"select-specs": "node scripts/select-specs/cli.mts",
"test:staging": "SIGNOZ_E2E_BASE_URL=https://app.us.staging.signoz.cloud playwright test",
"test:ui": "playwright test --ui",
"test:headed": "playwright test --headed",

View File

@@ -0,0 +1,64 @@
import path from 'node:path';
import type { FrontendGraph } from './graph.mts';
import { SPEC_DATA, SPEC_PAGES } from './spec-pages.mts';
export type Verdict =
| { kind: 'all'; reason: string }
| { kind: 'folders'; folders: string[]; reason: string }
| { kind: 'playwright'; reason: string }
| { kind: 'none'; reason: string };
// Same paths as the `changes` job in `.github/workflows/e2eci.yaml`.
const E2E_TRIGGER =
/^(frontend\/|tests\/|\.github\/workflows\/e2eci\.yaml$|cmd\/enterprise\/Dockerfile\.with-web\.integration$)/;
const E2E_INERT =
/^tests\/e2e\/(.*\.md$|docs\/|specs\/|scripts\/|\.oxlintrc\.json$|\.oxfmtrc\.json$)/;
const FRONTEND_INERT =
/^frontend\/(.*\.md$|docs\/|\.storybook\/|\.cursor\/|__mocks__\/|plugins\/|scripts\/(geo-outlines|test-storybook|post-types-generation)|.*\.(test|spec|stories)\.[jt]sx?$|jest\.config\.|knip\.jsonc$|\.oxlintrc|\.oxfmtrc|\.eslintrc)/;
export function classify(
file: string,
repoRoot: string,
graph: FrontendGraph,
): Verdict {
for (const [folder, prefixes] of Object.entries(SPEC_DATA)) {
if (prefixes.some((prefix) => file.startsWith(prefix))) {
return { kind: 'folders', folders: [folder], reason: 'runtime data' };
}
}
if (!E2E_TRIGGER.test(file) || file.startsWith('tests/integration/')) {
return { kind: 'none', reason: 'outside the e2e trigger' };
}
if (/^tests\/e2e\/(tests|drivers|testdata)\//.test(file)) {
return { kind: 'playwright', reason: 'spec code, --only-changed' };
}
if (E2E_INERT.test(file)) {
return { kind: 'none', reason: 'not loaded by the suite' };
}
if (!file.startsWith('frontend/')) {
return { kind: 'all', reason: 'suite, stack or workflow' };
}
const absolute = path.join(repoRoot, file);
const pages = [...graph.pageReach]
.filter(([, reach]) => reach.has(absolute))
.map(([page]) => page);
if (pages.length > 0) {
const folders = Object.entries(SPEC_PAGES)
.filter(([, specPages]) => specPages.some((page) => pages.includes(page)))
.map(([folder]) => folder);
const reason = pages.length > 3 ? `${pages.length} pages` : pages.join(', ');
return folders.length > 0
? { kind: 'folders', folders, reason }
: { kind: 'none', reason: `no spec opens ${reason}` };
}
if (graph.shell.has(absolute)) {
return { kind: 'all', reason: 'app shell' };
}
if (file.startsWith('frontend/src/') || FRONTEND_INERT.test(file)) {
return { kind: 'none', reason: 'not loaded by the app' };
}
return { kind: 'all', reason: 'frontend build input' };
}

View File

@@ -0,0 +1,229 @@
import { execFileSync, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from 'node:util';
import { classify, type Verdict } from './classify.mts';
import { buildFrontendGraph } from './graph.mts';
import { SPEC_PAGES } from './spec-pages.mts';
const USAGE = `Usage: node scripts/select-specs/cli.mts [options] [-- playwright args]
Picks the Playwright spec files a change can affect.
--base <ref> compare the working tree with <ref> (default: merge-base with origin/main)
--all select every spec without reading the diff
--project <name> Playwright project to list (default: chromium)
--max-shards <n> shards a full run uses (default: 10)
--github-output write mode, specs, shards and shard-total to $GITHUB_OUTPUT
--run run the selected specs, passing the args after --
--check fail when spec-pages.mts and the code disagree
`;
interface ListedSuite {
file: string;
specs?: { tests: { projectName: string }[] }[];
suites?: ListedSuite[];
}
const e2eDir = path.resolve(import.meta.dirname, '../..');
const git = (...args: string[]): string =>
execFileSync('git', args, { cwd: e2eDir, encoding: 'utf8' }).trim();
function playwrightList(project: string, extra: string[]): Map<string, number> {
const result = spawnSync(
'pnpm',
[
'exec',
'playwright',
'test',
'--list',
'--reporter=json',
`--project=${project}`,
'--pass-with-no-tests',
...extra,
],
{
cwd: e2eDir,
encoding: 'utf8',
maxBuffer: 256 * 1024 * 1024,
env: { ...process.env, CI: '' },
},
);
if (result.status !== 0) {
throw new Error(`playwright --list failed:\n${result.stderr}`);
}
const report = JSON.parse(result.stdout) as { suites: ListedSuite[] };
const counts = new Map<string, number>();
const visit = (suite: ListedSuite): void => {
for (const spec of suite.specs ?? []) {
const tests = spec.tests.filter((t) => t.projectName === project).length;
if (tests > 0) {
const file = path.join('tests', suite.file);
counts.set(file, (counts.get(file) ?? 0) + tests);
}
}
suite.suites?.forEach(visit);
};
report.suites.forEach(visit);
return counts;
}
function changedFiles(base: string): string[] {
const tracked = git('diff', '--name-only', '--no-renames', base).split('\n');
const untracked = git(
'ls-files',
'--others',
'--exclude-standard',
'--full-name',
':/',
).split('\n');
return [...new Set([...tracked, ...untracked])].filter(Boolean).sort();
}
function check(repoRoot: string): number {
const graph = buildFrontendGraph(path.join(repoRoot, 'frontend'));
const errors: string[] = [];
const folders = fs
.readdirSync(path.join(e2eDir, 'tests'), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
for (const folder of folders) {
if (!SPEC_PAGES[folder]) {
errors.push(`tests/${folder} has no entry in spec-pages.mts`);
}
}
for (const [folder, pages] of Object.entries(SPEC_PAGES)) {
if (!folders.includes(folder)) {
errors.push(
`spec-pages.mts lists ${folder}, which is not a folder under tests/`,
);
}
for (const page of pages.filter((p) => !graph.pages.has(p))) {
errors.push(
`spec-pages.mts: ${folder} lists ${page}, which pageComponents.ts does not import`,
);
}
}
const covered = new Set(Object.values(SPEC_PAGES).flat());
const uncovered = [...graph.pages.keys()]
.filter((p) => !covered.has(p))
.sort();
console.error(`pages no spec opens: ${uncovered.join(', ')}`);
errors.forEach((e) => console.error(`error: ${e}`));
return errors.length > 0 ? 1 : 0;
}
function main(): number {
const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
base: { type: 'string' },
all: { type: 'boolean', default: false },
project: { type: 'string', default: 'chromium' },
'max-shards': { type: 'string', default: '10' },
'github-output': { type: 'boolean', default: false },
run: { type: 'boolean', default: false },
check: { type: 'boolean', default: false },
help: { type: 'boolean', default: false },
},
});
if (values.help) {
process.stdout.write(USAGE);
return 0;
}
const repoRoot = git('rev-parse', '--show-toplevel');
if (values.check) {
return check(repoRoot);
}
const project = values.project as string;
const maxShards = Number(values['max-shards']);
let mode: 'all' | 'some' | 'none' = 'all';
let specs: string[] = [];
let share = 1;
const report: string[] = [];
if (!values.all) {
const base = values.base ?? git('merge-base', 'HEAD', 'origin/main');
const graph = buildFrontendGraph(path.join(repoRoot, 'frontend'));
const verdicts = changedFiles(base).map((file): [string, Verdict] => [
file,
classify(file, repoRoot, graph),
]);
for (const [file, verdict] of verdicts) {
const target =
verdict.kind === 'folders' ? verdict.folders.join(' ') : verdict.kind;
console.error(`${file}\n ${target} (${verdict.reason})`);
report.push(`| \`${file}\` | ${target} | ${verdict.reason} |`);
}
if (!verdicts.some(([, v]) => v.kind === 'all')) {
const all = playwrightList(project, []);
const folders = new Set(
verdicts.flatMap(([, v]) => (v.kind === 'folders' ? v.folders : [])),
);
const selected = new Set(
[...all.keys()].filter((f) => folders.has(f.split(path.sep)[1])),
);
if (verdicts.some(([, v]) => v.kind === 'playwright')) {
for (const file of playwrightList(project, [
`--only-changed=${base}`,
]).keys()) {
selected.add(file);
}
}
specs = [...selected].sort();
const total = [...all.values()].reduce((a, b) => a + b, 0);
share = specs.reduce((sum, f) => sum + (all.get(f) ?? 0), 0) / total;
mode = specs.length === 0 ? 'none' : 'some';
}
}
const shardTotal =
mode === 'none' ? 0 : Math.max(1, Math.ceil(maxShards * share));
console.error(
mode === 'all'
? `\nall specs, ${shardTotal} shards`
: `\n${specs.length} spec files, ${(share * 100).toFixed(0)}% of tests, ${shardTotal} shards\n${specs.join('\n')}`,
);
if (values['github-output']) {
const shards = Array.from({ length: shardTotal }, (_, i) => i + 1);
fs.appendFileSync(
process.env.GITHUB_OUTPUT as string,
`mode=${mode}\nspecs=${specs.join(' ')}\nshards=${JSON.stringify(shards)}\nshard-total=${shardTotal}\n`,
);
if (process.env.GITHUB_STEP_SUMMARY) {
const heading =
mode === 'all'
? 'Running every spec.'
: `Running ${specs.length} spec files, ${(share * 100).toFixed(0)}% of tests, on ${shardTotal} shards.`;
const table =
report.length > 0
? `\n\n| File | Runs | Why |\n|---|---|---|\n${report.join('\n')}`
: '';
fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${heading}${table}\n`);
}
}
if (values.run && mode !== 'none') {
const run = spawnSync(
'pnpm',
[
'exec',
'playwright',
'test',
`--project=${project}`,
...positionals,
...specs,
],
{
cwd: e2eDir,
stdio: 'inherit',
},
);
return run.status ?? 1;
}
return 0;
}
process.exitCode = main();

View File

@@ -0,0 +1,345 @@
import fs from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
const CODE_EXTENSIONS = new Set([
'.ts',
'.tsx',
'.js',
'.jsx',
'.mts',
'.cts',
'.mjs',
'.cjs',
]);
const STYLE_EXTENSIONS = new Set(['.scss', '.css', '.less']);
const ASSET_EXTENSIONS = new Set([
...STYLE_EXTENSIONS,
'.svg',
'.png',
'.jpg',
'.jpeg',
'.gif',
'.webp',
'.ico',
'.json',
]);
interface ImportRef {
specifier: string;
dynamic: boolean;
/** `specifier` is a Vite glob: `import.meta.glob` or a template `import()`. */
glob?: boolean;
}
export interface FrontendGraph {
frontendDir: string;
/** Every file reachable from the app entry, keyed by absolute path. */
edges: Map<string, Set<string>>;
/** Route components, keyed by the specifier `pageComponents.ts` imports them with. */
pages: Map<string, string>;
/** Files the app loads outside any page: reachable from the entry without entering a page. */
shell: Set<string>;
/** Files each page imports, shell files included. Keyed like `pages`. */
pageReach: Map<string, Set<string>>;
}
function isTypeOnlySyntax(node: ts.Node): boolean {
return (
ts.isTypeNode(node) ||
ts.isInterfaceDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isImportDeclaration(node) ||
(ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword)
);
}
function collectValueNames(source: ts.SourceFile): Set<string> {
const names = new Set<string>();
const visit = (node: ts.Node): void => {
if (isTypeOnlySyntax(node)) {
return;
}
if (ts.isIdentifier(node)) {
names.add(node.text);
}
ts.forEachChild(node, visit);
};
visit(source);
return names;
}
// The build (esbuild, isolatedModules) drops an import whose bindings are only used as types.
function importSurvivesBuild(
node: ts.ImportDeclaration,
valueNames: Set<string>,
): boolean {
const clause = node.importClause;
if (!clause) {
return true;
}
if (clause.isTypeOnly) {
return false;
}
const bindings: string[] = [];
if (clause.name) {
bindings.push(clause.name.text);
}
if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)) {
bindings.push(clause.namedBindings.name.text);
} else if (clause.namedBindings) {
for (const element of clause.namedBindings.elements) {
if (!element.isTypeOnly) {
bindings.push(element.name.text);
}
}
}
return bindings.some((name) => valueNames.has(name));
}
function readImports(file: string): ImportRef[] {
const text = fs.readFileSync(file, 'utf8');
const ext = path.extname(file);
if (STYLE_EXTENSIONS.has(ext)) {
const pattern =
/@(?:use|import|forward)\s+['"]([^'"]+)['"]|url\(\s*['"]?(\.[^)'"]+)/g;
return [...text.matchAll(pattern)].map((m) => ({
specifier: m[1] ?? m[2],
dynamic: false,
}));
}
if (!CODE_EXTENSIONS.has(ext)) {
return [];
}
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
const valueNames = collectValueNames(source);
const refs: ImportRef[] = [];
const visit = (node: ts.Node): void => {
if (ts.isImportDeclaration(node)) {
if (
ts.isStringLiteral(node.moduleSpecifier) &&
importSurvivesBuild(node, valueNames)
) {
refs.push({ specifier: node.moduleSpecifier.text, dynamic: false });
}
} else if (
ts.isExportDeclaration(node) &&
!node.isTypeOnly &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier)
) {
refs.push({ specifier: node.moduleSpecifier.text, dynamic: false });
} else if (ts.isCallExpression(node) && node.arguments.length > 0) {
const [arg] = node.arguments;
const isImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
const isRequire =
ts.isIdentifier(node.expression) && node.expression.text === 'require';
const isGlob =
ts.isPropertyAccessExpression(node.expression) &&
ts.isMetaProperty(node.expression.expression) &&
node.expression.name.text === 'glob';
if ((isImport || isRequire) && ts.isStringLiteralLike(arg)) {
refs.push({ specifier: arg.text, dynamic: isImport });
} else if (isImport && ts.isTemplateExpression(arg)) {
const pattern =
arg.head.text +
arg.templateSpans.map((s) => `*${s.literal.text}`).join('');
refs.push({ specifier: pattern, dynamic: true, glob: true });
} else if (isGlob) {
const patterns = ts.isArrayLiteralExpression(arg)
? [...arg.elements]
: [arg];
for (const p of patterns) {
if (ts.isStringLiteralLike(p) && !p.text.startsWith('!')) {
refs.push({ specifier: p.text, dynamic: true, glob: true });
}
}
}
}
ts.forEachChild(node, visit);
};
visit(source);
return refs;
}
function createResolver(
frontendDir: string,
): (specifier: string, from: string) => string | undefined {
const config = ts.getParsedCommandLineOfConfigFile(
path.join(frontendDir, 'tsconfig.json'),
{},
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => undefined },
);
if (!config) {
throw new Error(`cannot read ${frontendDir}/tsconfig.json`);
}
const options = config.options;
const cache = ts.createModuleResolutionCache(frontendDir, (f) => f, options);
const paths = Object.entries(options.paths ?? {});
const pathsBase =
typeof options.pathsBasePath === 'string'
? options.pathsBasePath
: frontendDir;
const firstExisting = (candidates: string[]): string | undefined =>
candidates.find((c) => fs.existsSync(c) && fs.statSync(c).isFile());
// TypeScript only resolves code, so styles and assets go through `paths` by hand.
const resolveAsset = (specifier: string, from: string): string | undefined => {
const bare = specifier.replace(/\?.*$/, '');
let targets: string[] = [];
if (bare.startsWith('.')) {
targets = [path.resolve(path.dirname(from), bare)];
} else {
for (const [pattern, replacements] of paths) {
const prefix = pattern.replace(/\*$/, '');
if (pattern.endsWith('*') ? bare.startsWith(prefix) : bare === pattern) {
const rest = bare.slice(prefix.length);
targets.push(
...replacements.map((r) => path.resolve(pathsBase, r.replace('*', rest))),
);
}
}
}
const candidates = targets.flatMap((t) => {
const dir = path.dirname(t);
const name = path.basename(t);
return [
t,
`${t}.scss`,
path.join(dir, `_${name}.scss`),
path.join(dir, `_${name}`),
`${t}/index.scss`,
`${t}/_index.scss`,
`${t}.css`,
];
});
return firstExisting(candidates);
};
return (specifier, from) => {
const ext = path.extname(specifier.replace(/\?.*$/, ''));
if (STYLE_EXTENSIONS.has(path.extname(from)) || ASSET_EXTENSIONS.has(ext)) {
const asset = resolveAsset(specifier, from);
if (asset || ext !== '.json') {
return asset;
}
}
const { resolvedModule } = ts.resolveModuleName(
specifier,
from,
options,
ts.sys,
cache,
);
if (!resolvedModule || resolvedModule.isExternalLibraryImport) {
return undefined;
}
const resolved = path.resolve(resolvedModule.resolvedFileName);
return resolved.endsWith('.d.ts') ? undefined : resolved;
};
}
function expandGlob(pattern: string): string[] {
const segments = pattern.split('/');
const firstGlob = segments.findIndex((segment) => /[*?{]/.test(segment));
const base = segments.slice(0, firstGlob).join('/');
if (!fs.existsSync(base)) {
return [];
}
const source = segments
.slice(firstGlob)
.join('/')
.replace(/[.+^$()|[\]\\]/g, '\\$&')
.replace(/\*\*\//g, '\0')
.replace(/\*/g, '[^/]*')
.replace(/\?/g, '[^/]')
.replace(
/\{([^}]*)\}/g,
(_, options: string) => `(?:${options.split(',').join('|')})`,
)
.replace(/\0/g, '(?:.*/)?');
const matcher = new RegExp(`^${source}$`);
return fs
.readdirSync(base, { recursive: true, encoding: 'utf8' })
.filter((relative) => matcher.test(relative.split(path.sep).join('/')))
.map((relative) => path.join(base, relative));
}
function closure(
starts: Iterable<string>,
edges: Map<string, Set<string>>,
stop: Set<string>,
): Set<string> {
const seen = new Set<string>();
const queue = [...starts];
while (queue.length > 0) {
const file = queue.pop() as string;
if (seen.has(file)) {
continue;
}
seen.add(file);
for (const next of edges.get(file) ?? []) {
if (!seen.has(next) && !stop.has(next)) {
queue.push(next);
}
}
}
return seen;
}
export function buildFrontendGraph(frontendDir: string): FrontendGraph {
const resolve = createResolver(frontendDir);
const entry = path.join(frontendDir, 'src/index.tsx');
const pageComponents = path.join(
frontendDir,
'src/AppRoutes/pageComponents.ts',
);
const edges = new Map<string, Set<string>>();
const pages = new Map<string, string>();
const queue = [entry];
while (queue.length > 0) {
const file = queue.pop() as string;
if (edges.has(file)) {
continue;
}
const targets = new Set<string>();
edges.set(file, targets);
for (const ref of readImports(file)) {
if (ref.glob) {
const cwd = ref.specifier.startsWith('/')
? frontendDir
: path.dirname(file);
for (const match of expandGlob(
path.resolve(cwd, ref.specifier.replace(/^\//, '')),
)) {
targets.add(match);
queue.push(match);
}
continue;
}
const target = resolve(ref.specifier, file);
if (!target) {
continue;
}
if (file === pageComponents && ref.dynamic) {
pages.set(ref.specifier, target);
}
targets.add(target);
queue.push(target);
}
}
if (pages.size === 0) {
throw new Error(`no lazy route components found in ${pageComponents}`);
}
const shell = closure([entry], edges, new Set(pages.values()));
const pageReach = new Map<string, Set<string>>();
for (const [specifier, file] of pages) {
pageReach.set(specifier, closure([file], edges, new Set()));
}
return { frontendDir, edges, pages, shell, pageReach };
}

View File

@@ -0,0 +1,103 @@
/**
* Route components each folder under `tests/` opens, keyed by the specifier
* `frontend/src/AppRoutes/pageComponents.ts` lazy-imports them with. A folder
* runs when a changed frontend file is reachable from one of its pages.
* `pnpm select-specs --check` fails when a folder or a page key is missing.
*/
export const SPEC_PAGES: Record<string, string[]> = {
alerts: ['pages/AlertList', 'pages/CreateAlert', 'pages/EditRules'],
'api-monitoring': ['pages/ApiMonitoring'],
'app-shell': [
'pages/HomePage/HomePage',
'pages/Services',
'pages/DashboardsListPage',
'pages/Settings',
'pages/Login',
],
auth: [
'pages/Login',
'pages/SignUp',
'pages/ForgotPassword',
'pages/ResetPassword',
'pages/HomePage/HomePage',
'pages/Settings',
],
dashboards: [
'pages/DashboardsListPage',
'pages/DashboardPage',
'pages/DashboardPage/PanelEditorPage/PanelEditorPage',
],
exceptions: [
'pages/AllErrors',
'pages/ErrorDetails',
'pages/TraceDetailsV3/index',
],
home: ['pages/HomePage/HomePage'],
'infra-monitoring': ['pages/InfrastructureMonitoring'],
integrations: [
'pages/IntegrationsModulePage',
'pages/IntegrationsDetailsPage',
],
'llm-o11y': ['pages/LLMObservability', 'pages/TraceDetailsV3/index'],
'logs-explorer': ['pages/LogsModulePage', 'pages/LogsSettings'],
'logs-pipelines': ['pages/LogsModulePage'],
'messaging-queues': [
'pages/MessagingQueues',
'pages/MessagingQueues/MQDetailPage',
'pages/Celery/CeleryOverview/CeleryOverview',
'pages/Celery/CeleryTask/CeleryTask',
],
meter: ['pages/MeterExplorer'],
'metrics-explorer': ['pages/MetricsExplorer'],
onboarding: [
'pages/OrgOnboarding',
'pages/OnboardingPageV2',
'pages/HomePage/HomePage',
],
'public-dashboard': ['pages/PublicDashboard', 'pages/DashboardPage'],
'query-builder': [
'pages/LogsModulePage',
'pages/TracesModulePage',
'pages/MetricsExplorer',
'pages/DashboardPage',
'pages/DashboardPage/PanelEditorPage/PanelEditorPage',
'pages/CreateAlert',
'pages/EditRules',
],
'quick-filters': ['pages/LogsModulePage'],
routing: [
'pages/HomePage/HomePage',
'pages/Services',
'pages/DashboardsListPage',
'pages/DashboardPage',
'pages/AlertList',
'pages/InfrastructureMonitoring',
'pages/MetricsExplorer',
'pages/TracesModulePage',
'pages/TraceDetailsV3/index',
'pages/LogsModulePage',
'pages/Settings',
],
'saved-views': [
'pages/LogsModulePage',
'pages/TracesModulePage',
'pages/MetricsExplorer',
'pages/MeterExplorer',
],
'service-map': ['modules/Servicemap', 'pages/Services'],
services: [
'pages/Services',
'pages/MetricsApplication/MetricsApplication',
'pages/ServiceTopLevelOperations',
],
settings: ['pages/Settings'],
sso: ['pages/Login', 'pages/Settings'],
'trace-details': ['pages/TraceDetailsV3/index'],
'traces-explorer': ['pages/TracesModulePage', 'pages/TraceDetailsV3/index'],
'traces-funnels': ['pages/TracesModulePage', 'pages/TraceDetailsV3/index'],
};
/** Files outside `frontend/` that a folder reads at runtime, by repo-relative prefix. */
export const SPEC_DATA: Record<string, string[]> = {
'infra-monitoring': ['tests/integration/testdata/inframonitoring/'],
};

View File

@@ -13,12 +13,20 @@
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"types": ["node", "@playwright/test"],
"paths": {
"@tests/*": ["./tests/*"],
"@specs/*": ["./specs/*"]
}
},
"include": ["tests/**/*.ts", "drivers/**/*.ts", "bootstrap/**/*.ts", "playwright.config.ts"],
"include": [
"tests/**/*.ts",
"drivers/**/*.ts",
"bootstrap/**/*.ts",
"scripts/**/*.mts",
"playwright.config.ts"
],
"exclude": ["node_modules", "dist"]
}