Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c5c906cbb | ||
|
|
ac12301818 | ||
|
|
84dba6d670 | ||
|
|
ff83b6c7da | ||
|
|
a328ef5ea7 | ||
|
|
7d366e6368 | ||
|
|
5ea1e38f25 | ||
|
|
d99bb75fc2 | ||
|
|
d79415cbb3 | ||
|
|
1eea4eb8d8 | ||
|
|
385f51f3ba | ||
|
|
540a7ec96b | ||
|
|
4e79d3cd81 | ||
|
|
cbfd4404c1 | ||
|
|
50820b8b40 | ||
|
|
502a3e4f2c | ||
|
|
b57b55f3e1 | ||
|
|
06c662042b | ||
|
|
461669b3fb | ||
|
|
9580a7b2df | ||
|
|
86f9ac5603 | ||
|
|
6a91ce30e3 | ||
|
|
aa3bae9020 | ||
|
|
ba46789226 | ||
|
|
4e494ce4fd | ||
|
|
8c6158e8e3 | ||
|
|
b4cfe050fa | ||
|
|
a199700878 | ||
|
|
2a46b355db | ||
|
|
a50dce2755 | ||
|
|
8dbd319bba | ||
|
|
67e230a647 | ||
|
|
ad155e269c | ||
|
|
f268d0e3eb | ||
|
|
a779ab4667 | ||
|
|
e6aacc899d |
No files matched your search
+5
-1
@@ -14,4 +14,8 @@ DB_PATH=data/sessions.db
|
||||
# Close open sessions that have been idle for longer than this many minutes
|
||||
SESSION_IDLE_TIMEOUT_MINUTES=30
|
||||
# Delete closed sessions whose updatedAt is older than this many days
|
||||
SESSION_DELETE_CLOSED_DAYS=7
|
||||
SESSION_DELETE_CLOSED_DAYS=7
|
||||
|
||||
# Playwright trace recording for scenario runs: on | retain-on-failure | off
|
||||
# (traces often reach ~10 MB per run; can be overridden per run in the run modal)
|
||||
PLAYWRIGHT_TRACE_MODE=off
|
||||
@@ -1,5 +1,6 @@
|
||||
# runtime
|
||||
/data
|
||||
server/data/
|
||||
.env
|
||||
*.log
|
||||
|
||||
@@ -13,3 +14,11 @@ client/dist
|
||||
*storybook.log
|
||||
storybook-static
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
# organization
|
||||
TODO.md
|
||||
|
||||
# IDE/editor
|
||||
.vscode/
|
||||
.idea/
|
||||
.github/
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 1.17.0 - 2026-09-30
|
||||
|
||||
Changes since 1.16.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Files can be deleted from a run: a delete button (with confirmation) in the Files section of the run detail page, `DELETE /scenarios/:id/runs/:runId/files/:fileId`, and the `delete_run_file` MCP tool. The stored file is removed once no scenario or run references it.
|
||||
|
||||
## 1.16.1 - 2026-09-30
|
||||
|
||||
Changes since 1.16.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- Playwright traces are now off by default (`PLAYWRIGHT_TRACE_MODE` defaults to `off`), since a trace often reaches ~10 MB per run. Traces can still be enabled per run in the run modal, via `traceMode` in `POST /scenarios/:id/run`, or for all runs by setting `PLAYWRIGHT_TRACE_MODE`.
|
||||
|
||||
## 1.16.0 - 2026-09-30
|
||||
|
||||
Changes since 1.15.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenarios and snippets are now versioned, starting at version 1. A scenario's version goes up when its name, description, default environment, timeout or steps change; a snippet's when its alias, title, description or code changes. Saving without changes does not create a new version. Credential assignments and scenario files are not versioned.
|
||||
- Each run records the scenario version it runs. The run modal has a version picker (latest by default), `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `version`, and "Repeat run" reuses the run's version.
|
||||
- `context.runSnippet("alias@N")` pins version N of a snippet; `runSnippet("alias")` keeps using the latest. The scenario page's "Used Snippets" section shows which snippets are pinned.
|
||||
- Version numbers are shown on the scenario, snippet and run pages and in the scenario and run lists.
|
||||
- Added `GET /scenarios/:id/versions[/:version]` and `GET /snippets/:id/versions[/:version]`, and the `list_scenario_versions`, `get_scenario_version`, `list_snippet_versions` and `get_snippet_version` MCP tools.
|
||||
- Scenario and snippet exports accept `?version=N` (the `export_scenario` MCP tool takes `version`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Breaking:** scenario and snippet exports now include `version`, and imports require it. An import restores that exact version by id + version: an existing version is left untouched, and a new one is stored under its number and becomes the latest when it is higher than the current latest. Export files from earlier releases need a `version` field added before they can be imported.
|
||||
- Scenario exports now include scenario and step timeouts.
|
||||
- Runs keep their own copy of the steps they were created with. Editing or deleting a step no longer changes past runs, and deleting a step no longer deletes its results from past runs. Existing run steps are backfilled from the current steps on startup.
|
||||
|
||||
## 1.15.0 - 2026-09-30
|
||||
|
||||
Changes since 1.14.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenario runs now record a Playwright trace (screenshots and DOM snapshots) and upload it to the run's files as `trace.zip` when the run finishes. Open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||
- Added the `PLAYWRIGHT_TRACE_MODE` setting (`on` (default), `retain-on-failure`, or `off`) that controls which traces are kept.
|
||||
- Added a "Playwright trace" option to the run modal to override the trace mode for a single run. It defaults to the server's `PLAYWRIGHT_TRACE_MODE`, served by the new `GET /scenarios/run-defaults` endpoint.
|
||||
- `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `traceMode`. The trace mode is stored on the run, shown on the run detail page, and reused by "Repeat run".
|
||||
|
||||
### Changed
|
||||
|
||||
- The run modals on the scenario list and scenario detail pages now share one component.
|
||||
- `server/data/` is now git-ignored.
|
||||
|
||||
## 1.14.0 - 2026-09-30
|
||||
|
||||
Changes since 1.13.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a "Repeat run" button on the scenario run detail page that starts a new run of the same scenario with the same environment and "save session" setting, then navigates to it. The button is disabled when the run's environment has since been deleted.
|
||||
|
||||
## 1.13.0 - 2026-09-30
|
||||
|
||||
Changes since 1.12.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added credential CRUD tools to the MCP server: `list_credentials`, `get_credential`, `create_credential`, `update_credential`, and `delete_credential`. Combined with the existing `add_scenario_credential` tool, credentials can now be created and attached to scenarios entirely via MCP.
|
||||
|
||||
## 1.12.0 - 2026-09-16
|
||||
|
||||
Changes since 1.11.0:
|
||||
|
||||
### Added
|
||||
|
||||
- When a scenario or snippet step fails, a full-page screenshot and the current page HTML are captured and uploaded as run artifacts, so failures can be diagnosed from the run's file list.
|
||||
|
||||
## 1.11.0 - 2026-09-15
|
||||
|
||||
Changes since 1.10.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added export of a scenario as a standalone, plug-and-play Playwright e2e test project (zip archive with `package.json`, `playwright.config.ts`, `test.spec.ts`, `README.md`, `.env`, `credentials.json`, `snippets/*.js`, and any attached scenario files) that runs entirely independently of the liqa backend. Available as a "Export e2e test" button on the scenario detail page, `GET /scenarios/:id/export-e2e`, and the `export_e2e_test` MCP tool.
|
||||
- The exported test only bundles the credentials, snippets, and attached files actually referenced (directly or transitively) by the scenario's steps.
|
||||
- Added a "Used Snippets" section on the scenario detail page listing the snippets referenced by the scenario's steps, linking to each snippet's detail page. Backed by `GET /scenarios/:id/used-snippets`.
|
||||
|
||||
## 1.10.1 - 2026-09-15
|
||||
|
||||
Changes since 1.10.0:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.runSnippet()` now logs "Snippet started"/"finished"/"failed" entries, matching the automatic step start/pass/fail logging.
|
||||
|
||||
### Changed
|
||||
|
||||
- Reworked the Markdown log export format: each log entry is now its own `## [level] timestamp` section with the message as its body, instead of a single large table.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Run logs could persist out of call order (e.g. a snippet's "started" log appearing after its "finished" log) because writes were fire-and-forget and raced against each other. Log entries now carry a per-run sequence number assigned in call order, and queries/exports sort by it.
|
||||
|
||||
## 1.10.0 - 2026-09-15
|
||||
|
||||
Changes since 1.9.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a "Download logs" button on the scenario run detail page: opens a modal to choose Markdown (default) or CSV, then downloads the run's logs in that format.
|
||||
- Added `GET /scenarios/:id/run/:runId/logs/export?format=csv|md` backend endpoint to export a run's logs.
|
||||
|
||||
## 1.9.1 - 2026-09-15
|
||||
|
||||
Changes since 1.9.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenario run logs now include an automatic entry when a step starts and when it finishes (pass or fail), so step boundaries are visible in run logs even for steps that don't call `context.log`/`context.assert` themselves.
|
||||
|
||||
## 1.9.0 - 2026-09-15
|
||||
|
||||
Changes since 1.8.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added `context.assert(fn, description)` for scenario/snippet script steps: runs the given function, requires it to return `true`, logs the outcome (`log` on success, `error` on failure or exception), and throws to stop the step on failure.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented `context.assert` in `docs/scenario.md`.
|
||||
|
||||
## 1.8.0 - 2026-09-15
|
||||
|
||||
Changes since 1.7.1:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.downloadFile()` now accepts `data:` URIs, so scenario steps can save in-script generated content (e.g. a credential JWT) as a run artifact without a network fetch.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented the full scenario step `context` file API (`getScenarioFiles`, `downloadFile`) in `docs/scenario.md`.
|
||||
|
||||
## 1.7.1 - 2026-04-21
|
||||
|
||||
Changes since 1.7.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added MCP tools to upload, list, and fetch scenario files using base64 content payloads.
|
||||
- Added MCP tools to list run artifacts and fetch run artifact content with metadata.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented MCP binary content handling for scenario files and run artifacts.
|
||||
|
||||
## 1.7.0 - 2026-04-21
|
||||
|
||||
Changes since 1.6.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added scenario file storage and run artifact support on the backend.
|
||||
- Added file management UI for scenarios and run details, including artifact lists.
|
||||
- Added snippet CRUD tools to the MCP server.
|
||||
|
||||
### Changed
|
||||
|
||||
- Added dynamic page titles based on the active client content.
|
||||
- Extended the scenarios list to show the latest run status and timestamp.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Exposed file expiry metadata in scenario and run file responses.
|
||||
- Disabled expired download actions in the UI while keeping the action visible.
|
||||
@@ -0,0 +1,58 @@
|
||||
# liqa
|
||||
|
||||
liqa (liquio-qa-bot) is a QA automation service for Liquio environments. It stores **scenarios** (ordered Playwright steps), **snippets** (reusable code run via `context.runSnippet`), **environments**, **credentials** and **sessions**, and runs scenarios in headless Chromium. Scenarios and snippets are versioned; each run records the scenario version it executed.
|
||||
|
||||
It is an npm workspace with two packages:
|
||||
|
||||
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM (`synchronize: true`, so entity changes alter the schema on startup - there are no migrations). REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`.
|
||||
- `client/` - React 19 + Vite SPA (i18n strings in `client/src/i18n/locales/en.json`).
|
||||
|
||||
## Docs
|
||||
|
||||
- [README.md](README.md) - overview
|
||||
- [docs/architecture.md](docs/architecture.md) - services and modules
|
||||
- [docs/development.md](docs/development.md) - local setup, running, testing, Docker
|
||||
- [docs/scenario.md](docs/scenario.md) - scenario execution, script `context` API, versioning, export/import, Playwright traces
|
||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||
- [CHANGELOG.md](CHANGELOG.md) - release notes per version
|
||||
- [.env.example](.env.example) - all configuration variables (validated in `server/src/config/app.config.ts`)
|
||||
|
||||
## Default deployment (docker compose)
|
||||
|
||||
`compose.yaml` at the repo root runs two containers:
|
||||
|
||||
| Service | URL | Notes |
|
||||
|---|---|---|
|
||||
| `server` | http://localhost:13000 | Built from `server/Dockerfile`; reads `.env`; mounts `./data` (SQLite DB `data/liqa.db` + stored files) and `./keys` |
|
||||
| `client` | http://localhost:13001 | Built from `client/Dockerfile`; nginx serves the SPA and proxies `/api/` to `server:3000` |
|
||||
|
||||
Rebuild and restart: `docker compose up -d --build`. Check with `docker compose ps`, `curl localhost:13000/health` and `docker compose logs server`.
|
||||
|
||||
The live database is `data/liqa.db`. Because the schema is synced on startup, back it up before deploying entity changes.
|
||||
|
||||
## Code quality
|
||||
|
||||
Before committing, run and pass all of these (and report the results):
|
||||
|
||||
```bash
|
||||
# server
|
||||
cd server && npm run lint && npx tsc --noEmit -p tsconfig.json && npm test && npm run build
|
||||
# client
|
||||
cd client && npm run lint && npm run build
|
||||
```
|
||||
|
||||
- The server lint has some pre-existing errors (e.g. `no-explicit-any` in `test/mcp.controller.spec.ts`). Don't add new ones; compare against the last commit if unsure.
|
||||
- Don't run prettier over whole existing files; several aren't prettier-clean and it produces unrelated diffs. Format only new files or the lines you changed.
|
||||
- Server tests use an in-memory DB and a Playwright mock (`server/test/__mocks__/playwright.ts`). They create `server/data/` (git-ignored).
|
||||
|
||||
## Committing a new version
|
||||
|
||||
When asked to commit:
|
||||
|
||||
1. **Ask which version to bump** - major, minor or patch - and propose a sensible default based on the changes: patch for fixes and small behavior/default tweaks, minor for new features, major for breaking changes (e.g. changed API or export/import formats that old clients or files can't use).
|
||||
2. Run the code quality checks above.
|
||||
3. Bump `version` in the root `package.json` and in both places at the top of `package-lock.json` (the root entry and `packages[""]`). `server/package.json` and `client/package.json` keep their own versions; don't bump them.
|
||||
4. Add a `## <version> - <YYYY-MM-DD>` entry at the top of `CHANGELOG.md` ("Changes since <previous version>:", then `### Added` / `### Changed` / `### Fixed`). Mark breaking changes with **Breaking:**.
|
||||
5. Update the docs affected by the change (`docs/*.md`, `README.md`, `.env.example`, MCP tool descriptions).
|
||||
6. Build the commit message with the `/git-commit` skill if it is available, following its format and rules. Otherwise use a conventional commit message (`type(scope): subject`, then a bullet list body). Either way, put the version bump in the body as a bullet (e.g. `- bump version to <version>`), not in the subject line. This overrides the skill's rule of putting versions in the subject. Then make the commit with that message.
|
||||
7. **After committing, ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
|
||||
+1
-4
@@ -90,10 +90,7 @@ const SnippetDetailPage = lazy(() =>
|
||||
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
|
||||
);
|
||||
|
||||
const NAV: (
|
||||
| { path: string; labelKey: string; Icon: LucideIcon }
|
||||
| { separator: true }
|
||||
)[] = [
|
||||
const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator: true })[] = [
|
||||
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ separator: true },
|
||||
|
||||
+130
-22
@@ -2,6 +2,9 @@ import type {
|
||||
PaginatedResponse,
|
||||
Credential,
|
||||
Environment,
|
||||
FileMetadata,
|
||||
FileListResponse,
|
||||
RunDefaults,
|
||||
ScenarioCredential,
|
||||
Session,
|
||||
Scenario,
|
||||
@@ -9,7 +12,11 @@ import type {
|
||||
ScenarioRunDetail,
|
||||
ScenarioRunStep,
|
||||
ScenarioStep,
|
||||
ScenarioVersion,
|
||||
Snippet,
|
||||
SnippetVersion,
|
||||
TraceMode,
|
||||
UsedSnippet,
|
||||
} from './types';
|
||||
import { emitApiErrorToast } from '../lib/toast-events';
|
||||
|
||||
@@ -23,9 +30,14 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!(init?.body instanceof FormData) && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...init?.headers },
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = (err as Error).message || 'Network request failed';
|
||||
@@ -113,6 +125,9 @@ export const snippets = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/snippets/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
versions(id: string): Promise<SnippetVersion[]> {
|
||||
return request(`/snippets/${id}/versions`);
|
||||
},
|
||||
exportSnippet(id: string): Promise<unknown> {
|
||||
return request(`/snippets/${id}/export`);
|
||||
},
|
||||
@@ -133,13 +148,16 @@ export const environments = {
|
||||
get(id: string): Promise<Environment> {
|
||||
return request(`/environments/${id}`);
|
||||
},
|
||||
create(name: string, data: Environment['data']): Promise<Environment> {
|
||||
create(name: string, data: Environment['data'], description?: string): Promise<Environment> {
|
||||
return request('/environments', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, data }),
|
||||
body: JSON.stringify({ name, description, data }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'data'>>): Promise<Environment> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Environment, 'name' | 'description' | 'data'>>,
|
||||
): Promise<Environment> {
|
||||
return request(`/environments/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -162,8 +180,13 @@ export const environments = {
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const sessions = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'id',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
|
||||
},
|
||||
get(id: string): Promise<Session> {
|
||||
return request(`/sessions/${id}`);
|
||||
@@ -176,19 +199,29 @@ export const sessions = {
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarios = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=updatedAt&orderDir=DESC`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'updatedAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(
|
||||
`/scenarios?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
|
||||
);
|
||||
},
|
||||
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
|
||||
return request(`/scenarios/${id}`);
|
||||
},
|
||||
create(name: string): Promise<Scenario> {
|
||||
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
|
||||
return request('/scenarios', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name }),
|
||||
body: JSON.stringify({ name, description, environmentId }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>,
|
||||
): Promise<Scenario> {
|
||||
return request(`/scenarios/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -197,12 +230,25 @@ export const scenarios = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/scenarios/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
run(id: string, environmentId: string, saveSession?: boolean): Promise<ScenarioRun> {
|
||||
run(
|
||||
id: string,
|
||||
environmentId: string,
|
||||
saveSession?: boolean,
|
||||
traceMode?: TraceMode,
|
||||
/** Scenario version to run; omit for the latest. */
|
||||
version?: number,
|
||||
): Promise<ScenarioRun> {
|
||||
return request(`/scenarios/${id}/run`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ environmentId, saveSession }),
|
||||
body: JSON.stringify({ environmentId, saveSession, traceMode, version }),
|
||||
});
|
||||
},
|
||||
versions(id: string): Promise<ScenarioVersion[]> {
|
||||
return request(`/scenarios/${id}/versions`);
|
||||
},
|
||||
runDefaults(): Promise<RunDefaults> {
|
||||
return request('/scenarios/run-defaults');
|
||||
},
|
||||
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}`);
|
||||
},
|
||||
@@ -216,8 +262,19 @@ export const scenarios = {
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
},
|
||||
exportScenario(id: string): Promise<string> {
|
||||
return request(`/scenarios/${id}/export`);
|
||||
exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[] } = {
|
||||
includeEnvironment: false,
|
||||
credentialIds: [],
|
||||
},
|
||||
): Promise<string> {
|
||||
const params = new URLSearchParams();
|
||||
params.set('includeEnvironment', String(options.includeEnvironment));
|
||||
for (const cid of options.credentialIds) {
|
||||
params.append('credentialIds', cid);
|
||||
}
|
||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||
},
|
||||
importScenario(payload: unknown): Promise<Scenario> {
|
||||
return request('/scenarios/import', {
|
||||
@@ -225,6 +282,12 @@ export const scenarios = {
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
exportE2eTestUrl(id: string): string {
|
||||
return `${BASE_URL}/scenarios/${id}/export-e2e`;
|
||||
},
|
||||
usedSnippets(id: string): Promise<UsedSnippet[]> {
|
||||
return request(`/scenarios/${id}/used-snippets`);
|
||||
},
|
||||
};
|
||||
|
||||
// ── Runs ─────────────────────────────────────────────────────────────────────
|
||||
@@ -234,12 +297,10 @@ export const runs = {
|
||||
page = 1,
|
||||
limit = 20,
|
||||
status?: string,
|
||||
): Promise<
|
||||
PaginatedResponse<
|
||||
ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }
|
||||
>
|
||||
> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { scenario: { id: string; name: string } }>> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit), orderBy, orderDir });
|
||||
if (status) q.set('status', status);
|
||||
return request(`/scenarios/runs?${q}`);
|
||||
},
|
||||
@@ -247,13 +308,20 @@ export const runs = {
|
||||
scenarioId: string,
|
||||
page = 1,
|
||||
limit = 20,
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
return request(
|
||||
`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
|
||||
);
|
||||
},
|
||||
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
|
||||
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}${qs}`);
|
||||
},
|
||||
exportLogs(scenarioId: string, runId: string, format: 'csv' | 'md'): Promise<string> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}/logs/export?format=${format}`);
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Credentials ──────────────────────────────────────────────────────
|
||||
@@ -279,12 +347,14 @@ export const scenarioCredentials = {
|
||||
export interface CreateStepPayload {
|
||||
title?: string;
|
||||
execCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
execCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export const steps = {
|
||||
@@ -307,3 +377,41 @@ export const steps = {
|
||||
return request(`/scenarios/${scenarioId}/steps/${stepId}`, { method: 'DELETE' });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Files ────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarioFiles = {
|
||||
upload(scenarioId: string, file: File, expiresAt?: Date): Promise<FileMetadata> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (expiresAt) form.append('expiresAt', expiresAt.toISOString());
|
||||
return request(`/scenarios/${scenarioId}/files`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
},
|
||||
list(scenarioId: string, limit = 20, offset = 0): Promise<FileListResponse> {
|
||||
return request(`/scenarios/${scenarioId}/files?limit=${limit}&offset=${offset}`);
|
||||
},
|
||||
/** Returns a URL that can be used as an <a href> for direct download. */
|
||||
contentUrl(scenarioId: string, fileId: string): string {
|
||||
return `${BASE_URL}/scenarios/${scenarioId}/files/${fileId}/content`;
|
||||
},
|
||||
};
|
||||
|
||||
// ── Run Files ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const runFiles = {
|
||||
list(scenarioId: string, runId: string, limit = 20, offset = 0): Promise<FileListResponse> {
|
||||
return request(`/scenarios/${scenarioId}/runs/${runId}/files?limit=${limit}&offset=${offset}`);
|
||||
},
|
||||
/** Returns a URL that can be used as an <a href> for direct download. */
|
||||
contentUrl(scenarioId: string, runId: string, fileId: string): string {
|
||||
return `${BASE_URL}/scenarios/${scenarioId}/runs/${runId}/files/${fileId}/content`;
|
||||
},
|
||||
remove(scenarioId: string, runId: string, fileId: string): Promise<void> {
|
||||
return request(`/scenarios/${scenarioId}/runs/${runId}/files/${fileId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
},
|
||||
};
|
||||
+82
-3
@@ -16,6 +16,7 @@ export interface EnvironmentData {
|
||||
export interface Environment {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
data: EnvironmentData;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -40,10 +41,29 @@ export interface Snippet {
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
/** Latest version number. */
|
||||
version: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SnippetVersion {
|
||||
id: string;
|
||||
snippetId: string;
|
||||
version: number;
|
||||
alias: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** A snippet referenced by a scenario's steps. */
|
||||
export interface UsedSnippet extends Snippet {
|
||||
/** Version pinned via runSnippet('alias@N'), or null for the latest. */
|
||||
pinnedVersion: number | null;
|
||||
}
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type SessionStatus = 'open' | 'closed';
|
||||
@@ -66,6 +86,7 @@ export interface ScenarioStep {
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -82,14 +103,48 @@ export interface ScenarioCredential {
|
||||
export interface Scenario {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
environmentId?: string | null;
|
||||
timeoutSeconds?: number | null;
|
||||
/** Latest version number. */
|
||||
version: number;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
steps?: ScenarioStep[];
|
||||
scenarioCredentials?: ScenarioCredential[];
|
||||
lastRunStatus?: ScenarioRunStatus | null;
|
||||
lastRunAt?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ScenarioStepSnapshot {
|
||||
id: string | null;
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
}
|
||||
|
||||
export interface ScenarioVersion {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
version: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
environmentId: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
steps: ScenarioStepSnapshot[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type ScenarioRunStatus = 'pending' | 'in_progress' | 'pass' | 'fail';
|
||||
|
||||
export type TraceMode = 'on' | 'retain-on-failure' | 'off';
|
||||
|
||||
export interface RunDefaults {
|
||||
traceMode: TraceMode;
|
||||
}
|
||||
|
||||
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
|
||||
|
||||
export type LogLevel = 'log' | 'warn' | 'error';
|
||||
@@ -97,9 +152,12 @@ export type LogLevel = 'log' | 'warn' | 'error';
|
||||
export interface ScenarioRun {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
environmentId: string;
|
||||
environmentId: string | null;
|
||||
sessionId?: string | null;
|
||||
saveSession: boolean;
|
||||
traceMode: TraceMode | null;
|
||||
/** Scenario version the run executes; null for runs created before versioning. */
|
||||
scenarioVersion: number | null;
|
||||
scenario?: Pick<Scenario, 'id' | 'name'>;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
session?: { id: string; sessionName: string };
|
||||
@@ -112,8 +170,12 @@ export interface ScenarioRun {
|
||||
export interface ScenarioRunStep {
|
||||
id: string;
|
||||
runId: string;
|
||||
scenarioStepId: string;
|
||||
scenarioStep: ScenarioStep;
|
||||
/** Live step this run step came from; null once that step is deleted. */
|
||||
scenarioStepId: string | null;
|
||||
// Step content as of the run's scenario version
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
status: RunStepStatus;
|
||||
order: number;
|
||||
description: string | null;
|
||||
@@ -135,3 +197,20 @@ export interface ScenarioRunDetail extends ScenarioRun {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
logs: ScenarioRunLog[];
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FileMetadata {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface FileListResponse {
|
||||
items: FileMetadata[];
|
||||
total: number;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.radioRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.radioRow input[type='radio'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Download } from 'lucide-react';
|
||||
import { Modal, Button } from '../../ui';
|
||||
import styles from './ExportLogsModal.module.css';
|
||||
|
||||
export type LogExportFormat = 'md' | 'csv';
|
||||
|
||||
export interface ExportLogsModalProps {
|
||||
open: boolean;
|
||||
format: LogExportFormat;
|
||||
onFormatChange: (format: LogExportFormat) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportLogsModal({
|
||||
open,
|
||||
format,
|
||||
onFormatChange,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportLogsModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('runs.export_logs_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Download size={14} />
|
||||
{t('runs.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('runs.export_logs_format')}</h4>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name="log-export-format"
|
||||
checked={format === 'md'}
|
||||
onChange={() => onFormatChange('md')}
|
||||
/>
|
||||
<span>{t('runs.export_logs_format_md')}</span>
|
||||
</label>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name="log-export-format"
|
||||
checked={format === 'csv'}
|
||||
onChange={() => onFormatChange('csv')}
|
||||
/>
|
||||
<span>{t('runs.export_logs_format_csv')}</span>
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
.exportModal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.scenarioMeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--color-primary);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.metaRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.metaLabel {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-primary-fg);
|
||||
opacity: 0.7;
|
||||
min-width: 4rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.metaValue {
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-primary-fg);
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.checkboxRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.checkboxRow input[type='checkbox'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Upload } from 'lucide-react';
|
||||
import { Modal, Button, UuidBadge } from '../../ui';
|
||||
import type { Scenario, ScenarioCredential } from '../../api';
|
||||
import styles from './ExportScenarioModal.module.css';
|
||||
|
||||
export interface ExportScenarioModalProps {
|
||||
open: boolean;
|
||||
scenario: Scenario | null;
|
||||
scenarioCredentials: ScenarioCredential[];
|
||||
environment: Pick<{ id: string; name: string }, 'id' | 'name'> | null;
|
||||
includeEnvironment: boolean;
|
||||
onIncludeEnvironmentChange: (v: boolean) => void;
|
||||
includedCredentialIds: Set<string>;
|
||||
onCredentialToggle: (id: string, checked: boolean) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportScenarioModal({
|
||||
open,
|
||||
scenario,
|
||||
scenarioCredentials,
|
||||
environment,
|
||||
includeEnvironment,
|
||||
onIncludeEnvironmentChange,
|
||||
includedCredentialIds,
|
||||
onCredentialToggle,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportScenarioModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('scenarios.export_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{scenario && (
|
||||
<div className={styles.exportModal}>
|
||||
<div className={styles.scenarioMeta}>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_name')}</span>
|
||||
<span className={styles.metaValue}>{scenario.name}</span>
|
||||
</div>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_id')}</span>
|
||||
<span className={styles.metaValue}>
|
||||
<UuidBadge id={scenario.id} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{environment && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_environment')}</h4>
|
||||
<label className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeEnvironment}
|
||||
onChange={(e) => onIncludeEnvironmentChange(e.target.checked)}
|
||||
/>
|
||||
<span>{environment.name}</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenarioCredentials.length > 0 && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_credentials')}</h4>
|
||||
{scenarioCredentials.map((sc) => (
|
||||
<label key={sc.credentialId} className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includedCredentialIds.has(sc.credentialId)}
|
||||
onChange={(e) => onCredentialToggle(sc.credentialId, e.target.checked)}
|
||||
/>
|
||||
<span>{sc.credential?.name ?? sc.alias}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Play } from 'lucide-react';
|
||||
import { Modal, Button, Select } from '../../ui';
|
||||
import type { Environment } from '../../api';
|
||||
import type { Environment, ScenarioVersion, TraceMode } from '../../api';
|
||||
|
||||
const TRACE_MODES: TraceMode[] = ['on', 'retain-on-failure', 'off'];
|
||||
|
||||
export interface RunScenarioModalProps {
|
||||
open: boolean;
|
||||
@@ -10,6 +12,14 @@ export interface RunScenarioModalProps {
|
||||
onEnvSelect: (envId: string) => void;
|
||||
saveSessionFlag: boolean;
|
||||
onSaveSessionChange: (flag: boolean) => void;
|
||||
/** Scenario versions, newest first; empty while loading. */
|
||||
versions: Pick<ScenarioVersion, 'version' | 'createdAt'>[];
|
||||
/** Selected version, or null for the latest. */
|
||||
selectedVersion: number | null;
|
||||
onVersionChange: (version: number | null) => void;
|
||||
traceMode: TraceMode;
|
||||
defaultTraceMode: TraceMode | null;
|
||||
onTraceModeChange: (mode: TraceMode) => void;
|
||||
onClose: () => void;
|
||||
onRun: () => void;
|
||||
isRunning: boolean;
|
||||
@@ -23,6 +33,12 @@ export function RunScenarioModal({
|
||||
onEnvSelect,
|
||||
saveSessionFlag,
|
||||
onSaveSessionChange,
|
||||
versions,
|
||||
selectedVersion,
|
||||
onVersionChange,
|
||||
traceMode,
|
||||
defaultTraceMode,
|
||||
onTraceModeChange,
|
||||
onClose,
|
||||
onRun,
|
||||
isRunning,
|
||||
@@ -58,6 +74,25 @@ export function RunScenarioModal({
|
||||
onChange={(e) => onEnvSelect(e.target.value)}
|
||||
options={environments.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_version_label')}
|
||||
value={selectedVersion == null ? '' : String(selectedVersion)}
|
||||
onChange={(e) => onVersionChange(e.target.value ? Number(e.target.value) : null)}
|
||||
options={[
|
||||
{
|
||||
value: '',
|
||||
label: versions[0]
|
||||
? t('scenarios.run_modal_version_latest_n', { version: versions[0].version })
|
||||
: t('scenarios.run_modal_version_latest'),
|
||||
},
|
||||
...versions.map((v) => ({
|
||||
value: String(v.version),
|
||||
label: `v${v.version} — ${new Date(v.createdAt).toLocaleString()}`,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
@@ -73,6 +108,19 @@ export function RunScenarioModal({
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_trace_label')}
|
||||
value={traceMode}
|
||||
onChange={(e) => onTraceModeChange(e.target.value as TraceMode)}
|
||||
options={TRACE_MODES.map((mode) => ({
|
||||
value: mode,
|
||||
label:
|
||||
t(`scenarios.trace_mode_${mode.replace(/-/g, '_')}`) +
|
||||
(mode === defaultTraceMode ? ` ${t('scenarios.trace_mode_default_suffix')}` : ''),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
|
||||
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
|
||||
export { ExportScenarioModal } from './ExportScenarioModal';
|
||||
export type { ExportScenarioModalProps } from './ExportScenarioModal';
|
||||
export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
export { ExportLogsModal } from './ExportLogsModal';
|
||||
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
const APP_NAME = 'Liqa';
|
||||
|
||||
/**
|
||||
* Sets document.title to "<title> | Liqa" for the current page.
|
||||
* Pass undefined or empty string to fall back to just "Liqa".
|
||||
*/
|
||||
export function usePageTitle(title: string | null | undefined): void {
|
||||
useEffect(() => {
|
||||
const prev = document.title;
|
||||
document.title = title ? `${title} | ${APP_NAME}` : APP_NAME;
|
||||
return () => {
|
||||
document.title = prev;
|
||||
};
|
||||
}, [title]);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { scenarios } from '../api';
|
||||
import type { RunDefaults } from '../api';
|
||||
|
||||
// Server run defaults don't change while the app is open; fetch them once
|
||||
let cached: Promise<RunDefaults> | null = null;
|
||||
|
||||
/**
|
||||
* Returns the server-configured defaults for new scenario runs, or null
|
||||
* while they are loading (or if the request failed).
|
||||
*/
|
||||
export function useRunDefaults(): RunDefaults | null {
|
||||
const [defaults, setDefaults] = useState<RunDefaults | null>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
cached ??= scenarios.runDefaults().catch((err: unknown) => {
|
||||
cached = null;
|
||||
throw err;
|
||||
});
|
||||
cached.then((d) => !cancelled && setDefaults(d)).catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return defaults;
|
||||
}
|
||||
@@ -36,6 +36,7 @@
|
||||
"updated": "Environment updated",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_description": "Description",
|
||||
"col_data": "Data",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No environments yet.",
|
||||
@@ -56,10 +57,13 @@
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. staging, production",
|
||||
"form_name_required": "Name is required",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this environment",
|
||||
"form_data": "Data (JSON)",
|
||||
"form_data_invalid_json": "Must be a valid JSON object",
|
||||
"back": "Environments",
|
||||
"field_id": "ID",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
"section_data": "Data"
|
||||
@@ -115,12 +119,16 @@
|
||||
"field_updated": "Updated",
|
||||
"field_lastUsed": "Last Used"
|
||||
},
|
||||
"scenarios": { "title": "Scenarios",
|
||||
"scenarios": {
|
||||
"title": "Scenarios",
|
||||
"created": "Scenario created",
|
||||
"updated": "Scenario updated",
|
||||
"run_started": "Scenario run started",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_version": "Version",
|
||||
"col_description": "Description",
|
||||
"col_last_run": "Last Run",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No scenarios yet.",
|
||||
"loading": "Loading…",
|
||||
@@ -128,6 +136,8 @@
|
||||
"action_delete": "Delete",
|
||||
"field_id": "ID",
|
||||
"field_name": "Name",
|
||||
"field_version": "Version",
|
||||
"field_description": "Description",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
@@ -141,6 +151,7 @@
|
||||
"action_edit": "Edit",
|
||||
"action_runs": "Runs",
|
||||
"action_export": "Export",
|
||||
"action_export_e2e": "Export e2e test",
|
||||
"action_import": "Import",
|
||||
"import_error": "Failed to import scenario",
|
||||
"action_save": "Create",
|
||||
@@ -148,10 +159,18 @@
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Scenario",
|
||||
"edit_title": "Edit Scenario",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this scenario",
|
||||
"form_environment": "Default Environment",
|
||||
"form_environment_none": "None (no default environment)",
|
||||
"field_environment": "Default Environment",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. Login flow",
|
||||
"form_name_required": "Name is required",
|
||||
"credentials_heading": "Credentials",
|
||||
"used_snippets_heading": "Used Snippets",
|
||||
"used_snippet_pinned": "v{{version}} (pinned)",
|
||||
"used_snippet_latest": "Latest (v{{version}})",
|
||||
"cred_empty": "No credentials assigned.",
|
||||
"cred_col_alias": "Alias",
|
||||
"cred_col_name": "Credential",
|
||||
@@ -169,7 +188,23 @@
|
||||
"run_modal_title": "Select environment",
|
||||
"run_modal_env_label": "Environment",
|
||||
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
|
||||
"run_modal_env_required": "Please select an environment"
|
||||
"run_modal_env_required": "Please select an environment",
|
||||
"run_modal_version_label": "Version",
|
||||
"run_modal_version_latest": "Latest",
|
||||
"run_modal_version_latest_n": "Latest (v{{version}})",
|
||||
"run_modal_trace_label": "Playwright trace",
|
||||
"trace_mode_on": "Always keep",
|
||||
"trace_mode_retain_on_failure": "Keep on failure",
|
||||
"trace_mode_off": "Off",
|
||||
"trace_mode_default_suffix": "(default)",
|
||||
"export_modal_title": "Export Scenario",
|
||||
"export_include_environment": "Include Environment",
|
||||
"export_include_credentials": "Include Credentials",
|
||||
"form_timeout": "Scenario Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 600",
|
||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
|
||||
"field_name": "Name",
|
||||
"field_id": "ID"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -205,7 +240,10 @@
|
||||
"form_session_placeholder": "e.g. my-session",
|
||||
"form_session_required": "Session name is required",
|
||||
"form_exec_code": "Exec code",
|
||||
"form_exec_code_placeholder": "return await page.title();"
|
||||
"form_exec_code_placeholder": "return await page.title();",
|
||||
"form_timeout": "Step Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 60",
|
||||
"form_timeout_hint": "Max seconds for this step (default: 60)"
|
||||
},
|
||||
"runs": {
|
||||
"title": "Runs",
|
||||
@@ -216,12 +254,15 @@
|
||||
"col_scenario": "Scenario",
|
||||
"col_status": "Status",
|
||||
"col_steps": "Steps",
|
||||
"col_version": "Version",
|
||||
"col_created": "Started",
|
||||
"field_id": "ID",
|
||||
"field_status": "Status",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Started",
|
||||
"field_updated": "Updated",
|
||||
"field_trace": "Playwright trace",
|
||||
"field_scenario_version": "Scenario version",
|
||||
"steps_heading": "Step runs",
|
||||
"step_title": "Title",
|
||||
"logs_heading": "Logs",
|
||||
@@ -233,7 +274,15 @@
|
||||
"step_description": "Result",
|
||||
"log_level": "Level",
|
||||
"log_message": "Message",
|
||||
"log_time": "Time"
|
||||
"log_time": "Time",
|
||||
"action_download_logs": "Download logs",
|
||||
"action_repeat": "Repeat run",
|
||||
"repeat_no_environment": "The environment used by this run no longer exists",
|
||||
"export_logs_modal_title": "Export logs",
|
||||
"export_logs_format": "Format",
|
||||
"export_logs_format_md": "Markdown (.md)",
|
||||
"export_logs_format_csv": "CSV (.csv)",
|
||||
"action_export": "Export"
|
||||
},
|
||||
"snippets": {
|
||||
"title": "Snippets",
|
||||
@@ -263,6 +312,7 @@
|
||||
"form_code_required": "Code is required",
|
||||
"field_id": "ID",
|
||||
"field_alias": "Alias",
|
||||
"field_version": "Version",
|
||||
"field_title": "Title",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
@@ -271,5 +321,26 @@
|
||||
"action_export": "Export",
|
||||
"action_import": "Import",
|
||||
"import_error": "Failed to import snippet"
|
||||
},
|
||||
"files": {
|
||||
"title": "Files",
|
||||
"upload": "Upload",
|
||||
"uploadTitle": "Upload File",
|
||||
"uploadSuccess": "File uploaded successfully",
|
||||
"name": "Name",
|
||||
"mimeType": "MIME Type",
|
||||
"size": "Size",
|
||||
"expiresAt": "Expires At",
|
||||
"expiresAtLabel": "Expires At (optional)",
|
||||
"createdAt": "Created",
|
||||
"download": "Download",
|
||||
"delete": "Delete",
|
||||
"deleteTitle": "Delete file",
|
||||
"confirmDelete": "Are you sure you want to delete \"{{name}}\" from this run?",
|
||||
"deleteSuccess": "File deleted",
|
||||
"expiredTooltip": "File is expired",
|
||||
"empty": "No files uploaded.",
|
||||
"totalCount": "Total: {{count}} file(s)",
|
||||
"artifactsTitle": "Artifacts"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { KeyRound, X, Save } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
@@ -8,6 +9,7 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function CreateCredentialPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('credentials.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
|
||||
import { CodeBlock } from '../../ui';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
@@ -16,6 +17,7 @@ export function CredentialDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(credential?.name ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { credentials } from '../../api';
|
||||
@@ -100,6 +101,7 @@ function AddCredentialCard() {
|
||||
|
||||
export function CredentialsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('credentials.title'));
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Credential[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { KeyRound, X, Save } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
@@ -15,6 +16,11 @@ export function EditCredentialPage() {
|
||||
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
credential
|
||||
? `${t('credentials.edit_title')} — ${credential.name}`
|
||||
: t('credentials.edit_title'),
|
||||
);
|
||||
const [data, setData] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Globe, Save } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
@@ -8,10 +9,12 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function CreateEnvironmentPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('environments.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
@@ -42,7 +45,11 @@ export function CreateEnvironmentPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const env = await environments.create(name.trim(), parsedData);
|
||||
const env = await environments.create(
|
||||
name.trim(),
|
||||
parsedData,
|
||||
description.trim() || undefined,
|
||||
);
|
||||
toast.success(t('environments.created'));
|
||||
navigate(`/environments/${env.id}`);
|
||||
} catch (err) {
|
||||
@@ -83,6 +90,15 @@ export function CreateEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Globe, Save } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
@@ -15,6 +16,10 @@ export function EditEnvironmentPage() {
|
||||
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
env ? `${t('environments.edit_title')} — ${env.name}` : t('environments.edit_title'),
|
||||
);
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
@@ -28,6 +33,7 @@ export function EditEnvironmentPage() {
|
||||
.then((data) => {
|
||||
setEnv(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
@@ -60,6 +66,7 @@ export function EditEnvironmentPage() {
|
||||
try {
|
||||
await environments.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
data: parsedData,
|
||||
});
|
||||
toast.success(t('environments.updated'));
|
||||
@@ -109,6 +116,15 @@ export function EditEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import type { Environment } from '../../api';
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
DescriptionList,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -24,6 +26,7 @@ export function EnvironmentDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(env?.name ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
|
||||
@@ -117,6 +120,17 @@ export function EnvironmentDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{env.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={env.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
|
||||
<Card>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
@@ -117,6 +118,7 @@ function AddEnvironmentCard() {
|
||||
|
||||
export function EnvironmentsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('environments.title'));
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Environment[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Activity } from 'lucide-react';
|
||||
import { runs } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
@@ -12,6 +14,7 @@ import {
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -31,34 +34,49 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
};
|
||||
|
||||
type AllRunRow = ScenarioRun & {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
scenario: { id: number; name: string };
|
||||
scenario: { id: string; name: string };
|
||||
};
|
||||
|
||||
export function AllRunsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('runs.title'));
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
data: items = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery<AllRunRow[]>({
|
||||
queryKey: ['runs'],
|
||||
queryFn: async () => {
|
||||
const res = await runs.listAll();
|
||||
return res.data as AllRunRow[];
|
||||
},
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['runs', sortBy, sortDir, page, pageSize],
|
||||
queryFn: () =>
|
||||
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
refetchInterval: 10_000,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
const items = (data?.data ?? []) as AllRunRow[];
|
||||
const total = data?.total ?? 0;
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => setPage(p);
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const columns: TableColumn<AllRunRow>[] = [
|
||||
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
|
||||
{
|
||||
key: 'scenario',
|
||||
key: 'scenario.name',
|
||||
header: t('runs.col_scenario'),
|
||||
sortable: true,
|
||||
render: (r) => (
|
||||
<span
|
||||
className={styles.linkCell}
|
||||
@@ -75,18 +93,25 @@ export function AllRunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 110,
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
key: 'scenarioVersion',
|
||||
header: t('runs.col_version'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
render: (r) =>
|
||||
r.scenarioVersion != null ? (
|
||||
`v${r.scenarioVersion}`
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -109,9 +134,16 @@ export function AllRunsPage() {
|
||||
rowKey={(r) => r.id}
|
||||
loading={isLoading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { runs } from '../../api';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { runs, runFiles } from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioRunDetail,
|
||||
@@ -10,11 +11,18 @@ import type {
|
||||
ScenarioRunStatus,
|
||||
RunStepStatus,
|
||||
LogLevel,
|
||||
FileMetadata,
|
||||
} from '../../api';
|
||||
import { scenarios } from '../../api';
|
||||
import {
|
||||
DeleteConfirmationModal,
|
||||
ExportLogsModal,
|
||||
type LogExportFormat,
|
||||
} from '../../components/modals';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Button,
|
||||
Breadcrumbs,
|
||||
Card,
|
||||
CodeBlock,
|
||||
@@ -24,10 +32,19 @@ import {
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import { ChevronDown, ChevronRight, ClipboardList, Activity } from 'lucide-react';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
Activity,
|
||||
Download,
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
} from 'lucide-react';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
@@ -62,13 +79,21 @@ const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
|
||||
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
|
||||
|
||||
export function RunDetailPage() {
|
||||
const { runId } = useParams<{ runId: string }>();
|
||||
// Remount per run so "Repeat run" navigation starts from a clean state
|
||||
return <RunDetail key={runId} />;
|
||||
}
|
||||
|
||||
function RunDetail() {
|
||||
const { t } = useTranslation();
|
||||
const { id, runId } = useParams<{ id: string; runId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [run, setRun] = useState<ScenarioRunDetail | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [polling, setPolling] = useState(false);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
@@ -77,6 +102,15 @@ export function RunDetailPage() {
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [expandAll, setExpandAll] = useState(false);
|
||||
const [expandedStepIds, setExpandedStepIds] = useState<Set<string>>(new Set());
|
||||
const [artifacts, setArtifacts] = useState<FileMetadata[]>([]);
|
||||
const [artifactsTotal, setArtifactsTotal] = useState(0);
|
||||
const [artifactsLoading, setArtifactsLoading] = useState(false);
|
||||
const [exportLogsOpen, setExportLogsOpen] = useState(false);
|
||||
const [exportLogsFormat, setExportLogsFormat] = useState<LogExportFormat>('md');
|
||||
const [exportingLogs, setExportingLogs] = useState(false);
|
||||
const [pendingDeleteFile, setPendingDeleteFile] = useState<FileMetadata | null>(null);
|
||||
const [deletingFile, setDeletingFile] = useState(false);
|
||||
const [repeating, setRepeating] = useState(false);
|
||||
const logSearchRef = useRef('');
|
||||
const LOG_PAGE_SIZE = 25;
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
@@ -89,6 +123,72 @@ export function RunDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDownload = (url: string, filename: string) => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
|
||||
const isFileExpired = (file: FileMetadata) =>
|
||||
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
|
||||
|
||||
const handleExportLogs = async () => {
|
||||
if (!id || !runId) return;
|
||||
setExportingLogs(true);
|
||||
try {
|
||||
const content = await runs.exportLogs(id, runId, exportLogsFormat);
|
||||
const mimeType = exportLogsFormat === 'csv' ? 'text/csv' : 'text/markdown';
|
||||
const blob = new Blob([content], { type: mimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `run-${runId}-logs.${exportLogsFormat}`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportLogsOpen(false);
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
} finally {
|
||||
setExportingLogs(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepeatRun = async () => {
|
||||
if (!id || !run?.environmentId) return;
|
||||
setRepeating(true);
|
||||
try {
|
||||
const newRun = await scenarios.run(
|
||||
id,
|
||||
run.environmentId,
|
||||
run.saveSession,
|
||||
run.traceMode ?? undefined,
|
||||
run.scenarioVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${newRun.id}`);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRepeating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteFile = async () => {
|
||||
if (!id || !runId || !pendingDeleteFile) return;
|
||||
setDeletingFile(true);
|
||||
try {
|
||||
await runFiles.remove(id, runId, pendingDeleteFile.id);
|
||||
toast.success(t('files.deleteSuccess'));
|
||||
setPendingDeleteFile(null);
|
||||
await loadArtifacts();
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
} finally {
|
||||
setDeletingFile(false);
|
||||
}
|
||||
};
|
||||
|
||||
const manualRefresh = () => {
|
||||
if (!id || !runId) return;
|
||||
runs
|
||||
@@ -101,6 +201,22 @@ export function RunDetailPage() {
|
||||
.catch((err: Error) => setError(err.message));
|
||||
};
|
||||
|
||||
const loadArtifacts = useCallback(async () => {
|
||||
if (!id || !runId) return;
|
||||
setArtifactsLoading(true);
|
||||
try {
|
||||
const result = await runFiles.list(id, runId);
|
||||
setArtifacts(result.items);
|
||||
setArtifactsTotal(result.total);
|
||||
} catch {
|
||||
// Silently fail - artifacts are not critical
|
||||
setArtifacts([]);
|
||||
setArtifactsTotal(0);
|
||||
} finally {
|
||||
setArtifactsLoading(false);
|
||||
}
|
||||
}, [id, runId]);
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
setDebouncedSearch(logSearch);
|
||||
@@ -127,6 +243,7 @@ export function RunDetailPage() {
|
||||
if (cancelled) return;
|
||||
setScenario(sc);
|
||||
setRun(r);
|
||||
loadArtifacts();
|
||||
if (!FINAL.includes(r.status)) {
|
||||
setPolling(true);
|
||||
pollRef.current = setInterval(async () => {
|
||||
@@ -135,7 +252,10 @@ export function RunDetailPage() {
|
||||
if (cancelled) return;
|
||||
setRun(updated);
|
||||
setPulseKey((k) => k + 1);
|
||||
if (FINAL.includes(updated.status)) stopPolling();
|
||||
if (FINAL.includes(updated.status)) {
|
||||
stopPolling();
|
||||
await loadArtifacts();
|
||||
}
|
||||
} catch {
|
||||
stopPolling();
|
||||
}
|
||||
@@ -153,7 +273,7 @@ export function RunDetailPage() {
|
||||
cancelled = true;
|
||||
stopPolling();
|
||||
};
|
||||
}, [id, runId]);
|
||||
}, [id, runId, loadArtifacts]);
|
||||
|
||||
const stepColumns: TableColumn<ScenarioRunStep>[] = [
|
||||
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
|
||||
@@ -161,7 +281,7 @@ export function RunDetailPage() {
|
||||
key: 'title',
|
||||
header: t('runs.step_title'),
|
||||
width: 220,
|
||||
render: (s) => s.scenarioStep?.title ?? <span className={styles.muted}>–</span>,
|
||||
render: (s) => s.title ?? <span className={styles.muted}>–</span>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
@@ -214,6 +334,7 @@ export function RunDetailPage() {
|
||||
),
|
||||
render: (s) => {
|
||||
const isExpanded = expandAll || expandedStepIds.has(s.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
@@ -321,12 +442,27 @@ export function RunDetailPage() {
|
||||
{ label: `${runId}` },
|
||||
]}
|
||||
/>
|
||||
<AutoRefreshIndicator
|
||||
active={polling}
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={manualRefresh}
|
||||
/>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
{run && (
|
||||
<span title={run.environmentId ? undefined : t('runs.repeat_no_environment')}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={handleRepeatRun}
|
||||
disabled={!run.environmentId || repeating}
|
||||
>
|
||||
<RotateCcw size={14} />
|
||||
{t('runs.action_repeat')}
|
||||
</Button>
|
||||
</span>
|
||||
)}
|
||||
<AutoRefreshIndicator
|
||||
active={polling}
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={manualRefresh}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
|
||||
@@ -350,6 +486,20 @@ export function RunDetailPage() {
|
||||
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
|
||||
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
|
||||
];
|
||||
if (run.scenarioVersion != null) {
|
||||
items.push({
|
||||
term: t('runs.field_scenario_version'),
|
||||
detail: <span>v{run.scenarioVersion}</span>,
|
||||
});
|
||||
}
|
||||
if (run.traceMode) {
|
||||
items.push({
|
||||
term: t('runs.field_trace'),
|
||||
detail: (
|
||||
<span>{t(`scenarios.trace_mode_${run.traceMode.replace(/-/g, '_')}`)}</span>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (run.environment) {
|
||||
items.push({
|
||||
term: 'Environment',
|
||||
@@ -398,11 +548,17 @@ export function RunDetailPage() {
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
|
||||
<Search
|
||||
value={logSearch}
|
||||
onChange={setLogSearch}
|
||||
placeholder={t('runs.logs_search_placeholder')}
|
||||
/>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<Search
|
||||
value={logSearch}
|
||||
onChange={setLogSearch}
|
||||
placeholder={t('runs.logs_search_placeholder')}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => setExportLogsOpen(true)}>
|
||||
<Download size={14} />
|
||||
{t('runs.action_download_logs')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
columns={logColumns}
|
||||
@@ -421,8 +577,103 @@ export function RunDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(artifactsTotal > 0 || artifactsLoading) && (
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('files.artifactsTitle')}</h2>
|
||||
<Table<FileMetadata>
|
||||
loading={artifactsLoading}
|
||||
data={artifacts}
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{ key: 'name', header: t('files.name'), render: (f) => f.name },
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
render: (f) => f.mimeType,
|
||||
},
|
||||
{
|
||||
key: 'size',
|
||||
header: t('files.size'),
|
||||
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
|
||||
},
|
||||
{
|
||||
key: 'expiresAt',
|
||||
header: t('files.expiresAt'),
|
||||
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
header: t('files.createdAt'),
|
||||
render: (f) => <Timestamp value={f.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'download',
|
||||
header: '',
|
||||
render: (f) => {
|
||||
const expired = isFileExpired(f);
|
||||
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
|
||||
|
||||
return (
|
||||
<span title={tooltip}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={tooltip}
|
||||
aria-label={tooltip}
|
||||
disabled={expired}
|
||||
onClick={() =>
|
||||
handleFileDownload(runFiles.contentUrl(id!, runId!, f.id), f.name)
|
||||
}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
header: '',
|
||||
render: (f) => (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={t('files.delete')}
|
||||
aria-label={t('files.delete')}
|
||||
onClick={() => setPendingDeleteFile(f)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
] satisfies TableColumn<FileMetadata>[]
|
||||
}
|
||||
emptyMessage={t('files.empty')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<ExportLogsModal
|
||||
open={exportLogsOpen}
|
||||
format={exportLogsFormat}
|
||||
onFormatChange={setExportLogsFormat}
|
||||
onClose={() => setExportLogsOpen(false)}
|
||||
onExport={handleExportLogs}
|
||||
isExporting={exportingLogs}
|
||||
/>
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={pendingDeleteFile != null}
|
||||
title={t('files.deleteTitle')}
|
||||
message={t('files.confirmDelete', { name: pendingDeleteFile?.name ?? '' })}
|
||||
onClose={() => setPendingDeleteFile(null)}
|
||||
onConfirm={handleDeleteFile}
|
||||
isDeleting={deletingFile}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Play, ClipboardList, Activity } from 'lucide-react';
|
||||
import { environments, scenarios, runs } from '../../api';
|
||||
import type {
|
||||
Environment,
|
||||
Scenario,
|
||||
ScenarioRun,
|
||||
ScenarioRunStep,
|
||||
ScenarioRunStatus,
|
||||
} from '../../api';
|
||||
import type { Environment, Scenario, ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
@@ -22,6 +17,7 @@ import {
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
@@ -40,7 +36,7 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
|
||||
type RunRow = ScenarioRun;
|
||||
|
||||
export function RunsPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -50,6 +46,7 @@ export function RunsPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [items, setItems] = useState<RunRow[]>([]);
|
||||
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
@@ -60,29 +57,73 @@ export function RunsPage() {
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const hasDataRef = useRef(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([scenarios.get(id!), runs.list(id!)])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
// Keep refs so the poll interval always reads current values
|
||||
const sortByRef = useRef(sortBy);
|
||||
const sortDirRef = useRef(sortDir);
|
||||
const pageRef = useRef(page);
|
||||
const pageSizeRef = useRef(pageSize);
|
||||
sortByRef.current = sortBy;
|
||||
sortDirRef.current = sortDir;
|
||||
pageRef.current = page;
|
||||
pageSizeRef.current = pageSize;
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.get(id!),
|
||||
runs.list(id!, p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[id],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
load('createdAt', 'desc', 1, 20);
|
||||
pollRef.current = setInterval(
|
||||
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
|
||||
10_000,
|
||||
);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
@@ -117,18 +158,25 @@ export function RunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
key: 'scenarioVersion',
|
||||
header: t('runs.col_version'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
render: (r) =>
|
||||
r.scenarioVersion != null ? (
|
||||
`v${r.scenarioVersion}`
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -151,7 +199,12 @@ export function RunsPage() {
|
||||
]}
|
||||
/>
|
||||
<div className={styles.toolbarActions}>
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
|
||||
<AutoRefreshIndicator
|
||||
active
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={() => load(sortBy, sortDir, page, pageSize)}
|
||||
/>
|
||||
<Button size="sm" onClick={() => setRunModalOpen(true)}>
|
||||
<Play size={14} />
|
||||
{t('runs.action_run')}
|
||||
@@ -165,9 +218,16 @@ export function RunsPage() {
|
||||
rowKey={(r) => r.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
|
||||
@@ -1,20 +1,33 @@
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateScenarioPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('scenarios.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => setEnvs(r?.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
@@ -23,7 +36,11 @@ export function CreateScenarioPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const scenario = await scenarios.create(name.trim());
|
||||
const scenario = await scenarios.create(
|
||||
name.trim(),
|
||||
description.trim() || undefined,
|
||||
environmentId || undefined,
|
||||
);
|
||||
toast.success(t('scenarios.created'));
|
||||
navigate(`/scenarios/${scenario.id}`);
|
||||
} catch (err) {
|
||||
@@ -64,6 +81,24 @@ export function CreateScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
@@ -14,8 +15,10 @@ export function CreateStepPage() {
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
usePageTitle(t('steps.create_title'));
|
||||
const [title, setTitle] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -33,6 +36,7 @@ export function CreateStepPage() {
|
||||
await steps.create(id!, {
|
||||
title: title.trim() || undefined,
|
||||
execCode: execCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
|
||||
});
|
||||
toast.success(t('steps.created'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
@@ -76,6 +80,15 @@ export function CreateStepPage() {
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Scenario, Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditScenarioPage() {
|
||||
@@ -15,6 +16,13 @@ export function EditScenarioPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
scenario ? `${t('scenarios.edit_title')} — ${scenario.name}` : t('scenarios.edit_title'),
|
||||
);
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState<string>('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -26,8 +34,15 @@ export function EditScenarioPage() {
|
||||
.then((data) => {
|
||||
setScenario(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setEnvironmentId(data.environmentId ?? '');
|
||||
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => setEnvs(r?.data ?? []))
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
@@ -38,7 +53,12 @@ export function EditScenarioPage() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await scenarios.update(id!, { name: name.trim() });
|
||||
await scenarios.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
environmentId: environmentId || null,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('scenarios.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
@@ -86,6 +106,33 @@ export function EditScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.form_timeout')}
|
||||
placeholder={t('scenarios.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('scenarios.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, ScenarioStep } from '../../api';
|
||||
@@ -15,8 +16,12 @@ export function EditStepPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [step, setStep] = useState<ScenarioStep | null>(null);
|
||||
usePageTitle(
|
||||
step ? t('steps.edit_title', { order: step.order }) : t('steps.edit_title', { order: '' }),
|
||||
);
|
||||
const [title, setTitle] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -28,6 +33,7 @@ export function EditStepPage() {
|
||||
setStep(st);
|
||||
setTitle(st.title ?? '');
|
||||
setExecCode(st.execCode ?? '');
|
||||
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [id, stepId]);
|
||||
@@ -39,6 +45,7 @@ export function EditStepPage() {
|
||||
await steps.update(id!, stepId!, {
|
||||
title: title.trim() || undefined,
|
||||
execCode: execCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('steps.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
@@ -64,7 +71,7 @@ export function EditStepPage() {
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{ label: t('steps.edit_title', { order: step ? step.order + 1 : stepId }) },
|
||||
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
@@ -85,6 +92,15 @@ export function EditStepPage() {
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useEffect, useRef, useState, useCallback, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import {
|
||||
Play,
|
||||
Pencil,
|
||||
Plus,
|
||||
History,
|
||||
Download,
|
||||
Trash2,
|
||||
Upload,
|
||||
GripVertical,
|
||||
ClipboardList,
|
||||
FileArchive,
|
||||
} from 'lucide-react';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import {
|
||||
environments,
|
||||
scenarios,
|
||||
steps,
|
||||
scenarioCredentials,
|
||||
scenarioFiles,
|
||||
credentials as credentialsApi,
|
||||
} from '../../api';
|
||||
import type {
|
||||
@@ -25,6 +28,10 @@ import type {
|
||||
ScenarioCredential,
|
||||
Credential,
|
||||
Environment,
|
||||
FileMetadata,
|
||||
ScenarioVersion,
|
||||
TraceMode,
|
||||
UsedSnippet,
|
||||
} from '../../api';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
@@ -37,9 +44,12 @@ import {
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import { ExportScenarioModal, RunScenarioModal } from '../../components/modals';
|
||||
import { useRunDefaults } from '../../hooks/useRunDefaults';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function ScenarioDetailPage() {
|
||||
@@ -49,6 +59,7 @@ export function ScenarioDetailPage() {
|
||||
const toast = useToast();
|
||||
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(scenario?.name ?? null);
|
||||
|
||||
// Credentials state
|
||||
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
|
||||
@@ -65,13 +76,50 @@ export function ScenarioDetailPage() {
|
||||
const [runModalOpen, setRunModalOpen] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
// null = use the server's configured default
|
||||
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
|
||||
const runDefaults = useRunDefaults();
|
||||
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
|
||||
// null = latest
|
||||
const [runVersion, setRunVersion] = useState<number | null>(null);
|
||||
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
const envInitRef = useRef(false);
|
||||
const [pendingDelete, setPendingDelete] = useState<
|
||||
{ type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null
|
||||
>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
// Export modal state
|
||||
const [exportModalOpen, setExportModalOpen] = useState(false);
|
||||
const [includeEnvironment, setIncludeEnvironment] = useState(true);
|
||||
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
// Files state
|
||||
const [files, setFiles] = useState<FileMetadata[]>([]);
|
||||
const [filesTotal, setFilesTotal] = useState(0);
|
||||
const [filesLoading, setFilesLoading] = useState(false);
|
||||
const [uploadOpen, setUploadOpen] = useState(false);
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||
const [uploadExpiresAt, setUploadExpiresAt] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]);
|
||||
|
||||
const loadFiles = useCallback(async () => {
|
||||
if (!id) return;
|
||||
setFilesLoading(true);
|
||||
try {
|
||||
const result = await scenarioFiles.list(id);
|
||||
setFiles(result.items);
|
||||
setFilesTotal(result.total);
|
||||
} finally {
|
||||
setFilesLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
void scenarios
|
||||
@@ -81,6 +129,11 @@ export function ScenarioDetailPage() {
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
void loadFiles();
|
||||
scenarios
|
||||
.usedSnippets(id)
|
||||
.then(setUsedSnippets)
|
||||
.catch(() => {});
|
||||
credentialsApi
|
||||
.list(1, 200)
|
||||
.then((r) => setAllCredentials(r.data))
|
||||
@@ -89,16 +142,28 @@ export function ScenarioDetailPage() {
|
||||
.list(1, 200)
|
||||
.then((r) => {
|
||||
setEnvs(r.data);
|
||||
setSelectedEnvId((prev) => prev || r.data[0]?.id || '');
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
}, [id, loadFiles]);
|
||||
|
||||
// Default selected env to scenario's linked environment (or first env) once both are loaded
|
||||
useEffect(() => {
|
||||
if (envInitRef.current || envs.length === 0) return;
|
||||
envInitRef.current = true;
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : envs[0].id);
|
||||
}, [scenario, envs]);
|
||||
|
||||
const reloadScenario = async () => {
|
||||
if (!id) return;
|
||||
const s = await scenarios.get(id);
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
scenarios
|
||||
.usedSnippets(id)
|
||||
.then(setUsedSnippets)
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
@@ -109,7 +174,13 @@ export function ScenarioDetailPage() {
|
||||
}
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(scenario.id, selectedEnvId, saveSessionFlag);
|
||||
const run = await scenarios.run(
|
||||
scenario.id,
|
||||
selectedEnvId,
|
||||
saveSessionFlag,
|
||||
traceModeOverride ?? undefined,
|
||||
runVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
setRunModalOpen(false);
|
||||
@@ -127,19 +198,70 @@ export function ScenarioDetailPage() {
|
||||
navigate('/scenarios');
|
||||
};
|
||||
|
||||
const handleOpenExportModal = () => {
|
||||
if (!scenario) return;
|
||||
// Initialise all credential checkboxes to checked
|
||||
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
|
||||
setIncludeEnvironment(true);
|
||||
setExportModalOpen(true);
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!scenario) return;
|
||||
const data = await scenarios.exportScenario(scenario.id);
|
||||
const yamlContent = typeof data === 'string' ? data : yamlStringify(data);
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const credIds = Array.from(includedCredentialIds);
|
||||
const yamlContent = await scenarios.exportScenario(scenario.id, {
|
||||
includeEnvironment,
|
||||
credentialIds: credIds,
|
||||
});
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportModalOpen(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDownload = (url: string, filename: string) => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
|
||||
const isFileExpired = (file: FileMetadata) =>
|
||||
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
|
||||
|
||||
async function handleUpload(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
if (!id || !uploadFile) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
await scenarioFiles.upload(
|
||||
id,
|
||||
uploadFile,
|
||||
uploadExpiresAt ? new Date(uploadExpiresAt) : undefined,
|
||||
);
|
||||
setUploadOpen(false);
|
||||
setUploadFile(null);
|
||||
setUploadExpiresAt('');
|
||||
await loadFiles();
|
||||
toast.success(t('files.uploadSuccess'));
|
||||
} catch {
|
||||
// error toast already emitted by API client
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteStep = async (stepId: string) => {
|
||||
await steps.remove(id!, stepId);
|
||||
await reloadScenario();
|
||||
@@ -252,7 +374,7 @@ export function ScenarioDetailPage() {
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order + 1, width: 60 },
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
|
||||
{
|
||||
key: 'title',
|
||||
header: t('scenarios.step_title'),
|
||||
@@ -350,7 +472,21 @@ export function ScenarioDetailPage() {
|
||||
/>
|
||||
{scenario && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button size="sm" onClick={() => setRunModalOpen(true)}>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setTraceModeOverride(null);
|
||||
setRunVersion(null);
|
||||
setRunVersions([]);
|
||||
if (id) {
|
||||
scenarios
|
||||
.versions(id)
|
||||
.then(setRunVersions)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
setRunModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Play size={14} />
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
@@ -358,10 +494,20 @@ export function ScenarioDetailPage() {
|
||||
<History size={14} />
|
||||
{t('scenarios.action_runs')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`)
|
||||
}
|
||||
>
|
||||
<FileArchive size={14} />
|
||||
{t('scenarios.action_export_e2e')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/edit`)}>
|
||||
<Pencil size={14} />
|
||||
{t('scenarios.action_edit')}
|
||||
@@ -388,6 +534,25 @@ export function ScenarioDetailPage() {
|
||||
items={[
|
||||
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
|
||||
{ term: t('scenarios.field_name'), detail: scenario.name },
|
||||
{ term: t('scenarios.field_version'), detail: `v${scenario.version}` },
|
||||
...(scenario.environment
|
||||
? [
|
||||
{
|
||||
term: t('scenarios.field_environment'),
|
||||
detail: (
|
||||
<a
|
||||
href={`/environments/${scenario.environment.id}`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
navigate(`/environments/${scenario.environment!.id}`);
|
||||
}}
|
||||
>
|
||||
{scenario.environment.name}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
term: t('scenarios.field_created'),
|
||||
detail: <Timestamp value={scenario.createdAt} />,
|
||||
@@ -400,6 +565,17 @@ export function ScenarioDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{scenario.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={scenario.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenario.steps.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
@@ -527,6 +703,139 @@ export function ScenarioDetailPage() {
|
||||
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Used snippets section ───────────────────────────────────────── */}
|
||||
{usedSnippets.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.used_snippets_heading')}</h2>
|
||||
</div>
|
||||
<Table<UsedSnippet>
|
||||
data={usedSnippets}
|
||||
rowKey={(s) => `${s.id}@${s.pinnedVersion ?? 'latest'}`}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
onRowClick={(s) => navigate(`/snippets/${s.id}`)}
|
||||
columns={
|
||||
[
|
||||
{
|
||||
key: 'alias',
|
||||
header: t('snippets.field_alias'),
|
||||
render: (s) => s.alias,
|
||||
},
|
||||
{
|
||||
key: 'title',
|
||||
header: t('snippets.field_title'),
|
||||
render: (s) => s.title,
|
||||
},
|
||||
{
|
||||
key: 'version',
|
||||
header: t('snippets.field_version'),
|
||||
render: (s) =>
|
||||
s.pinnedVersion != null
|
||||
? t('scenarios.used_snippet_pinned', { version: s.pinnedVersion })
|
||||
: t('scenarios.used_snippet_latest', { version: s.version }),
|
||||
},
|
||||
] satisfies TableColumn<UsedSnippet>[]
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Files section ───────────────────────────────────────────────── */}
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('files.title')}</h2>
|
||||
<Button size="sm" onClick={() => setUploadOpen(true)}>
|
||||
<Upload size={14} /> {t('files.upload')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table<FileMetadata>
|
||||
loading={filesLoading}
|
||||
data={files}
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{
|
||||
key: 'name',
|
||||
header: t('files.name'),
|
||||
render: (f) => f.name,
|
||||
},
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
render: (f) => f.mimeType,
|
||||
},
|
||||
{
|
||||
key: 'size',
|
||||
header: t('files.size'),
|
||||
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
|
||||
},
|
||||
{
|
||||
key: 'expiresAt',
|
||||
header: t('files.expiresAt'),
|
||||
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
header: t('files.createdAt'),
|
||||
render: (f) => <Timestamp value={f.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'download',
|
||||
header: '',
|
||||
render: (f) => {
|
||||
const expired = isFileExpired(f);
|
||||
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
|
||||
|
||||
return (
|
||||
<span title={tooltip}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={tooltip}
|
||||
aria-label={tooltip}
|
||||
disabled={expired}
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarioFiles.contentUrl(id!, f.id), f.name)
|
||||
}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
] satisfies TableColumn<FileMetadata>[]
|
||||
}
|
||||
emptyMessage={t('files.empty')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Upload modal ─────────────────────────────────────────────── */}
|
||||
<Modal
|
||||
open={uploadOpen}
|
||||
title={t('files.uploadTitle')}
|
||||
onClose={() => setUploadOpen(false)}
|
||||
>
|
||||
<form onSubmit={handleUpload}>
|
||||
<input
|
||||
type="file"
|
||||
required
|
||||
onChange={(e) => setUploadFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
<Input
|
||||
label={t('files.expiresAtLabel')}
|
||||
type="datetime-local"
|
||||
value={uploadExpiresAt}
|
||||
onChange={(e) => setUploadExpiresAt(e.target.value)}
|
||||
/>
|
||||
<Button type="submit" loading={uploading} disabled={!uploadFile}>
|
||||
{t('files.upload')}
|
||||
</Button>
|
||||
</form>
|
||||
</Modal>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -556,44 +865,46 @@ export function ScenarioDetailPage() {
|
||||
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
<RunScenarioModal
|
||||
open={runModalOpen}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunModalOpen(false)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
environments={envs}
|
||||
selectedEnvId={selectedEnvId}
|
||||
onEnvSelect={setSelectedEnvId}
|
||||
saveSessionFlag={saveSessionFlag}
|
||||
onSaveSessionChange={setSaveSessionFlag}
|
||||
versions={runVersions}
|
||||
selectedVersion={runVersion}
|
||||
onVersionChange={setRunVersion}
|
||||
traceMode={traceMode}
|
||||
defaultTraceMode={runDefaults?.traceMode ?? null}
|
||||
onTraceModeChange={setTraceModeOverride}
|
||||
onClose={() => setRunModalOpen(false)}
|
||||
onRun={handleRun}
|
||||
isRunning={running}
|
||||
/>
|
||||
|
||||
<ExportScenarioModal
|
||||
open={exportModalOpen}
|
||||
scenario={scenario}
|
||||
scenarioCredentials={scenarioCreds}
|
||||
environment={
|
||||
scenario?.environment ?? envs.find((e) => e.id === scenario?.environmentId) ?? null
|
||||
}
|
||||
>
|
||||
{envs.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => setSelectedEnvId(e.target.value)}
|
||||
options={envs.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
<label
|
||||
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveSessionFlag}
|
||||
onChange={(e) => setSaveSessionFlag(e.target.checked)}
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
includeEnvironment={includeEnvironment}
|
||||
onIncludeEnvironmentChange={setIncludeEnvironment}
|
||||
includedCredentialIds={includedCredentialIds}
|
||||
onCredentialToggle={(credId, checked) => {
|
||||
setIncludedCredentialIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (checked) next.add(credId);
|
||||
else next.delete(credId);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
onClose={() => setExportModalOpen(false)}
|
||||
onExport={handleExport}
|
||||
isExporting={isExporting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,46 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { environments, scenarios } from '../../api';
|
||||
import type { Environment, Scenario } from '../../api';
|
||||
import type { Environment, Scenario, ScenarioVersion, TraceMode } from '../../api';
|
||||
import { RunScenarioModal } from '../../components/modals';
|
||||
import { useRunDefaults } from '../../hooks/useRunDefaults';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import type { ScenarioRunStatus } from '../../api';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const LAST_RUN_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
pending: 'neutral',
|
||||
in_progress: 'info',
|
||||
pass: 'success',
|
||||
fail: 'error',
|
||||
};
|
||||
|
||||
const LAST_RUN_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
pending: 'Pending',
|
||||
in_progress: 'Running',
|
||||
pass: 'Pass',
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
export function ScenariosPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('scenarios.title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const [items, setItems] = useState<Scenario[]>([]);
|
||||
@@ -29,39 +50,92 @@ export function ScenariosPage() {
|
||||
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
// null = use the server's configured default
|
||||
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
|
||||
const runDefaults = useRunDefaults();
|
||||
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
|
||||
// null = latest
|
||||
const [runVersion, setRunVersion] = useState<number | null>(null);
|
||||
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
Promise.all([scenarios.list(), environments.list(1, 200)])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes?.data ?? []);
|
||||
setEnvs(envRes?.data ?? []);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error((err as Error).message);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [toast]);
|
||||
const [sortBy, setSortBy] = useState('updatedAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
environments.list(1, 200),
|
||||
])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes?.data ?? []);
|
||||
setTotal(scenarioRes?.total ?? 0);
|
||||
setEnvs(envRes?.data ?? []);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error((err as Error).message);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
load('updatedAt', 'desc', 1, 10);
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
const openRunModal = (id: string) => {
|
||||
setRunScenarioId(id);
|
||||
if (!selectedEnvId && envs.length > 0) {
|
||||
setSelectedEnvId(envs[0].id);
|
||||
}
|
||||
setTraceModeOverride(null);
|
||||
setRunVersion(null);
|
||||
setRunVersions([]);
|
||||
scenarios
|
||||
.versions(id)
|
||||
.then(setRunVersions)
|
||||
.catch(() => undefined);
|
||||
const scenario = items.find((s) => s.id === id);
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : envs[0]?.id || '');
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
if (!runScenarioId || !selectedEnvId) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(runScenarioId, selectedEnvId, saveSessionFlag);
|
||||
const run = await scenarios.run(
|
||||
runScenarioId,
|
||||
selectedEnvId,
|
||||
saveSessionFlag,
|
||||
traceModeOverride ?? undefined,
|
||||
runVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
|
||||
setRunScenarioId(null);
|
||||
@@ -78,8 +152,7 @@ export function ScenariosPage() {
|
||||
setDeleting(true);
|
||||
try {
|
||||
await scenarios.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
@@ -102,11 +175,36 @@ export function ScenariosPage() {
|
||||
|
||||
const columns: TableColumn<Scenario>[] = [
|
||||
{ key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name, sortable: true },
|
||||
{
|
||||
key: 'updated',
|
||||
key: 'version',
|
||||
header: t('scenarios.col_version'),
|
||||
width: 80,
|
||||
render: (s) => `v${s.version}`,
|
||||
},
|
||||
{
|
||||
key: 'lastRunStatus',
|
||||
header: t('scenarios.col_last_run'),
|
||||
width: 160,
|
||||
render: (s) =>
|
||||
s.lastRunStatus ? (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ display: 'inline-flex', minWidth: 62 }}>
|
||||
<Badge variant={LAST_RUN_VARIANT[s.lastRunStatus]}>
|
||||
{LAST_RUN_LABEL[s.lastRunStatus]}
|
||||
</Badge>
|
||||
</span>
|
||||
{s.lastRunAt && <Timestamp value={s.lastRunAt} />}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ color: 'var(--color-text-muted)', fontSize: '0.8em' }}>—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'updatedAt',
|
||||
header: t('scenarios.col_updated'),
|
||||
width: 140,
|
||||
sortable: true,
|
||||
render: (s) => <Timestamp value={s.updatedAt} />,
|
||||
},
|
||||
{
|
||||
@@ -170,9 +268,16 @@ export function ScenariosPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('scenarios.empty')}
|
||||
pageSize={10}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
@@ -193,44 +298,23 @@ export function ScenariosPage() {
|
||||
{t('common.confirm_delete_scenario')}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
<RunScenarioModal
|
||||
open={runScenarioId != null}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunScenarioId(null)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{envs.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => setSelectedEnvId(e.target.value)}
|
||||
options={envs.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
<label
|
||||
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveSessionFlag}
|
||||
onChange={(e) => setSaveSessionFlag(e.target.checked)}
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
environments={envs}
|
||||
selectedEnvId={selectedEnvId}
|
||||
onEnvSelect={setSelectedEnvId}
|
||||
saveSessionFlag={saveSessionFlag}
|
||||
onSaveSessionChange={setSaveSessionFlag}
|
||||
versions={runVersions}
|
||||
selectedVersion={runVersion}
|
||||
onVersionChange={setRunVersion}
|
||||
traceMode={traceMode}
|
||||
defaultTraceMode={runDefaults?.traceMode ?? null}
|
||||
onTraceModeChange={setTraceModeOverride}
|
||||
onClose={() => setRunScenarioId(null)}
|
||||
onRun={handleRun}
|
||||
isRunning={running}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Trash2, Monitor } from 'lucide-react';
|
||||
import { sessions } from '../../api';
|
||||
import type { Session } from '../../api';
|
||||
@@ -14,6 +15,7 @@ export function SessionDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [session, setSession] = useState<Session | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(session?.sessionName ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Trash2, Monitor } from 'lucide-react';
|
||||
import { sessions } from '../../api';
|
||||
import type { Session } from '../../api';
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
Button,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
@@ -18,30 +20,45 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function SessionsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('sessions.title'));
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Session[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [sortBy, setSortBy] = useState('id');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(() => {
|
||||
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
sessions
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
|
||||
.then((res) => {
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
}, [load, sortBy, sortDir, page, pageSize]);
|
||||
|
||||
const handleSort = (col: string, dir: SortDirection) => {
|
||||
setSortBy(col);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await sessions.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
@@ -50,17 +67,24 @@ export function SessionsPage() {
|
||||
|
||||
const columns: TableColumn<Session>[] = [
|
||||
{ key: 'id', header: t('sessions.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
|
||||
{
|
||||
key: 'sessionName',
|
||||
header: t('sessions.col_name'),
|
||||
sortable: true,
|
||||
render: (s) => s.sessionName,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: t('sessions.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'lastUsed',
|
||||
key: 'lastUsedAt',
|
||||
header: t('sessions.col_lastUsed'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
@@ -95,7 +119,16 @@ export function SessionsPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('sessions.empty')}
|
||||
pageSize={10}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(s) => {
|
||||
setPageSize(s);
|
||||
setPage(1);
|
||||
}}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
@@ -8,6 +9,7 @@ import styles from '../Page.module.css';
|
||||
|
||||
export function CreateSnippetPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('snippets.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
@@ -15,6 +16,9 @@ export function EditSnippetPage() {
|
||||
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [alias, setAlias] = useState('');
|
||||
usePageTitle(
|
||||
snippet ? `${t('snippets.edit_title')} — ${snippet.title}` : t('snippets.edit_title'),
|
||||
);
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Upload, Pencil, Trash2, Braces } from 'lucide-react';
|
||||
import { CodeBlock } from '../../ui';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
@@ -24,6 +25,7 @@ export function SnippetDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(snippet?.title ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
@@ -105,6 +107,7 @@ export function SnippetDetailPage() {
|
||||
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
|
||||
{ term: t('snippets.field_alias'), detail: snippet.alias },
|
||||
{ term: t('snippets.field_title'), detail: snippet.title },
|
||||
{ term: t('snippets.field_version'), detail: `v${snippet.version}` },
|
||||
{
|
||||
term: t('snippets.field_created'),
|
||||
detail: <Timestamp value={snippet.createdAt} />,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { snippets } from '../../api';
|
||||
@@ -83,6 +84,7 @@ function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: s
|
||||
>
|
||||
<p className={styles.muted}>
|
||||
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
|
||||
{' · '}v{snippet.version}
|
||||
</p>
|
||||
{snippet.description &&
|
||||
(() => {
|
||||
@@ -114,6 +116,7 @@ function AddSnippetCard() {
|
||||
|
||||
export function SnippetsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('snippets.title'));
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Snippet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -27,11 +27,40 @@
|
||||
background: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
.thContent {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.thSortable {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary-fg) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
.sortIcon {
|
||||
opacity: 0.4;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sortIconActive {
|
||||
opacity: 1;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .th {
|
||||
background: var(--color-secondary);
|
||||
color: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
/* Rounded top corners on first/last header cells */
|
||||
.th:first-child { border-radius: var(--radius-lg) 0 0 0; }
|
||||
.th:last-child { border-radius: 0 var(--radius-lg) 0 0; }
|
||||
|
||||
+109
-24
@@ -1,13 +1,18 @@
|
||||
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
|
||||
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
|
||||
import { Pagination } from '../Pagination/Pagination';
|
||||
import styles from './Table.module.css';
|
||||
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
export interface TableColumn<T> {
|
||||
key: string;
|
||||
header: ReactNode;
|
||||
render: (row: T) => ReactNode;
|
||||
width?: string | number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
/** If true, a sort icon is shown and clicking the header triggers onSort */
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface TableProps<T> {
|
||||
@@ -17,7 +22,10 @@ export interface TableProps<T> {
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
/** Enable built-in client-side pagination with this default page size */
|
||||
/**
|
||||
* Client-side pagination: pass a default page size to enable.
|
||||
* For server-side pagination use `total` + `page` + `onPageChange` instead.
|
||||
*/
|
||||
pageSize?: number;
|
||||
/** Offer a page-size selector when pagination is enabled */
|
||||
pageSizeOptions?: number[];
|
||||
@@ -25,6 +33,21 @@ export interface TableProps<T> {
|
||||
onRowClick?: (row: T) => void;
|
||||
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
|
||||
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
|
||||
/** Currently sorted column key (controlled) */
|
||||
sortBy?: string;
|
||||
/** Current sort direction (controlled) */
|
||||
sortDir?: SortDirection;
|
||||
/** Called when the user clicks a sortable column header */
|
||||
onSort?: (key: string, dir: SortDirection) => void;
|
||||
// ── Server-side pagination (controlled) ──────────────────────────────────
|
||||
/** Total record count from server. Presence switches to server-side pagination mode. */
|
||||
total?: number;
|
||||
/** Controlled current page (1-based). Required when `total` is set. */
|
||||
page?: number;
|
||||
/** Called when the user navigates to a new page. Required when `total` is set. */
|
||||
onPageChange?: (page: number) => void;
|
||||
/** Called when the user changes page size. Optional for server-side pagination. */
|
||||
onPageSizeChange?: (size: number) => void;
|
||||
}
|
||||
|
||||
export function Table<T>({
|
||||
@@ -38,34 +61,74 @@ export function Table<T>({
|
||||
pageSizeOptions,
|
||||
onRowClick,
|
||||
getRowProps,
|
||||
sortBy,
|
||||
sortDir,
|
||||
onSort,
|
||||
total,
|
||||
page: controlledPage,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
}: TableProps<T>) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
|
||||
const [internalPage, setInternalPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 10);
|
||||
|
||||
const paginated = defaultPageSize !== undefined && !loading;
|
||||
const visibleData = paginated ? data.slice((page - 1) * pageSize, page * pageSize) : data;
|
||||
const serverMode = total !== undefined;
|
||||
|
||||
// Reset to page 1 when data changes and current page would be empty
|
||||
const lastPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safePage = Math.min(page, Math.max(1, lastPage));
|
||||
const handleSortClick = (key: string) => {
|
||||
if (!onSort) return;
|
||||
const nextDir: SortDirection = sortBy === key && sortDir === 'asc' ? 'desc' : 'asc';
|
||||
onSort(key, nextDir);
|
||||
};
|
||||
|
||||
// Client-side pagination
|
||||
const clientPaginated = !serverMode && defaultPageSize !== undefined && !loading;
|
||||
const visibleData = clientPaginated
|
||||
? data.slice((internalPage - 1) * pageSize, internalPage * pageSize)
|
||||
: data;
|
||||
|
||||
const lastClientPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safeInternalPage = Math.min(internalPage, Math.max(1, lastClientPage));
|
||||
|
||||
// Server-side pagination display values
|
||||
const serverPage = controlledPage ?? 1;
|
||||
const serverTotal = total ?? 0;
|
||||
|
||||
return (
|
||||
<div className={`${styles.wrapper} ${className ?? ''}`}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={styles.th}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
>
|
||||
{col.header}
|
||||
</th>
|
||||
))}
|
||||
{columns.map((col) => {
|
||||
const isSorted = col.sortable && sortBy === col.key;
|
||||
const SortIcon = isSorted ? (sortDir === 'asc' ? ArrowUp : ArrowDown) : ArrowUpDown;
|
||||
|
||||
return (
|
||||
<th
|
||||
key={col.key}
|
||||
className={[styles.th, col.sortable ? styles.thSortable : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
onClick={col.sortable ? () => handleSortClick(col.key) : undefined}
|
||||
>
|
||||
<span className={styles.thContent}>
|
||||
{col.header}
|
||||
{col.sortable && (
|
||||
<SortIcon
|
||||
size={12}
|
||||
className={[styles.sortIcon, isSorted ? styles.sortIconActive : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -122,17 +185,39 @@ export function Table<T>({
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{paginated && data.length > 0 && (
|
||||
{serverMode && serverTotal > 0 && onPageChange && (
|
||||
<Pagination
|
||||
page={safePage}
|
||||
page={serverPage}
|
||||
pageSize={pageSize}
|
||||
total={serverTotal}
|
||||
onPageChange={onPageChange}
|
||||
onPageSizeChange={
|
||||
onPageSizeChange
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageSizeChange(size);
|
||||
}
|
||||
: pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageChange(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
/>
|
||||
)}
|
||||
{clientPaginated && data.length > 0 && (
|
||||
<Pagination
|
||||
page={safeInternalPage}
|
||||
pageSize={pageSize}
|
||||
total={data.length}
|
||||
onPageChange={setPage}
|
||||
onPageChange={setInternalPage}
|
||||
onPageSizeChange={
|
||||
pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
setInternalPage(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ export { Modal } from './Modal/Modal';
|
||||
export type { ModalProps } from './Modal/Modal';
|
||||
|
||||
export { Table } from './Table/Table';
|
||||
export type { TableProps, TableColumn } from './Table/Table';
|
||||
export type { TableProps, TableColumn, SortDirection } from './Table/Table';
|
||||
|
||||
export { UuidBadge } from './UuidBadge/UuidBadge';
|
||||
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
|
||||
File renamed without changes.
+40
-3
@@ -44,13 +44,50 @@ The server currently registers the following tools.
|
||||
| `update_scenario_step` | Update step fields |
|
||||
| `delete_scenario_step` | Delete step |
|
||||
| `list_scenario_runs` | List runs for a scenario |
|
||||
| `run_scenario` | Trigger run for scenario |
|
||||
| `list_scenario_versions` | List a scenario's versions, newest first |
|
||||
| `get_scenario_version` | Get one scenario version with its steps |
|
||||
| `run_scenario` | Trigger run for scenario; optional `version` (defaults to latest) and `traceMode` |
|
||||
| `get_scenario_run` | Get run with step runs and logs |
|
||||
| `wait_for_scenario_run` | Wait until run is `pass` or `fail` |
|
||||
| `export_scenario` | Export scenario payload |
|
||||
| `import_scenario` | Import scenario payload |
|
||||
| `export_scenario` | Export one scenario version (optional `version`, defaults to latest) |
|
||||
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in `scenario.md`) |
|
||||
|
||||
## Snippets
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_snippets` | List snippets (paginated) |
|
||||
| `get_snippet` | Get one snippet (latest version) |
|
||||
| `create_snippet` | Create snippet (`alias`, `title`, `code`) |
|
||||
| `update_snippet` | Update snippet fields; bumps its version when content changes |
|
||||
| `delete_snippet` | Delete snippet and all its versions |
|
||||
| `list_snippet_versions` | List a snippet's versions, newest first |
|
||||
| `get_snippet_version` | Get one snippet version |
|
||||
|
||||
## Scenario Files
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `upload_scenario_file` | Upload a file to a scenario; accepts optional `expiresAt` (ISO 8601 date string) |
|
||||
| `list_scenario_files` | List scenario files (paginated) |
|
||||
| `get_scenario_file_content` | Retrieve file content as base64 with metadata |
|
||||
|
||||
## Run Artifact Files
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_run_files` | List files (artifacts) created during a scenario run (paginated) |
|
||||
| `get_run_file_content` | Retrieve run artifact content as base64 with metadata; run artifact content can't be modified and inherits expiry from the run artifact subsystem |
|
||||
| `delete_run_file` | Delete a file from a run; the stored file is removed once no scenario or run references it (also `DELETE /scenarios/:id/runs/:runId/files/:fileId` and the delete button on the run detail page) |
|
||||
|
||||
## Binary Content Handling
|
||||
|
||||
File tools transport binary payloads as base64-encoded strings in a `contentBase64` field with an accompanying `encoding: "base64"` marker in the response. When retrieving file content via `get_scenario_file_content` or `get_run_file_content`, decode the base64 to recover the original bytes.
|
||||
|
||||
Scenario files uploaded via `upload_scenario_file` must have their content pre-encoded as base64. Run artifacts are created implicitly through scenario execution (via `context.downloadFile()` during step execution) and cannot be uploaded via MCP.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tool IDs and entity IDs are UUIDs.
|
||||
- `create_scenario_step` schema still accepts legacy `type`/`sessionName` fields for compatibility. Current scheduler executes `execCode` plus optional `validateCode` and does not branch by step type.
|
||||
|
||||
+36
-1
@@ -35,11 +35,46 @@ Available in scope:
|
||||
- `context.getStepOutput(order)`: prior step output by absolute order (`1`, `2`, ...) or relative (`-1` = previous step)
|
||||
- `context.dumpDom(selector?)`: simplified DOM snapshot
|
||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: structured step logs
|
||||
- `context.runSnippet(name, ...args)`: execute stored snippet code with the same context
|
||||
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
|
||||
- `context.runSnippet(name, ...args)`: execute stored snippet code with the same context. `name` is the snippet alias for its latest version, or `alias@<version>` (e.g. `login@3`) to pin a specific version
|
||||
- `context.getScenarioFiles(opts?)`: list files uploaded to the scenario (`limit`, `offset`)
|
||||
- `context.downloadFile(url, opts?)`: fetch `url` and save the result as a run artifact (requires a real scenario run — throws when invoked ad hoc, e.g. via the `exec_code` MCP tool). `opts` may include `method`, `headers`, `body`, `filename`. `url` also accepts a `data:` URI (`data:<mediaType>;base64,<data>` or `data:<mediaType>,<percent-encoded data>`) to save content generated in-script (e.g. a credential JWT) directly, without an actual network fetch.
|
||||
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
||||
|
||||
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
|
||||
|
||||
## Versioning
|
||||
|
||||
Scenarios and snippets are versioned, starting at version 1.
|
||||
|
||||
- A scenario's version goes up when its content changes: name, description, default environment, timeout, or any step change (add, edit, delete, reorder). Credential assignments and uploaded files are not versioned. Saving without changes does not create a new version.
|
||||
- A snippet's version goes up when its alias, title, description or code changes.
|
||||
- The scenario and snippet pages always show the latest version. Older versions are available via `GET /scenarios/:id/versions[/:version]` and `GET /snippets/:id/versions[/:version]`.
|
||||
- A run executes one scenario version, chosen in the run modal (latest by default) or via `version` in `POST /scenarios/:id/run`. The run keeps its own copy of that version's steps, so deleting or editing steps later doesn't change what the run shows. "Repeat run" reuses the run's version.
|
||||
- Step code uses the latest version of a snippet by default. `context.runSnippet("alias@3")` pins version 3 instead. The version is looked up through the snippet's current alias. Pinned versions are listed under "Used Snippets" on the scenario page.
|
||||
|
||||
### Export / import
|
||||
|
||||
Exports hold exactly one version and always include its `version` number (the latest by default, or `?version=N`). Imports require `version`, and restore that exact version by id + version:
|
||||
|
||||
- If that version already exists, it is left untouched.
|
||||
- Otherwise it is stored under that number, and becomes the latest if it is higher than the current latest version.
|
||||
- Without an `id`, a new scenario or snippet is created at the given version.
|
||||
|
||||
## Playwright traces
|
||||
|
||||
A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||
|
||||
The trace mode is chosen per run: the run modal in the UI, the `traceMode` field of `POST /scenarios/:id/run`, and the `traceMode` argument of the `run_scenario` MCP tool all accept one of the values below. When it is omitted, the server's `PLAYWRIGHT_TRACE_MODE` setting is used (exposed via `GET /scenarios/run-defaults`). "Repeat run" reuses the original run's mode.
|
||||
|
||||
- `on`: keep the trace of every run
|
||||
- `retain-on-failure`: keep traces only for runs that failed
|
||||
- `off` (default): do not record traces
|
||||
|
||||
Traces are off by default because they often reach ~10 MB per run.
|
||||
|
||||
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
|
||||
|
||||
## Validation contract
|
||||
|
||||
`validateCode` may return:
|
||||
|
||||
Generated
+716
-7
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.6.0",
|
||||
"version": "1.17.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "liqa",
|
||||
"version": "1.6.0",
|
||||
"version": "1.17.0",
|
||||
"workspaces": [
|
||||
"server",
|
||||
"client"
|
||||
@@ -3979,7 +3979,6 @@
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@storybook/addon-a11y": {
|
||||
@@ -4666,6 +4665,16 @@
|
||||
"@types/react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/readdir-glob": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/readdir-glob/-/readdir-glob-1.1.5.tgz",
|
||||
"integrity": "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/resolve": {
|
||||
"version": "1.20.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.6.tgz",
|
||||
@@ -5566,6 +5575,18 @@
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/abort-controller": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
|
||||
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"event-target-shim": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.5"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
|
||||
@@ -5761,6 +5782,201 @@
|
||||
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/archiver": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/archiver/-/archiver-7.0.1.tgz",
|
||||
"integrity": "sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"archiver-utils": "^5.0.2",
|
||||
"async": "^3.2.4",
|
||||
"buffer-crc32": "^1.0.0",
|
||||
"readable-stream": "^4.0.0",
|
||||
"readdir-glob": "^1.1.2",
|
||||
"tar-stream": "^3.0.0",
|
||||
"zip-stream": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-5.0.2.tgz",
|
||||
"integrity": "sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"glob": "^10.0.0",
|
||||
"graceful-fs": "^4.2.0",
|
||||
"is-stream": "^2.0.1",
|
||||
"lazystream": "^1.0.0",
|
||||
"lodash": "^4.17.15",
|
||||
"normalize-path": "^3.0.0",
|
||||
"readable-stream": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/brace-expansion": {
|
||||
"version": "2.1.7",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
|
||||
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/glob": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
|
||||
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"foreground-child": "^3.1.0",
|
||||
"jackspeak": "^3.1.2",
|
||||
"minimatch": "^9.0.4",
|
||||
"minipass": "^7.1.2",
|
||||
"package-json-from-dist": "^1.0.0",
|
||||
"path-scurry": "^1.11.1"
|
||||
},
|
||||
"bin": {
|
||||
"glob": "dist/esm/bin.mjs"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/lru-cache": {
|
||||
"version": "10.4.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/minimatch": {
|
||||
"version": "9.0.9",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
|
||||
"integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/path-scurry": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
|
||||
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"lru-cache": "^10.2.0",
|
||||
"minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver-utils/node_modules/readable-stream": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
|
||||
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"events": "^3.3.0",
|
||||
"process": "^0.11.10",
|
||||
"string_decoder": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver/node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver/node_modules/readable-stream": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
|
||||
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"events": "^3.3.0",
|
||||
"process": "^0.11.10",
|
||||
"string_decoder": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/archiver/node_modules/tar-stream": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.1.tgz",
|
||||
"integrity": "sha512-nqsEO8zLZJvrOMdEwkA0QdCLFbetHMn95Zqu4fKwX+hkaTWJPZZOrxx/PwtxoK0MMGQmBQNRW3CPs8IFYQz4cQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"b4a": "^1.6.4",
|
||||
"bare-fs": "^4.5.5",
|
||||
"fast-fifo": "^1.2.0",
|
||||
"streamx": "^2.15.0"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
@@ -5843,6 +6059,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/async": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
|
||||
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
@@ -5875,6 +6097,20 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/b4a": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",
|
||||
"integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",
|
||||
"license": "Apache-2.0",
|
||||
"peerDependencies": {
|
||||
"react-native-b4a": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-native-b4a": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/babel-jest": {
|
||||
"version": "30.3.0",
|
||||
"resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-30.3.0.tgz",
|
||||
@@ -5990,6 +6226,86 @@
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bare-events": {
|
||||
"version": "2.9.2",
|
||||
"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
|
||||
"integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
|
||||
"license": "Apache-2.0",
|
||||
"peerDependencies": {
|
||||
"bare-abort-controller": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bare-abort-controller": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/bare-fs": {
|
||||
"version": "4.8.1",
|
||||
"resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.1.tgz",
|
||||
"integrity": "sha512-N1nnXdHZAOSstz0XiHikGS4HGMH4CnSwhqWdGQQMqqdvp4Jybm9sE3R1WVnpWVd4SFkc8ryPDBLViNLwiEqECg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"bare-events": "^2.5.4",
|
||||
"bare-path": "^3.0.0",
|
||||
"bare-stream": "^2.6.4",
|
||||
"bare-url": "^2.2.2",
|
||||
"fast-fifo": "^1.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"bare": ">=1.28.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bare-buffer": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bare-buffer": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/bare-path": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz",
|
||||
"integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/bare-stream": {
|
||||
"version": "2.13.4",
|
||||
"resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",
|
||||
"integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"b4a": "^1.8.1",
|
||||
"streamx": "^2.25.0",
|
||||
"teex": "^1.0.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bare-abort-controller": "*",
|
||||
"bare-buffer": "*",
|
||||
"bare-events": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bare-abort-controller": {
|
||||
"optional": true
|
||||
},
|
||||
"bare-buffer": {
|
||||
"optional": true
|
||||
},
|
||||
"bare-events": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/bare-url": {
|
||||
"version": "2.5.4",
|
||||
"resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.4.tgz",
|
||||
"integrity": "sha512-Gxa7UVWBr0/edU1b+TJhn/AZvMQUj9OGspvYsaTYQrAbZA4BOTZGL3LiZxvD+CeMlDH4juwD84+eTAp/bLYW5g==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"bare-path": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
@@ -6182,6 +6498,15 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-crc32": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-1.0.0.tgz",
|
||||
"integrity": "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
@@ -6681,6 +7006,62 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/compress-commons": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-6.0.2.tgz",
|
||||
"integrity": "sha512-6FqVXeETqWPoGcfzrXb37E50NP0LXT8kAMu5ooZayhWWdgEY4lBEEcbQNXtkuKQsGduxiIcI4gOTsxTmuq/bSg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"crc-32": "^1.2.0",
|
||||
"crc32-stream": "^6.0.0",
|
||||
"is-stream": "^2.0.1",
|
||||
"normalize-path": "^3.0.0",
|
||||
"readable-stream": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/compress-commons/node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/compress-commons/node_modules/readable-stream": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
|
||||
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"events": "^3.3.0",
|
||||
"process": "^0.11.10",
|
||||
"string_decoder": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
@@ -6766,6 +7147,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/core-util-is": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
|
||||
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cors": {
|
||||
"version": "2.8.6",
|
||||
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
|
||||
@@ -6810,6 +7197,71 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/crc-32": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
|
||||
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"crc32": "bin/crc32.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/crc32-stream": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-6.0.0.tgz",
|
||||
"integrity": "sha512-piICUB6ei4IlTv1+653yq5+KoqfBYmj9bw6LqXoOneTMDXk5nM1qt12mFW1caG3LlJXEKW1Bp0WggEmIfQB34g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"crc-32": "^1.2.0",
|
||||
"readable-stream": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/crc32-stream/node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/crc32-stream/node_modules/readable-stream": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
|
||||
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"events": "^3.3.0",
|
||||
"process": "^0.11.10",
|
||||
"string_decoder": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cron": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/cron/-/cron-4.4.0.tgz",
|
||||
@@ -7219,6 +7671,16 @@
|
||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/effect": {
|
||||
"version": "3.21.0",
|
||||
"resolved": "https://registry.npmjs.org/effect/-/effect-3.21.0.tgz",
|
||||
"integrity": "sha512-PPN80qRokCd1f015IANNhrwOnLO7GrrMQfk4/lnZRE/8j7UPWrNNjPV0uBrZutI/nHzernbW+J0hdqQysHiSnQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"fast-check": "^3.23.1"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.332",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.332.tgz",
|
||||
@@ -7942,16 +8404,33 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/event-target-shim": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
|
||||
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/events": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
|
||||
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.8.x"
|
||||
}
|
||||
},
|
||||
"node_modules/events-universal": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
|
||||
"integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"bare-events": "^2.7.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
|
||||
@@ -8118,6 +8597,44 @@
|
||||
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-check": {
|
||||
"version": "3.23.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz",
|
||||
"integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/dubzzz"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fast-check"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pure-rand": "^6.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-check/node_modules/pure-rand": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",
|
||||
"integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/dubzzz"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fast-check"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
@@ -8131,6 +8648,12 @@
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/fast-fifo": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
|
||||
"integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-json-stable-stringify": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
@@ -8674,7 +9197,6 @@
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/handlebars": {
|
||||
@@ -9289,7 +9811,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
|
||||
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -10476,6 +10997,54 @@
|
||||
"json-buffer": "3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/lazystream": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",
|
||||
"integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"readable-stream": "^2.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6.3"
|
||||
}
|
||||
},
|
||||
"node_modules/lazystream/node_modules/isarray": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lazystream/node_modules/readable-stream": {
|
||||
"version": "2.3.8",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
|
||||
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"core-util-is": "~1.0.0",
|
||||
"inherits": "~2.0.3",
|
||||
"isarray": "~1.0.0",
|
||||
"process-nextick-args": "~2.0.0",
|
||||
"safe-buffer": "~5.1.1",
|
||||
"string_decoder": "~1.1.1",
|
||||
"util-deprecate": "~1.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/lazystream/node_modules/safe-buffer": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lazystream/node_modules/string_decoder": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
|
||||
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "~5.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/leven": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
|
||||
@@ -11964,7 +12533,6 @@
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
||||
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -12590,6 +13158,21 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/process": {
|
||||
"version": "0.11.10",
|
||||
"resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
|
||||
"integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/process-nextick-args": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
|
||||
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/property-information": {
|
||||
"version": "7.1.0",
|
||||
"resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
|
||||
@@ -12892,6 +13475,36 @@
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/readdir-glob": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz",
|
||||
"integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"minimatch": "^5.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/readdir-glob/node_modules/brace-expansion": {
|
||||
"version": "2.1.7",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
|
||||
"integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/readdir-glob/node_modules/minimatch": {
|
||||
"version": "5.1.9",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
|
||||
"integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/readdirp": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
|
||||
@@ -13766,6 +14379,17 @@
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/streamx": {
|
||||
"version": "2.28.1",
|
||||
"resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",
|
||||
"integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"events-universal": "^1.0.0",
|
||||
"fast-fifo": "^1.3.2",
|
||||
"text-decoder": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||
@@ -14093,6 +14717,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/teex": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
|
||||
"integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"streamx": "^2.12.5"
|
||||
}
|
||||
},
|
||||
"node_modules/terser": {
|
||||
"version": "5.46.1",
|
||||
"resolved": "https://registry.npmjs.org/terser/-/terser-5.46.1.tgz",
|
||||
@@ -14228,6 +14861,15 @@
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/text-decoder": {
|
||||
"version": "1.2.7",
|
||||
"resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
|
||||
"integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"b4a": "^1.6.4"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-invariant": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
||||
@@ -15927,6 +16569,60 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/zip-stream": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-6.0.1.tgz",
|
||||
"integrity": "sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"archiver-utils": "^5.0.0",
|
||||
"compress-commons": "^6.0.2",
|
||||
"readable-stream": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/zip-stream/node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/zip-stream/node_modules/readable-stream": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
|
||||
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"events": "^3.3.0",
|
||||
"process": "^0.11.10",
|
||||
"string_decoder": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
@@ -15984,9 +16680,11 @@
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"acorn": "^8.16.0",
|
||||
"archiver": "^7.0.1",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
@@ -16000,6 +16698,7 @@
|
||||
"@nestjs/cli": "^11.0.17",
|
||||
"@nestjs/testing": "^11.1.18",
|
||||
"@types/acorn": "^4.0.6",
|
||||
"@types/archiver": "^6.0.4",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/debug": "^4.1.13",
|
||||
"@types/express": "^5.0.6",
|
||||
@@ -16019,6 +16718,16 @@
|
||||
"typescript-eslint": "^8.58.1"
|
||||
}
|
||||
},
|
||||
"server/node_modules/@types/archiver": {
|
||||
"version": "6.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/archiver/-/archiver-6.0.4.tgz",
|
||||
"integrity": "sha512-ULdQpARQ3sz9WH4nb98mJDYA0ft2A8C4f4fovvUcFwINa1cgGjY36JCAYuP5YypRq4mco1lJp1/7jEMS2oR0Hg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/readdir-glob": "*"
|
||||
}
|
||||
},
|
||||
"server/node_modules/ajv": {
|
||||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.6.0",
|
||||
"version": "1.17.0",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"server",
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ RUN npm ci --omit=dev -w server
|
||||
COPY --from=builder /app/server/dist ./dist
|
||||
|
||||
# Runtime directories (keys and SQLite DB mounted via volumes)
|
||||
RUN mkdir -p data keys
|
||||
RUN mkdir -p data
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
|
||||
@@ -29,9 +29,11 @@
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"acorn": "^8.16.0",
|
||||
"archiver": "^7.0.1",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
@@ -45,6 +47,7 @@
|
||||
"@nestjs/cli": "^11.0.17",
|
||||
"@nestjs/testing": "^11.1.18",
|
||||
"@types/acorn": "^4.0.6",
|
||||
"@types/archiver": "^6.0.4",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/debug": "^4.1.13",
|
||||
"@types/express": "^5.0.6",
|
||||
|
||||
@@ -8,6 +8,10 @@ import { CredentialEntity } from "./credential/credential.entity";
|
||||
import { CredentialModule } from "./credential/credential.module";
|
||||
import { EnvironmentEntity } from "./environment/environment.entity";
|
||||
import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { FileEntity } from "./file/file.entity";
|
||||
import { FileModule } from "./file/file.module";
|
||||
import { ScenarioFileEntity } from "./file/scenario-file.entity";
|
||||
import { ScenarioRunFileEntity } from "./file/scenario-run-file.entity";
|
||||
import { HealthModule } from "./health/health.module";
|
||||
import { McpModule } from "./mcp/mcp.module";
|
||||
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
|
||||
@@ -15,6 +19,8 @@ import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
|
||||
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
|
||||
import { ScenarioVersionEntity } from "./scenario/scenario-version.entity";
|
||||
import { SnippetVersionEntity } from "./snippet/snippet-version.entity";
|
||||
import { ScenarioEntity } from "./scenario/scenario.entity";
|
||||
import { ScenarioModule } from "./scenario/scenario.module";
|
||||
import { SessionEntity } from "./session/session.entity";
|
||||
@@ -40,11 +46,16 @@ import { SnippetModule } from "./snippet/snippet.module";
|
||||
CredentialEntity,
|
||||
ScenarioEntity,
|
||||
ScenarioStepEntity,
|
||||
ScenarioVersionEntity,
|
||||
ScenarioRunEntity,
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
SnippetEntity,
|
||||
SnippetVersionEntity,
|
||||
FileEntity,
|
||||
ScenarioFileEntity,
|
||||
ScenarioRunFileEntity,
|
||||
],
|
||||
synchronize: true,
|
||||
}),
|
||||
@@ -54,6 +65,7 @@ import { SnippetModule } from "./snippet/snippet.module";
|
||||
CredentialModule,
|
||||
ScenarioModule,
|
||||
SnippetModule,
|
||||
FileModule,
|
||||
McpModule,
|
||||
HealthModule,
|
||||
],
|
||||
|
||||
@@ -6,8 +6,11 @@ import {
|
||||
import { expect as playwrightExpect } from "@playwright/test";
|
||||
import { parse } from "acorn";
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import { URL } from "url";
|
||||
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { FileStorageService } from "../file/file-storage.service";
|
||||
import type { DomNode } from "./dom-helpers";
|
||||
import { dumpDom } from "./dom-helpers";
|
||||
|
||||
@@ -39,8 +42,27 @@ export interface ScriptContext {
|
||||
log: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Runs `fn` and requires it to return `true`. Logs the outcome under
|
||||
* `description`, then throws if `fn` returned anything other than `true`
|
||||
* or threw an exception.
|
||||
*/
|
||||
assert: (
|
||||
fn: () => boolean | Promise<boolean>,
|
||||
description: string,
|
||||
) => Promise<void>;
|
||||
/** Runs a named snippet with the same context, plus any extra positional args. */
|
||||
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
|
||||
/** Returns metadata + absolute disk path for files attached to the current scenario. */
|
||||
getScenarioFiles: (opts?: { limit?: number; offset?: number }) => Promise<{
|
||||
items: Array<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
|
||||
total: number;
|
||||
}>;
|
||||
/** Downloads a file and creates a run artifact. */
|
||||
downloadFile: (
|
||||
url: string,
|
||||
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
|
||||
) => Promise<{ id: string; name: string; mimeType: string; size: number; sha256: string; path: string }>;
|
||||
}
|
||||
|
||||
export interface ExecContext {
|
||||
@@ -53,6 +75,9 @@ export interface ExecContext {
|
||||
environment?: EnvironmentData | null;
|
||||
snippets?: Record<string, string> | null;
|
||||
result?: unknown;
|
||||
scenarioId?: string;
|
||||
runId?: string;
|
||||
fileService?: FileStorageService;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -91,6 +116,9 @@ export class CodeExecutorService {
|
||||
environment,
|
||||
snippets,
|
||||
result,
|
||||
scenarioId,
|
||||
runId,
|
||||
fileService,
|
||||
} = ctx;
|
||||
const scriptLog: ScriptLogger =
|
||||
log ?? ((level, msg) => this.logger[level](msg));
|
||||
@@ -122,6 +150,28 @@ export class CodeExecutorService {
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
assert: async (
|
||||
fn: () => boolean | Promise<boolean>,
|
||||
description: string,
|
||||
): Promise<void> => {
|
||||
let passed: boolean;
|
||||
let failureReason: string | undefined;
|
||||
try {
|
||||
passed = (await fn()) === true;
|
||||
} catch (err) {
|
||||
passed = false;
|
||||
failureReason = (err as Error).message;
|
||||
}
|
||||
if (passed) {
|
||||
scriptLog("log", `Assertion passed: ${description}`);
|
||||
return;
|
||||
}
|
||||
const message = failureReason
|
||||
? `Assertion failed: ${description} (${failureReason})`
|
||||
: `Assertion failed: ${description}`;
|
||||
scriptLog("error", message);
|
||||
throw new Error(message);
|
||||
},
|
||||
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
|
||||
getCredential: (alias: string): unknown => {
|
||||
if (!(alias in credMap)) {
|
||||
@@ -149,6 +199,7 @@ export class CodeExecutorService {
|
||||
if (snippetCode == null) {
|
||||
throw new Error(`Snippet alias "${alias}" not found`);
|
||||
}
|
||||
scriptLog("log", `Snippet "${alias}" started`);
|
||||
const snippetFn = new Function(
|
||||
"context",
|
||||
"console",
|
||||
@@ -156,7 +207,74 @@ export class CodeExecutorService {
|
||||
"expect",
|
||||
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
|
||||
);
|
||||
return snippetFn(scriptContext, fakeConsole, args, playwrightExpect);
|
||||
try {
|
||||
const snippetResult = await snippetFn(
|
||||
scriptContext,
|
||||
fakeConsole,
|
||||
args,
|
||||
playwrightExpect,
|
||||
);
|
||||
scriptLog("log", `Snippet "${alias}" finished`);
|
||||
return snippetResult;
|
||||
} catch (err) {
|
||||
scriptLog(
|
||||
"error",
|
||||
`Snippet "${alias}" failed: ${(err as Error).message}`,
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
getScenarioFiles: async (opts?: { limit?: number; offset?: number }) => {
|
||||
if (!fileService || !scenarioId) {
|
||||
throw new Error("File service not available in this context");
|
||||
}
|
||||
const result = await fileService.listScenarioFiles(
|
||||
scenarioId,
|
||||
opts?.limit,
|
||||
opts?.offset,
|
||||
);
|
||||
return {
|
||||
items: result.items.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
mimeType: item.mimeType,
|
||||
size: item.size,
|
||||
sha256: item.sha256,
|
||||
path: item.path,
|
||||
})),
|
||||
total: result.total,
|
||||
};
|
||||
},
|
||||
downloadFile: async (
|
||||
url: string,
|
||||
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
|
||||
) => {
|
||||
if (!fileService || !scenarioId || !runId) {
|
||||
throw new Error("File service or run context not available");
|
||||
}
|
||||
// Download file
|
||||
const buffer = await downloadFileImpl(url, opts);
|
||||
|
||||
// Determine filename and mime type
|
||||
const filename = opts?.filename ?? new URL(url).pathname.split("/").pop() ?? "download";
|
||||
const mimeType = this.getMimeType(filename);
|
||||
|
||||
// Create run artifact with mapping
|
||||
const savedFile = await fileService.createAndSaveRunArtifact(
|
||||
runId,
|
||||
buffer,
|
||||
filename,
|
||||
mimeType,
|
||||
);
|
||||
|
||||
return {
|
||||
id: savedFile.id,
|
||||
name: savedFile.originalName,
|
||||
mimeType: savedFile.mimeType,
|
||||
size: savedFile.size,
|
||||
sha256: savedFile.sha256,
|
||||
path: fileService.getAbsolutePath(savedFile.filePath),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -184,4 +302,26 @@ export class CodeExecutorService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infers MIME type from filename.
|
||||
*/
|
||||
private getMimeType(filename: string): string {
|
||||
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
|
||||
const mimeTypes: Record<string, string> = {
|
||||
pdf: "application/pdf",
|
||||
doc: "application/msword",
|
||||
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
xls: "application/vnd.ms-excel",
|
||||
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
jpg: "image/jpeg",
|
||||
jpeg: "image/jpeg",
|
||||
png: "image/png",
|
||||
gif: "image/gif",
|
||||
csv: "text/csv",
|
||||
txt: "text/plain",
|
||||
zip: "application/zip",
|
||||
};
|
||||
return mimeTypes[ext] ?? "application/octet-stream";
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { FileStorageService } from "../file/file-storage.service";
|
||||
import type { ExecContext, ScriptLogger } from "./code-executor.service";
|
||||
|
||||
export class ExecContextBuilder {
|
||||
@@ -50,6 +51,21 @@ export class ExecContextBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
scenarioId(scenarioId: string): this {
|
||||
this.ctx.scenarioId = scenarioId;
|
||||
return this;
|
||||
}
|
||||
|
||||
runId(runId: string): this {
|
||||
this.ctx.runId = runId;
|
||||
return this;
|
||||
}
|
||||
|
||||
fileService(fileService: FileStorageService): this {
|
||||
this.ctx.fileService = fileService;
|
||||
return this;
|
||||
}
|
||||
|
||||
build(): ExecContext {
|
||||
if (!this.ctx.page) throw new Error("ExecContextBuilder: page is required");
|
||||
if (!this.ctx.browser)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import * as https from "https";
|
||||
import * as http from "http";
|
||||
import { URL } from "url";
|
||||
|
||||
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
|
||||
const TIMEOUT_MS = 30000; // 30 seconds
|
||||
|
||||
function decodeDataUrl(urlStr: string): Buffer {
|
||||
const match = /^data:([^,]*),(.*)$/s.exec(urlStr);
|
||||
if (!match) {
|
||||
throw new Error("Malformed data: URL");
|
||||
}
|
||||
const [, meta, data] = match;
|
||||
if (meta.endsWith(";base64")) {
|
||||
return Buffer.from(data, "base64");
|
||||
}
|
||||
return Buffer.from(decodeURIComponent(data), "utf-8");
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
urlStr: string,
|
||||
options?: {
|
||||
method?: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: string;
|
||||
},
|
||||
): Promise<Buffer> {
|
||||
if (urlStr.startsWith("data:")) {
|
||||
return decodeDataUrl(urlStr);
|
||||
}
|
||||
|
||||
const url = new URL(urlStr);
|
||||
const protocol = url.protocol === "https:" ? https : http;
|
||||
const method = options?.method ?? "GET";
|
||||
const headers = options?.headers ?? {};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(
|
||||
{
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
path: url.pathname + url.search,
|
||||
method,
|
||||
headers,
|
||||
timeout: TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
// Follow redirects
|
||||
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
downloadFile(res.headers.location, options).then(resolve).catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.statusCode && res.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
let totalSize = 0;
|
||||
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
totalSize += chunk.length;
|
||||
if (totalSize > MAX_FILE_SIZE) {
|
||||
req.destroy();
|
||||
reject(new Error(`File exceeds maximum size of ${MAX_FILE_SIZE} bytes`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
|
||||
res.on("end", () => {
|
||||
resolve(Buffer.concat(chunks));
|
||||
});
|
||||
|
||||
res.on("error", reject);
|
||||
},
|
||||
);
|
||||
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
reject(new Error("Download timeout"));
|
||||
});
|
||||
|
||||
req.on("error", reject);
|
||||
|
||||
if (options?.body && (method === "POST" || method === "PUT")) {
|
||||
req.write(options.body);
|
||||
}
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/** Extracts the alias literals passed to `runSnippet("alias", ...)` calls in `code`. */
|
||||
export function extractRunSnippetAliases(code: string): string[] {
|
||||
const aliases: string[] = [];
|
||||
const regex = /runSnippet\s*\(\s*(['"`])((?:(?!\1).)*)\1/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = regex.exec(code)) !== null) {
|
||||
aliases.push(match[2]);
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the transitive closure of snippet aliases referenced (directly, or via
|
||||
* other snippets) by `stepCodes`, against the full alias -> code map. Aliases with
|
||||
* no matching entry in `snippetCodeByAlias` are dropped. Returned in discovery order.
|
||||
*/
|
||||
export function resolveUsedSnippetAliases(
|
||||
stepCodes: string[],
|
||||
snippetCodeByAlias: Record<string, string>,
|
||||
): string[] {
|
||||
const used: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const queue = stepCodes.flatMap((code) => extractRunSnippetAliases(code));
|
||||
while (queue.length > 0) {
|
||||
const alias = queue.shift()!;
|
||||
if (seen.has(alias)) continue;
|
||||
seen.add(alias);
|
||||
const code = snippetCodeByAlias[alias];
|
||||
if (code == null) continue;
|
||||
used.push(alias);
|
||||
queue.push(...extractRunSnippetAliases(code));
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a `runSnippet` reference into its alias and pinned version:
|
||||
* `"login@3"` → `{ alias: "login", version: 3 }`, `"login"` → `{ alias: "login", version: null }`.
|
||||
*/
|
||||
export function parseSnippetRef(ref: string): {
|
||||
alias: string;
|
||||
version: number | null;
|
||||
} {
|
||||
const match = /^(.+)@(\d+)$/.exec(ref);
|
||||
return match
|
||||
? { alias: match[1], version: Number(match[2]) }
|
||||
: { alias: ref, version: null };
|
||||
}
|
||||
@@ -1,8 +1,21 @@
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { IsInt, IsString, Max, Min, validateSync } from "class-validator";
|
||||
import {
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
validateSync,
|
||||
} from "class-validator";
|
||||
|
||||
import pkg from "../../package.json";
|
||||
|
||||
export enum TraceMode {
|
||||
On = "on",
|
||||
RetainOnFailure = "retain-on-failure",
|
||||
Off = "off",
|
||||
}
|
||||
|
||||
export class AppConfig {
|
||||
@IsString()
|
||||
NODE_ENV: string = "development";
|
||||
@@ -31,6 +44,20 @@ export class AppConfig {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
SESSION_DELETE_CLOSED_DAYS: number = 7;
|
||||
|
||||
@IsString()
|
||||
FILES_DIR: string = "data/files";
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
FILE_RUN_EXPIRATION_DAYS: number = 7;
|
||||
|
||||
@IsString()
|
||||
FILE_CLEANUP_CRON: string = "0 3 * * *";
|
||||
|
||||
@IsEnum(TraceMode)
|
||||
// Off by default: traces with screenshots and snapshots easily reach ~10 MB per run
|
||||
PLAYWRIGHT_TRACE_MODE: TraceMode = TraceMode.Off;
|
||||
}
|
||||
|
||||
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
|
||||
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy, CredentialService } from "./credential.service";
|
||||
import { CredentialQueryDto } from "./dto/credential-query.dto";
|
||||
import { CredentialService } from "./credential.service";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { CredentialExportDto } from "./dto/credential-export.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
@@ -39,7 +39,7 @@ export class CredentialController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all credentials (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated credentials" })
|
||||
findAll(@Query() query: PaginationQueryDto<CredentialOrderBy>) {
|
||||
findAll(@Query() query: CredentialQueryDto) {
|
||||
return this.credentialService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy } from "../credential.service";
|
||||
|
||||
const CREDENTIAL_ORDER_BY: CredentialOrderBy[] = ["id", "name", "lastUsedAt"];
|
||||
|
||||
export class CredentialQueryDto extends PaginationQueryDto<CredentialOrderBy> {
|
||||
@ApiPropertyOptional({ enum: CREDENTIAL_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(CREDENTIAL_ORDER_BY)
|
||||
declare orderBy?: CredentialOrderBy;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsObject, IsString } from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsObject, IsOptional, IsString } from "class-validator";
|
||||
import { EnvironmentData } from "../environment.entity";
|
||||
|
||||
export class CreateEnvironmentDto {
|
||||
@@ -8,6 +8,11 @@ export class CreateEnvironmentDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: "Generic key-value map for environment metadata",
|
||||
example: {
|
||||
|
||||
@@ -25,6 +25,11 @@ export class EnvironmentExportDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsObject()
|
||||
data: EnvironmentData;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { EnvironmentOrderBy } from "../environment.service";
|
||||
|
||||
const ENVIRONMENT_ORDER_BY: EnvironmentOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
|
||||
|
||||
export class EnvironmentQueryDto extends PaginationQueryDto<EnvironmentOrderBy> {
|
||||
@ApiPropertyOptional({ enum: ENVIRONMENT_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(ENVIRONMENT_ORDER_BY)
|
||||
declare orderBy?: EnvironmentOrderBy;
|
||||
}
|
||||
@@ -11,11 +11,11 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
|
||||
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
||||
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
||||
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
||||
import { EnvironmentOrderBy, EnvironmentService } from "./environment.service";
|
||||
import { EnvironmentService } from "./environment.service";
|
||||
|
||||
@ApiTags("environments")
|
||||
@Controller("environments")
|
||||
@@ -40,7 +40,7 @@ export class EnvironmentController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all environments (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated environments" })
|
||||
findAll(@Query() query: PaginationQueryDto<EnvironmentOrderBy>) {
|
||||
findAll(@Query() query: EnvironmentQueryDto) {
|
||||
return this.environmentService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ export class EnvironmentEntity {
|
||||
@Column({ unique: true })
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column("simple-json")
|
||||
data: EnvironmentData;
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ export class EnvironmentService {
|
||||
kind: "environment",
|
||||
id: env.id,
|
||||
name: env.name,
|
||||
description: env.description ?? undefined,
|
||||
data: env.data,
|
||||
};
|
||||
}
|
||||
@@ -81,18 +82,36 @@ export class EnvironmentService {
|
||||
if (dto.id) {
|
||||
const existing = await this.repo.findOneBy({ id: dto.id });
|
||||
if (existing) {
|
||||
Object.assign(existing, { name: dto.name, data: dto.data });
|
||||
Object.assign(existing, {
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
});
|
||||
return this.repo.save(existing);
|
||||
}
|
||||
return this.repo.save(
|
||||
this.repo.create({ id: dto.id, name: dto.name, data: dto.data }),
|
||||
this.repo.create({
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const byName = await this.repo.findOneBy({ name: dto.name });
|
||||
if (byName) {
|
||||
Object.assign(byName, { data: dto.data });
|
||||
Object.assign(byName, {
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
});
|
||||
return this.repo.save(byName);
|
||||
}
|
||||
return this.repo.save(this.repo.create({ name: dto.name, data: dto.data }));
|
||||
return this.repo.save(
|
||||
this.repo.create({
|
||||
name: dto.name,
|
||||
description: dto.description ?? null,
|
||||
data: dto.data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import { Injectable, OnModuleInit } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { SchedulerRegistry } from "@nestjs/schedule";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import * as crypto from "crypto";
|
||||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
import { CronJob } from "cron";
|
||||
import { Repository } from "typeorm";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { AppConfig } from "../config/app.config";
|
||||
import { FileEntity } from "./file.entity";
|
||||
import { ScenarioFileEntity } from "./scenario-file.entity";
|
||||
import { ScenarioRunFileEntity } from "./scenario-run-file.entity";
|
||||
|
||||
export interface FileMetadata {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
expiresAt: Date | null;
|
||||
createdAt: Date;
|
||||
path: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FileStorageService implements OnModuleInit {
|
||||
private static readonly DEFAULT_PAGE_SIZE = 20;
|
||||
private readonly logger = new TraceLogger(FileStorageService.name);
|
||||
private readonly filesDir: string;
|
||||
private readonly fileRunExpirationDays: number;
|
||||
private readonly fileCleanupCron: string;
|
||||
|
||||
constructor(
|
||||
@InjectRepository(FileEntity)
|
||||
readonly fileRepo: Repository<FileEntity>,
|
||||
@InjectRepository(ScenarioFileEntity)
|
||||
private readonly scenarioFileRepo: Repository<ScenarioFileEntity>,
|
||||
@InjectRepository(ScenarioRunFileEntity)
|
||||
private readonly scenarioRunFileRepo: Repository<ScenarioRunFileEntity>,
|
||||
configService: ConfigService<AppConfig, true>,
|
||||
private readonly schedulerRegistry: SchedulerRegistry,
|
||||
) {
|
||||
this.filesDir = configService.get("FILES_DIR");
|
||||
this.fileRunExpirationDays = configService.get("FILE_RUN_EXPIRATION_DAYS");
|
||||
this.fileCleanupCron = configService.get("FILE_CLEANUP_CRON");
|
||||
}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
// Ensure the files directory exists
|
||||
try {
|
||||
await fs.mkdir(this.filesDir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.logger.error(`Failed to create FILES_DIR ${this.filesDir}: ${(err as Error).message}`);
|
||||
}
|
||||
|
||||
// Register cleanup cron job dynamically so the schedule is runtime-configurable
|
||||
const job = new CronJob(this.fileCleanupCron, () => {
|
||||
void this.cleanupExpiredFiles();
|
||||
});
|
||||
this.schedulerRegistry.addCronJob("file-cleanup", job);
|
||||
job.start();
|
||||
this.logger.debug(`File cleanup cron registered: ${this.fileCleanupCron}`);
|
||||
|
||||
// Run cleanup at startup to catch any backlog
|
||||
await this.cleanupExpiredFiles();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a file to disk with sharded directory structure.
|
||||
* Returns the FileEntity (unsaved) with computed filePath.
|
||||
*/
|
||||
async saveFile(
|
||||
buffer: Buffer,
|
||||
originalName: string,
|
||||
mimeType: string,
|
||||
expiresAt?: Date,
|
||||
): Promise<FileEntity> {
|
||||
const fileId = crypto.randomUUID();
|
||||
const sha256 = crypto.createHash("sha256").update(buffer).digest("hex");
|
||||
const shardPath = this.getShardedPath(fileId);
|
||||
const fullPath = path.join(this.filesDir, shardPath);
|
||||
|
||||
// Create sharded directory
|
||||
const dirPath = path.dirname(fullPath);
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
|
||||
// Write file to disk and persist entity
|
||||
await fs.writeFile(fullPath, buffer);
|
||||
|
||||
const file = this.fileRepo.create({
|
||||
id: fileId,
|
||||
originalName,
|
||||
mimeType,
|
||||
size: buffer.length,
|
||||
sha256,
|
||||
filePath: shardPath,
|
||||
expiresAt: expiresAt ?? null,
|
||||
});
|
||||
|
||||
return this.fileRepo.save(file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the sharded path for a file ID: xx/xxxx/uuid
|
||||
*/
|
||||
private getShardedPath(uuid: string): string {
|
||||
return `${uuid.substring(0, 2)}/${uuid.substring(0, 4)}/${uuid}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns absolute disk path for a file.
|
||||
*/
|
||||
getAbsolutePath(filePath: string): string {
|
||||
return path.join(this.filesDir, filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists scenario files with pagination.
|
||||
*/
|
||||
async listScenarioFiles(
|
||||
scenarioId: string,
|
||||
limit?: number,
|
||||
offset?: number,
|
||||
): Promise<{ items: FileMetadata[]; total: number }> {
|
||||
const query = this.scenarioFileRepo
|
||||
.createQueryBuilder("sf")
|
||||
.innerJoinAndSelect("sf.file", "f")
|
||||
.where("sf.scenarioId = :scenarioId", { scenarioId });
|
||||
|
||||
const total = await query.getCount();
|
||||
|
||||
const items = await query
|
||||
.orderBy("sf.createdAt", "DESC")
|
||||
.skip(offset ?? 0)
|
||||
.take(limit ?? FileStorageService.DEFAULT_PAGE_SIZE)
|
||||
.getMany();
|
||||
return {
|
||||
items: items.map((sf) => this.mapFileEntityToMetadata(sf.file)),
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists run artifact files with pagination.
|
||||
*/
|
||||
async listRunFiles(
|
||||
runId: string,
|
||||
limit?: number,
|
||||
offset?: number,
|
||||
): Promise<{ items: FileMetadata[]; total: number }> {
|
||||
const query = this.scenarioRunFileRepo
|
||||
.createQueryBuilder("srf")
|
||||
.innerJoinAndSelect("srf.file", "f")
|
||||
.where("srf.runId = :runId", { runId });
|
||||
|
||||
const total = await query.getCount();
|
||||
|
||||
const items = await query
|
||||
.orderBy("srf.createdAt", "DESC")
|
||||
.skip(offset ?? 0)
|
||||
.take(limit ?? FileStorageService.DEFAULT_PAGE_SIZE)
|
||||
.getMany();
|
||||
return {
|
||||
items: items.map((srf) => this.mapFileEntityToMetadata(srf.file)),
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a file entity by ID.
|
||||
*/
|
||||
async getFile(fileId: string): Promise<FileEntity | null> {
|
||||
return this.fileRepo.findOneBy({ id: fileId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file and checks for orphaned FileEntity rows.
|
||||
* If a FileEntity has no remaining mappings, it is deleted along with its physical file.
|
||||
*/
|
||||
async deleteFile(fileId: string): Promise<void> {
|
||||
const file = await this.fileRepo.findOneBy({ id: fileId });
|
||||
if (!file) return;
|
||||
|
||||
// Check if this file still has any mappings
|
||||
const scenarioCount = await this.scenarioFileRepo.countBy({ fileId });
|
||||
const runCount = await this.scenarioRunFileRepo.countBy({ fileId });
|
||||
|
||||
// If no mappings remain, delete the file and its physical copy
|
||||
if (scenarioCount === 0 && runCount === 0) {
|
||||
const fullPath = this.getAbsolutePath(file.filePath);
|
||||
try {
|
||||
await fs.unlink(fullPath);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to delete physical file ${fullPath}: ${(err as Error).message}`);
|
||||
}
|
||||
|
||||
await this.fileRepo.delete(fileId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a run artifact file entry with auto-expiration.
|
||||
*/
|
||||
async createRunArtifact(buffer: Buffer, originalName: string, mimeType: string): Promise<FileEntity> {
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + this.fileRunExpirationDays * 24 * 60 * 60 * 1000);
|
||||
return this.saveFile(buffer, originalName, mimeType, expiresAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a run artifact with file and mapping in the database.
|
||||
*/
|
||||
async createAndSaveRunArtifact(
|
||||
runId: string,
|
||||
buffer: Buffer,
|
||||
originalName: string,
|
||||
mimeType: string,
|
||||
): Promise<FileEntity> {
|
||||
const savedFile = await this.createRunArtifact(buffer, originalName, mimeType);
|
||||
|
||||
// Create run file mapping
|
||||
const runFile = this.scenarioRunFileRepo.create({
|
||||
runId,
|
||||
fileId: savedFile.id,
|
||||
});
|
||||
await this.scenarioRunFileRepo.save(runFile);
|
||||
|
||||
return savedFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup job: deletes expired FileEntity rows and orphaned physical files.
|
||||
* Runs via @Cron scheduler and at module init.
|
||||
*/
|
||||
async cleanupExpiredFiles(): Promise<void> {
|
||||
const now = new Date();
|
||||
const expiredFiles = await this.fileRepo
|
||||
.createQueryBuilder("file")
|
||||
.where("file.expiresAt IS NOT NULL")
|
||||
.andWhere("file.expiresAt <= :now", { now })
|
||||
.setParameters({ now })
|
||||
.getMany();
|
||||
|
||||
if (expiredFiles.length === 0) return;
|
||||
|
||||
this.logger.debug(`Cleaning up ${expiredFiles.length} expired files`);
|
||||
|
||||
for (const file of expiredFiles) {
|
||||
try {
|
||||
// Delete associated mapping rows first (cascade will be handled, but we delete manually to ensure orphan check works)
|
||||
await this.scenarioFileRepo.delete({ fileId: file.id });
|
||||
await this.scenarioRunFileRepo.delete({ fileId: file.id });
|
||||
|
||||
// Delete the file entity and physical file
|
||||
await this.deleteFile(file.id);
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Failed to clean up expired file ${file.id}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps FileEntity to FileMetadata with absolute path.
|
||||
*/
|
||||
private mapFileEntityToMetadata(file: FileEntity): FileMetadata {
|
||||
return {
|
||||
id: file.id,
|
||||
name: file.originalName,
|
||||
mimeType: file.mimeType,
|
||||
size: file.size,
|
||||
sha256: file.sha256,
|
||||
expiresAt: file.expiresAt,
|
||||
createdAt: file.createdAt,
|
||||
path: this.getAbsolutePath(file.filePath),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from "typeorm";
|
||||
|
||||
@Entity("files")
|
||||
export class FileEntity {
|
||||
@PrimaryGeneratedColumn("uuid")
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
originalName: string;
|
||||
|
||||
@Column()
|
||||
mimeType: string;
|
||||
|
||||
@Column({ type: "integer" })
|
||||
size: number;
|
||||
|
||||
@Column()
|
||||
sha256: string;
|
||||
|
||||
@Column()
|
||||
filePath: string;
|
||||
|
||||
@Column({ type: "datetime", nullable: true })
|
||||
expiresAt: Date | null;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { FileEntity } from "./file.entity";
|
||||
import { FileStorageService } from "./file-storage.service";
|
||||
import { ScenarioFileEntity } from "./scenario-file.entity";
|
||||
import { ScenarioRunFileEntity } from "./scenario-run-file.entity";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([FileEntity, ScenarioFileEntity, ScenarioRunFileEntity])],
|
||||
providers: [FileStorageService],
|
||||
exports: [FileStorageService],
|
||||
})
|
||||
export class FileModule {}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
} from "typeorm";
|
||||
import { ScenarioEntity } from "../scenario/scenario.entity";
|
||||
import { FileEntity } from "./file.entity";
|
||||
|
||||
@Entity("scenario_files")
|
||||
export class ScenarioFileEntity {
|
||||
@PrimaryGeneratedColumn("uuid")
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
scenarioId: string;
|
||||
|
||||
@Column()
|
||||
fileId: string;
|
||||
|
||||
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "scenarioId" })
|
||||
scenario: ScenarioEntity;
|
||||
|
||||
@ManyToOne(() => FileEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "fileId" })
|
||||
file: FileEntity;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
} from "typeorm";
|
||||
import { ScenarioRunEntity } from "../scenario/scenario-run.entity";
|
||||
import { FileEntity } from "./file.entity";
|
||||
|
||||
@Entity("scenario_run_files")
|
||||
export class ScenarioRunFileEntity {
|
||||
@PrimaryGeneratedColumn("uuid")
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
runId: string;
|
||||
|
||||
@Column()
|
||||
fileId: string;
|
||||
|
||||
@ManyToOne(() => ScenarioRunEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "runId" })
|
||||
run: ScenarioRunEntity;
|
||||
|
||||
@ManyToOne(() => FileEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "fileId" })
|
||||
file: FileEntity;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -10,6 +10,21 @@ import { HttpExceptionFilter } from "./filters/http-exception.filter";
|
||||
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
|
||||
import { TraceInterceptor } from "./interceptors/trace.interceptor";
|
||||
|
||||
// Guard against uncaught exceptions thrown inside Playwright event listener
|
||||
// callbacks (e.g. a bad waitForURL predicate). Without this, Node.js v15+
|
||||
// crashes the process on any unhandled rejection or uncaught exception.
|
||||
const processLogger = new TraceLogger("Process");
|
||||
process.on("uncaughtException", (err) => {
|
||||
processLogger.error(`Uncaught exception (process kept alive): ${err.message}`, err.stack);
|
||||
});
|
||||
process.on("unhandledRejection", (reason) => {
|
||||
processLogger.error(
|
||||
`Unhandled promise rejection (process kept alive): ${
|
||||
reason instanceof Error ? reason.message : String(reason)
|
||||
}`,
|
||||
);
|
||||
});
|
||||
|
||||
async function bootstrap() {
|
||||
const API_PREFIX = "api/v1";
|
||||
const logger = new TraceLogger("Bootstrap");
|
||||
|
||||
@@ -5,6 +5,7 @@ import { CredentialModule } from "../credential/credential.module";
|
||||
import { EnvironmentModule } from "../environment/environment.module";
|
||||
import { ScenarioModule } from "../scenario/scenario.module";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { SnippetModule } from "../snippet/snippet.module";
|
||||
import { McpController } from "./mcp.controller";
|
||||
import { McpService } from "./mcp.service";
|
||||
|
||||
@@ -16,6 +17,7 @@ import { McpService } from "./mcp.service";
|
||||
BrowserModule,
|
||||
CodeExecutorModule,
|
||||
ScenarioModule,
|
||||
SnippetModule,
|
||||
],
|
||||
controllers: [McpController],
|
||||
providers: [McpService],
|
||||
|
||||
+872
-18
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,13 @@
|
||||
import { IsBoolean, IsNotEmpty, IsOptional, IsUUID } from "class-validator";
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsUUID,
|
||||
Min,
|
||||
} from "class-validator";
|
||||
import { TraceMode } from "../../config/app.config";
|
||||
|
||||
export class CreateScenarioRunDto {
|
||||
@IsUUID()
|
||||
@@ -8,4 +17,14 @@ export class CreateScenarioRunDto {
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
saveSession?: boolean;
|
||||
|
||||
@IsEnum(TraceMode)
|
||||
@IsOptional()
|
||||
traceMode?: TraceMode;
|
||||
|
||||
/** Scenario version to run; defaults to the latest. */
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@IsOptional()
|
||||
version?: number;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, Min } from "class-validator";
|
||||
|
||||
export class CreateScenarioStepDto {
|
||||
@ApiPropertyOptional({ example: "Check login page title" })
|
||||
@@ -12,4 +12,10 @@ export class CreateScenarioStepDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
execCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Step timeout in seconds (default: 60)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number;
|
||||
}
|
||||
@@ -1,9 +1,25 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsString } from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from "class-validator";
|
||||
|
||||
export class CreateScenarioDto {
|
||||
@ApiProperty({ example: "Login and verify cabinet" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional linked environment ID" })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Scenario timeout in seconds (default: 600)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number;
|
||||
}
|
||||
@@ -1 +1,15 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { ScenarioOrderBy } from "../scenario.service";
|
||||
|
||||
export { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
|
||||
const SCENARIO_ORDER_BY: ScenarioOrderBy[] = ["id", "name", "createdAt", "updatedAt"];
|
||||
|
||||
export class ScenarioQueryDto extends PaginationQueryDto<ScenarioOrderBy> {
|
||||
@ApiPropertyOptional({ enum: SCENARIO_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(SCENARIO_ORDER_BY)
|
||||
declare orderBy?: ScenarioOrderBy;
|
||||
}
|
||||
@@ -1,22 +1,17 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsIn, IsInt, IsOptional, Min } from "class-validator";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { RunStatus } from "../scenario-run.entity";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
|
||||
export class RunsQueryDto {
|
||||
@ApiPropertyOptional({ example: 1, default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number = 1;
|
||||
export type RunOrderBy = "createdAt" | "status" | "scenario.name";
|
||||
|
||||
@ApiPropertyOptional({ example: 20, default: 20 })
|
||||
const RUN_ORDER_BY: RunOrderBy[] = ["createdAt", "status", "scenario.name"];
|
||||
|
||||
export class RunsQueryDto extends PaginationQueryDto<RunOrderBy> {
|
||||
@ApiPropertyOptional({ enum: RUN_ORDER_BY })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
limit?: number = 20;
|
||||
@IsIn(RUN_ORDER_BY)
|
||||
declare orderBy?: RunOrderBy;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: ["pending", "in_progress", "pass", "fail"],
|
||||
|
||||
@@ -3,12 +3,16 @@ import { Type } from "class-transformer";
|
||||
import {
|
||||
IsArray,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
import { EnvironmentData } from "../../environment/environment.entity";
|
||||
|
||||
export class ScenarioStepExportDto {
|
||||
@ApiPropertyOptional()
|
||||
@@ -22,6 +26,71 @@ export class ScenarioStepExportDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
execCode: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export class CredentialExportDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsIn(["credential"])
|
||||
kind?: "credential";
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
id?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
data?: string | null;
|
||||
}
|
||||
|
||||
export class EnvironmentExportInlineDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsIn(["environment"])
|
||||
kind?: "environment";
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
id?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsObject()
|
||||
data: EnvironmentData;
|
||||
}
|
||||
|
||||
export class ScenarioCredentialMappingDto {
|
||||
@ApiProperty()
|
||||
@IsUUID()
|
||||
credentialId: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
alias: string;
|
||||
}
|
||||
|
||||
export class ScenarioExportDto {
|
||||
@@ -46,9 +115,43 @@ export class ScenarioExportDto {
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string;
|
||||
|
||||
@ApiProperty({ description: "Scenario version this export holds" })
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
version: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number;
|
||||
|
||||
@ApiPropertyOptional({ type: [ScenarioCredentialMappingDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ScenarioCredentialMappingDto)
|
||||
credentials?: ScenarioCredentialMappingDto[];
|
||||
|
||||
@ApiProperty({ type: [ScenarioStepExportDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ScenarioStepExportDto)
|
||||
steps: ScenarioStepExportDto[];
|
||||
}
|
||||
|
||||
/** Union type for multi-entity export array items */
|
||||
export type ExportEntity =
|
||||
| EnvironmentExportInlineDto
|
||||
| CredentialExportDto
|
||||
| ScenarioExportDto;
|
||||
@@ -18,4 +18,10 @@ export class UpdateScenarioStepDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
execCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Step timeout in seconds (null to use default of 60)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from "class-validator";
|
||||
|
||||
export class UpdateScenarioDto {
|
||||
@ApiPropertyOptional({ example: "Updated scenario name" })
|
||||
@@ -7,4 +7,20 @@ export class UpdateScenarioDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Optional markdown description" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Linked environment ID (null to unlink)" })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ description: "Scenario timeout in seconds (null to use default of 600)" })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import archiver = require("archiver");
|
||||
import { resolveUsedSnippetAliases } from "../common/snippet-usage";
|
||||
import { SnippetService } from "../snippet/snippet.service";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
|
||||
const DEFAULT_SCENARIO_TIMEOUT_SEC = 600;
|
||||
const DEFAULT_STEP_TIMEOUT_SEC = 60;
|
||||
|
||||
function slugify(name: string): string {
|
||||
const slug = name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return slug || "scenario";
|
||||
}
|
||||
|
||||
function jsStringLiteral(code: string): string {
|
||||
return JSON.stringify(code);
|
||||
}
|
||||
|
||||
function sanitizeAlias(alias: string): string {
|
||||
const sanitized = alias.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
|
||||
return sanitized || "snippet";
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a standalone, plug-and-play Playwright test project (package.json,
|
||||
* playwright.config.ts, test.spec.ts, .env, README) from a scenario's steps,
|
||||
* zipped for download. Each step's execCode is embedded verbatim and run
|
||||
* against a `context` shim that mirrors the shape scripts already use in
|
||||
* liqa (env, credentials, snippets, assert, ...).
|
||||
*/
|
||||
@Injectable()
|
||||
export class E2eExportService {
|
||||
constructor(
|
||||
private readonly scenarioService: ScenarioService,
|
||||
private readonly snippetService: SnippetService,
|
||||
) {}
|
||||
|
||||
async buildE2eTestPackage(scenarioId: string): Promise<{ filename: string; buffer: Buffer }> {
|
||||
const scenario = await this.scenarioService.findOne(scenarioId);
|
||||
const [credentialMap, snippetMap, attachedFiles] = await Promise.all([
|
||||
this.scenarioService.buildCredentialMap(scenarioId),
|
||||
this.snippetService.buildSnippetMap(),
|
||||
this.scenarioService.listScenarioFiles(scenarioId, 1000, 0),
|
||||
]);
|
||||
const envData = scenario.environment?.data ?? {};
|
||||
|
||||
const slug = slugify(scenario.name);
|
||||
const files: Record<string, string | Buffer> = {
|
||||
"package.json": this.buildPackageJson(slug),
|
||||
"playwright.config.ts": this.buildPlaywrightConfig(scenario.timeoutSeconds),
|
||||
".env": this.buildEnvFile(envData),
|
||||
"credentials.json": JSON.stringify(credentialMap, null, 2) + "\n",
|
||||
".gitignore": [
|
||||
"node_modules/",
|
||||
"test-results/",
|
||||
"playwright-report/",
|
||||
"downloads/",
|
||||
".env",
|
||||
"credentials.json",
|
||||
].join("\n") + "\n",
|
||||
"README.md": this.buildReadme(scenario.name, scenario.description),
|
||||
};
|
||||
|
||||
// Bundle any files attached to the scenario so getScenarioFiles works offline.
|
||||
const fileManifest: { id: string; name: string; mimeType: string; size: number; sha256: string; zipPath: string }[] =
|
||||
[];
|
||||
for (const item of attachedFiles.items as {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
}[]) {
|
||||
const { contentBuffer } = await this.scenarioService.getScenarioFileContentAsBuffer(
|
||||
scenarioId,
|
||||
item.id,
|
||||
);
|
||||
const zipPath = `files/${item.id}__${item.name}`;
|
||||
files[zipPath] = contentBuffer;
|
||||
fileManifest.push({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
mimeType: item.mimeType,
|
||||
size: item.size,
|
||||
sha256: item.sha256,
|
||||
zipPath,
|
||||
});
|
||||
}
|
||||
|
||||
// Bundle only the snippets actually referenced (directly or transitively via
|
||||
// other snippets) by this scenario's steps, as individual .js files under snippets/.
|
||||
const usedAliases = resolveUsedSnippetAliases(
|
||||
scenario.steps.map((s) => s.execCode ?? ""),
|
||||
snippetMap,
|
||||
);
|
||||
const snippetManifest: { alias: string; filename: string }[] = [];
|
||||
const usedSnippetFilenames = new Set<string>();
|
||||
for (const alias of usedAliases) {
|
||||
const code = snippetMap[alias];
|
||||
const base = sanitizeAlias(alias);
|
||||
let filename = `${base}.js`;
|
||||
let suffix = 2;
|
||||
while (usedSnippetFilenames.has(filename)) {
|
||||
filename = `${base}-${suffix}.js`;
|
||||
suffix += 1;
|
||||
}
|
||||
usedSnippetFilenames.add(filename);
|
||||
files[`snippets/${filename}`] = code;
|
||||
snippetManifest.push({ alias, filename });
|
||||
}
|
||||
|
||||
files["test.spec.ts"] = this.buildTestSpec(scenario, snippetManifest, fileManifest);
|
||||
|
||||
const buffer = await this.zip(files);
|
||||
return { filename: `${slug}-e2e-test.zip`, buffer };
|
||||
}
|
||||
|
||||
private buildPackageJson(slug: string): string {
|
||||
return (
|
||||
JSON.stringify(
|
||||
{
|
||||
name: `${slug}-e2e-test`,
|
||||
version: "1.0.0",
|
||||
private: true,
|
||||
scripts: {
|
||||
test: "playwright test",
|
||||
"test:headed": "playwright test --headed",
|
||||
},
|
||||
devDependencies: {
|
||||
"@playwright/test": "^1.59.1",
|
||||
dotenv: "^17.4.2",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
private buildPlaywrightConfig(scenarioTimeoutSeconds: number | null): string {
|
||||
const timeoutMs = (scenarioTimeoutSeconds ?? DEFAULT_SCENARIO_TIMEOUT_SEC) * 1000;
|
||||
return `import { defineConfig } from "@playwright/test";
|
||||
import * as dotenv from "dotenv";
|
||||
import * as path from "path";
|
||||
|
||||
dotenv.config({ path: path.resolve(__dirname, ".env") });
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
timeout: ${timeoutMs},
|
||||
use: {
|
||||
headless: true,
|
||||
},
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
private buildEnvFile(envData: Record<string, string>): string {
|
||||
const lines = Object.entries(envData).map(([key, value]) => `${key}=${value}`);
|
||||
return (
|
||||
[
|
||||
"# Environment values copied from the scenario's liqa environment.",
|
||||
"# This file may contain secrets - do not commit it.",
|
||||
...lines,
|
||||
].join("\n") + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
private buildReadme(scenarioName: string, description: string | null): string {
|
||||
const descriptionSection = description?.trim() ? `${description.trim()}\n\n` : "";
|
||||
return `# ${scenarioName} - standalone e2e test
|
||||
|
||||
${descriptionSection}## Setup
|
||||
|
||||
\`\`\`sh
|
||||
npm install
|
||||
npx playwright install --with-deps chromium
|
||||
\`\`\`
|
||||
|
||||
## Run
|
||||
|
||||
\`\`\`sh
|
||||
npm test
|
||||
\`\`\`
|
||||
|
||||
Environment values are loaded from \`.env\` (as plain process env vars). Credential
|
||||
data resolved from this scenario's aliases is stored in \`credentials.json\` and
|
||||
loaded by \`context.getCredential\`. Snippet bodies are stored as individual \`.js\`
|
||||
files under \`snippets/\` and loaded by \`context.runSnippet\`. Files attached to
|
||||
the scenario are bundled under \`files/\` and served locally by
|
||||
\`context.getScenarioFiles\`. \`context.downloadFile\` performs a real HTTP (or
|
||||
\`data:\` URL) download and saves the result under \`downloads/\`.
|
||||
`;
|
||||
}
|
||||
|
||||
private buildTestSpec(
|
||||
scenario: { name: string; timeoutSeconds: number | null; steps: { order: number; title: string | null; execCode: string | null; timeoutSeconds: number | null }[] },
|
||||
snippetManifest: { alias: string; filename: string }[],
|
||||
fileManifest: { id: string; name: string; mimeType: string; size: number; sha256: string; zipPath: string }[],
|
||||
): string {
|
||||
const steps = [...scenario.steps].sort((a, b) => a.order - b.order);
|
||||
const scenarioTimeoutSec = scenario.timeoutSeconds ?? DEFAULT_SCENARIO_TIMEOUT_SEC;
|
||||
|
||||
const stepBlocks = steps
|
||||
.map((step, index) => {
|
||||
const title = (step.title ?? `Step ${index + 1}`).replace(/`/g, "\\`");
|
||||
const timeoutSec = step.timeoutSeconds ?? scenarioTimeoutSec ?? DEFAULT_STEP_TIMEOUT_SEC;
|
||||
const code = step.execCode ?? "";
|
||||
return ` await test.step(\`${title}\`, async () => {
|
||||
const __run = new Function(
|
||||
"context",
|
||||
"console",
|
||||
"result",
|
||||
"expect",
|
||||
\`return (async (context) => { ${code.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")} })(context)\`,
|
||||
);
|
||||
const __timeoutMs = ${timeoutSec * 1000};
|
||||
const __output = await Promise.race([
|
||||
__run(context, console, undefined, expect),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error(\`Step timed out after ${timeoutSec}s\`)), __timeoutMs),
|
||||
),
|
||||
]);
|
||||
stepOutputs.push({ order: ${step.order}, output: __output });
|
||||
});`;
|
||||
})
|
||||
.join("\n\n");
|
||||
|
||||
return `import { test, expect } from "@playwright/test";
|
||||
import type { BrowserContext, Page } from "@playwright/test";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import * as crypto from "crypto";
|
||||
import * as http from "http";
|
||||
import * as https from "https";
|
||||
import { URL } from "url";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
// Credential data resolved from this scenario's aliases at export time.
|
||||
// Stored in credentials.json (gitignored) - contains sensitive values.
|
||||
const CREDENTIALS: Record<string, unknown> = JSON.parse(
|
||||
fs.readFileSync(path.resolve(__dirname, "credentials.json"), "utf-8"),
|
||||
);
|
||||
|
||||
// Snippet bodies are stored as individual .js files under snippets/, available
|
||||
// via context.runSnippet(alias, ...args).
|
||||
const SNIPPET_FILES: { alias: string; filename: string }[] = ${JSON.stringify(snippetManifest, null, 2)};
|
||||
|
||||
// Files attached to the scenario, bundled alongside this test under files/.
|
||||
const FILES: { id: string; name: string; mimeType: string; size: number; sha256: string; zipPath: string }[] =
|
||||
${JSON.stringify(fileManifest, null, 2)};
|
||||
|
||||
interface StepOutput {
|
||||
order: number;
|
||||
output: unknown;
|
||||
}
|
||||
|
||||
// ── Standalone downloadFile: real HTTP/data: URL fetch, no liqa backend involved ──
|
||||
|
||||
const MAX_DOWNLOAD_SIZE = 100 * 1024 * 1024; // 100 MB
|
||||
const DOWNLOAD_TIMEOUT_MS = 30000;
|
||||
|
||||
function decodeDataUrl(urlStr: string): Buffer {
|
||||
const match = /^data:([^,]*),(.*)$/s.exec(urlStr);
|
||||
if (!match) {
|
||||
throw new Error("Malformed data: URL");
|
||||
}
|
||||
const [, meta, data] = match;
|
||||
if (meta.endsWith(";base64")) {
|
||||
return Buffer.from(data, "base64");
|
||||
}
|
||||
return Buffer.from(decodeURIComponent(data), "utf-8");
|
||||
}
|
||||
|
||||
function fetchBytes(
|
||||
urlStr: string,
|
||||
options?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||
): Promise<Buffer> {
|
||||
if (urlStr.startsWith("data:")) {
|
||||
return Promise.resolve(decodeDataUrl(urlStr));
|
||||
}
|
||||
const url = new URL(urlStr);
|
||||
const protocol = url.protocol === "https:" ? https : http;
|
||||
const method = options?.method ?? "GET";
|
||||
const headers = options?.headers ?? {};
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = protocol.request(
|
||||
{ hostname: url.hostname, port: url.port, path: url.pathname + url.search, method, headers, timeout: DOWNLOAD_TIMEOUT_MS },
|
||||
(res) => {
|
||||
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
fetchBytes(res.headers.location, options).then(resolve).catch(reject);
|
||||
return;
|
||||
}
|
||||
if (res.statusCode && res.statusCode !== 200) {
|
||||
reject(new Error(\`HTTP \${res.statusCode}: \${res.statusMessage}\`));
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
let totalSize = 0;
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
totalSize += chunk.length;
|
||||
if (totalSize > MAX_DOWNLOAD_SIZE) {
|
||||
req.destroy();
|
||||
reject(new Error(\`File exceeds maximum size of \${MAX_DOWNLOAD_SIZE} bytes\`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on("end", () => resolve(Buffer.concat(chunks)));
|
||||
res.on("error", reject);
|
||||
},
|
||||
);
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
reject(new Error("Download timeout"));
|
||||
});
|
||||
req.on("error", reject);
|
||||
if (options?.body && (method === "POST" || method === "PUT")) {
|
||||
req.write(options.body);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
pdf: "application/pdf",
|
||||
doc: "application/msword",
|
||||
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
xls: "application/vnd.ms-excel",
|
||||
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
jpg: "image/jpeg",
|
||||
jpeg: "image/jpeg",
|
||||
png: "image/png",
|
||||
gif: "image/gif",
|
||||
csv: "text/csv",
|
||||
txt: "text/plain",
|
||||
zip: "application/zip",
|
||||
};
|
||||
|
||||
function inferMimeType(filename: string): string {
|
||||
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
|
||||
return MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
function buildContext(page: Page, browser: BrowserContext, stepOutputs: StepOutput[]) {
|
||||
const context: Record<string, unknown> = {
|
||||
page,
|
||||
browser,
|
||||
env: { ...process.env },
|
||||
getEnv(key: string): string {
|
||||
const value = process.env[key];
|
||||
if (value == null) {
|
||||
throw new Error(\`Environment value "\${key}" is not defined\`);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
getCredential(alias: string): unknown {
|
||||
if (!(alias in CREDENTIALS)) {
|
||||
throw new Error(\`Credential alias "\${alias}" not found in this export\`);
|
||||
}
|
||||
return CREDENTIALS[alias];
|
||||
},
|
||||
log: (...args: unknown[]) => console.log(...args),
|
||||
warn: (...args: unknown[]) => console.warn(...args),
|
||||
error: (...args: unknown[]) => console.error(...args),
|
||||
assert: async (fn: () => boolean | Promise<boolean>, description: string): Promise<void> => {
|
||||
let passed: boolean;
|
||||
let failureReason: string | undefined;
|
||||
try {
|
||||
passed = (await fn()) === true;
|
||||
} catch (err) {
|
||||
passed = false;
|
||||
failureReason = (err as Error).message;
|
||||
}
|
||||
if (passed) {
|
||||
console.log(\`Assertion passed: \${description}\`);
|
||||
return;
|
||||
}
|
||||
const message = failureReason
|
||||
? \`Assertion failed: \${description} (\${failureReason})\`
|
||||
: \`Assertion failed: \${description}\`;
|
||||
console.error(message);
|
||||
throw new Error(message);
|
||||
},
|
||||
getStepOutput: async (order: number): Promise<unknown> => {
|
||||
const targetOrder = order < 0 ? stepOutputs.length + order + 1 : order;
|
||||
return stepOutputs.find((s) => s.order === targetOrder)?.output ?? null;
|
||||
},
|
||||
runSnippet: async (alias: string, ...args: unknown[]): Promise<unknown> => {
|
||||
const entry = SNIPPET_FILES.find((s) => s.alias === alias);
|
||||
if (!entry) {
|
||||
throw new Error(\`Snippet alias "\${alias}" not found\`);
|
||||
}
|
||||
const snippetCode = fs.readFileSync(path.resolve(__dirname, "snippets", entry.filename), "utf-8");
|
||||
const snippetFn = new Function(
|
||||
"context",
|
||||
"console",
|
||||
"snippetArgs",
|
||||
"expect",
|
||||
\`return (async (context, ...args) => { \${snippetCode} })(context, ...snippetArgs)\`,
|
||||
);
|
||||
return snippetFn(context, console, args, expect);
|
||||
},
|
||||
dumpDom: async (): Promise<never> => {
|
||||
throw new Error("dumpDom is not available in this standalone export");
|
||||
},
|
||||
getScenarioFiles: async (opts?: { limit?: number; offset?: number }) => {
|
||||
const offset = opts?.offset ?? 0;
|
||||
const limit = opts?.limit ?? FILES.length;
|
||||
const items = FILES.slice(offset, offset + limit).map((f) => ({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
mimeType: f.mimeType,
|
||||
size: f.size,
|
||||
sha256: f.sha256,
|
||||
path: path.resolve(__dirname, f.zipPath),
|
||||
}));
|
||||
return { items, total: FILES.length };
|
||||
},
|
||||
downloadFile: async (
|
||||
url: string,
|
||||
opts?: { method?: string; headers?: Record<string, string>; body?: string; filename?: string },
|
||||
) => {
|
||||
const buffer = await fetchBytes(url, opts);
|
||||
const filename =
|
||||
opts?.filename ??
|
||||
(url.startsWith("data:") ? "download" : new URL(url).pathname.split("/").pop() || "download");
|
||||
const downloadsDir = path.resolve(__dirname, "downloads");
|
||||
fs.mkdirSync(downloadsDir, { recursive: true });
|
||||
const filePath = path.join(downloadsDir, filename);
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return {
|
||||
id: randomUUID(),
|
||||
name: filename,
|
||||
mimeType: inferMimeType(filename),
|
||||
size: buffer.length,
|
||||
sha256: crypto.createHash("sha256").update(buffer).digest("hex"),
|
||||
path: filePath,
|
||||
};
|
||||
},
|
||||
};
|
||||
return context;
|
||||
}
|
||||
|
||||
test.describe(${jsStringLiteral(scenario.name)}, () => {
|
||||
test(${jsStringLiteral(scenario.name)}, async ({ page, context: browserContext }) => {
|
||||
const stepOutputs: StepOutput[] = [];
|
||||
const context = buildContext(page, browserContext, stepOutputs);
|
||||
|
||||
${stepBlocks}
|
||||
});
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
private zip(files: Record<string, string | Buffer>): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const archive = archiver("zip", { zlib: { level: 9 } });
|
||||
const chunks: Buffer[] = [];
|
||||
archive.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
archive.on("error", (err) => reject(err));
|
||||
archive.on("end", () => resolve(Buffer.concat(chunks)));
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
archive.append(content, { name });
|
||||
}
|
||||
void archive.finalize();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,11 @@ export class ScenarioRunLogEntity {
|
||||
@Column({ type: "text" })
|
||||
message: string;
|
||||
|
||||
// Assigned in call order per run, since concurrent unawaited writes can
|
||||
// otherwise persist out of order (createdAt alone isn't a reliable tiebreaker).
|
||||
@Column({ type: "int", default: 0 })
|
||||
seq: number;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -32,12 +32,24 @@ export class ScenarioRunStepEntity {
|
||||
@JoinColumn({ name: "runId" })
|
||||
run: ScenarioRunEntity;
|
||||
|
||||
@Column("text")
|
||||
scenarioStepId: string;
|
||||
/** Live step this run step was created from; null once that step is deleted. */
|
||||
@Column("text", { nullable: true })
|
||||
scenarioStepId: string | null;
|
||||
|
||||
@ManyToOne(() => ScenarioStepEntity, { onDelete: "CASCADE" })
|
||||
@ManyToOne(() => ScenarioStepEntity, { onDelete: "SET NULL", nullable: true })
|
||||
@JoinColumn({ name: "scenarioStepId" })
|
||||
scenarioStep: ScenarioStepEntity;
|
||||
scenarioStep: ScenarioStepEntity | null;
|
||||
|
||||
// Step content copied from the run's scenario version, so the run executes
|
||||
// (and keeps showing) exactly what it was created with.
|
||||
@Column({ type: "text", nullable: true })
|
||||
title: string | null;
|
||||
|
||||
@Column({ type: "text", nullable: true })
|
||||
execCode: string | null;
|
||||
|
||||
@Column({ type: "int", nullable: true })
|
||||
timeoutSeconds: number | null;
|
||||
|
||||
@Column({ type: "text", default: "waiting" })
|
||||
status: RunStepStatus;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
import type { TraceMode } from "../config/app.config";
|
||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||
import { SessionEntity } from "../session/session.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||
@@ -41,12 +42,20 @@ export class ScenarioRunEntity {
|
||||
@JoinColumn({ name: "sessionId" })
|
||||
session: SessionEntity | null;
|
||||
|
||||
/** Scenario version this run executes; null for runs created before versioning. */
|
||||
@Column({ type: "int", nullable: true, default: null })
|
||||
scenarioVersion: number | null;
|
||||
|
||||
@Column({ type: "text", default: "pending" })
|
||||
status: RunStatus;
|
||||
|
||||
@Column({ type: "boolean", default: false })
|
||||
saveSession: boolean;
|
||||
|
||||
// Playwright trace mode for this run; null falls back to PLAYWRIGHT_TRACE_MODE
|
||||
@Column("text", { nullable: true, default: null })
|
||||
traceMode: TraceMode | null;
|
||||
|
||||
@OneToMany(() => ScenarioRunStepEntity, (rs) => rs.run, {
|
||||
cascade: true,
|
||||
eager: false,
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Injectable, OnModuleInit } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { Interval } from "@nestjs/schedule";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import * as crypto from "crypto";
|
||||
import * as fs from "fs/promises";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { Effect } from "effect";
|
||||
import type { Browser, BrowserContext, Page } from "playwright";
|
||||
import { chromium } from "playwright";
|
||||
import { Repository } from "typeorm";
|
||||
import { type AppConfig, TraceMode } from "../config/app.config";
|
||||
import { FileStorageService } from "../file/file-storage.service";
|
||||
import type { ScriptLogger } from "../code-executor/code-executor.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
|
||||
@@ -20,17 +27,17 @@ import { SnippetService } from "../snippet/snippet.service";
|
||||
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
|
||||
interface BrowserHandle {
|
||||
browser: Browser;
|
||||
context: BrowserContext;
|
||||
page: Page;
|
||||
tracing: boolean;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ScenarioSchedulerService {
|
||||
export class ScenarioSchedulerService implements OnModuleInit {
|
||||
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
|
||||
private readonly activeRuns = new Set<string>();
|
||||
private readonly runBrowsers = new Map<string, BrowserHandle>();
|
||||
@@ -40,6 +47,20 @@ export class ScenarioSchedulerService {
|
||||
private readonly runSnippets = new Map<string, Record<string, string>>();
|
||||
// Cache environment values per run (built once when a run starts)
|
||||
private readonly runEnvironments = new Map<string, EnvironmentData>();
|
||||
// Cache scenario-level timeout (seconds) per run
|
||||
private readonly runScenarioTimeouts = new Map<string, number | null>();
|
||||
// Cache scenarioId per run
|
||||
private readonly runScenarioIds = new Map<string, string>();
|
||||
// Monotonic log sequence per run, since persistLog writes are unawaited and
|
||||
// can otherwise resolve out of call order
|
||||
private readonly runLogSeq = new Map<string, number>();
|
||||
// Cache Playwright trace mode per run
|
||||
private readonly runTraceModes = new Map<string, TraceMode>();
|
||||
private readonly defaultTraceMode: TraceMode;
|
||||
|
||||
private static readonly DEFAULT_SCENARIO_TIMEOUT_SEC = 600;
|
||||
private static readonly DEFAULT_STEP_TIMEOUT_SEC = 60;
|
||||
private static readonly CONCURRENCY_LIMIT = 10;
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
@@ -55,7 +76,75 @@ export class ScenarioSchedulerService {
|
||||
private readonly snippetService: SnippetService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly sessionContextService: SessionContextService,
|
||||
) {}
|
||||
private readonly fileStorageService: FileStorageService,
|
||||
configService: ConfigService<AppConfig, true>,
|
||||
) {
|
||||
this.defaultTraceMode = configService.get("PLAYWRIGHT_TRACE_MODE");
|
||||
}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
const staleRuns = await this.runRepo.find({
|
||||
where: { status: "in_progress" },
|
||||
});
|
||||
if (staleRuns.length === 0) return;
|
||||
|
||||
this.logger.error(
|
||||
`Server restart detected ${staleRuns.length} in-progress run(s) that cannot be recovered — marking as failed`,
|
||||
);
|
||||
|
||||
for (const run of staleRuns) {
|
||||
this.logger.error(
|
||||
`Run #${run.id}: marked fail due to server restart (playwright session lost)`,
|
||||
);
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.forEach(
|
||||
staleRuns,
|
||||
(run) =>
|
||||
Effect.tryPromise(() =>
|
||||
this.failRun(
|
||||
run.id,
|
||||
"Run aborted: server restarted and playwright session could not be recovered",
|
||||
),
|
||||
).pipe(
|
||||
Effect.catchAll((err) =>
|
||||
Effect.sync(() =>
|
||||
this.logger.error(
|
||||
`Run #${run.id}: failRun threw unexpectedly — ${String(err)}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ concurrency: ScenarioSchedulerService.CONCURRENCY_LIMIT },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a run as failed, fails its active step run, cancels any queued
|
||||
* step runs, and persists an error log entry. Use this for all failure paths.
|
||||
*/
|
||||
private async failRun(runId: string, reason: string): Promise<void> {
|
||||
await this.runRepo.update(runId, { status: "fail" });
|
||||
// Fail the actively-running step; cancel anything still queued
|
||||
await this.runStepRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: "fail" })
|
||||
.where("runId = :runId AND status = 'in_progress'", { runId })
|
||||
.execute();
|
||||
await this.runStepRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: "cancelled" })
|
||||
.where("runId = :runId AND status IN (:...statuses)", {
|
||||
runId,
|
||||
statuses: ["pending", "waiting"],
|
||||
})
|
||||
.execute();
|
||||
this.persistLog(runId, null, "error", reason);
|
||||
}
|
||||
|
||||
private persistLog(
|
||||
runId: string,
|
||||
@@ -63,8 +152,10 @@ export class ScenarioSchedulerService {
|
||||
level: "log" | "warn" | "error",
|
||||
message: string,
|
||||
): void {
|
||||
const seq = (this.runLogSeq.get(runId) ?? 0) + 1;
|
||||
this.runLogSeq.set(runId, seq);
|
||||
void this.runLogRepo.save(
|
||||
this.runLogRepo.create({ runId, stepRunId, level, message }),
|
||||
this.runLogRepo.create({ runId, stepRunId, level, message, seq }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -98,47 +189,104 @@ export class ScenarioSchedulerService {
|
||||
@Interval(1000)
|
||||
async pickUpPendingRuns(): Promise<void> {
|
||||
const pending = await this.runRepo.find({ where: { status: "pending" } });
|
||||
for (const run of pending) {
|
||||
if (this.activeRuns.has(run.id)) continue;
|
||||
this.activeRuns.add(run.id);
|
||||
run.status = "in_progress";
|
||||
await this.runRepo.save(run);
|
||||
this.logger.log(`Run #${run.id} → in_progress`);
|
||||
// Pre-load credential map for the scenario
|
||||
const credMap = await this.scenarioService
|
||||
.buildCredentialMap(run.scenarioId)
|
||||
.catch(() => ({}) as Record<string, unknown>);
|
||||
this.runCredentials.set(run.id, credMap);
|
||||
// Pre-load snippet map
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
this.runSnippets.set(run.id, snippetMap);
|
||||
// Pre-load selected environment data
|
||||
const environmentData = await this.environmentRepo
|
||||
.findOneBy({ id: run.environmentId })
|
||||
.then((env) => env?.data ?? {})
|
||||
.catch(() => ({}) as EnvironmentData);
|
||||
this.runEnvironments.set(run.id, environmentData);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
);
|
||||
}
|
||||
const newRuns = pending.filter((run) => !this.activeRuns.has(run.id));
|
||||
if (newRuns.length === 0) return;
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.forEach(
|
||||
newRuns,
|
||||
(run) => {
|
||||
this.activeRuns.add(run.id);
|
||||
return Effect.tryPromise(async () => {
|
||||
run.status = "in_progress";
|
||||
await this.runRepo.save(run);
|
||||
this.logger.log(`Run #${run.id} → in_progress`);
|
||||
const credMap = await this.scenarioService
|
||||
.buildCredentialMap(run.scenarioId)
|
||||
.catch(() => ({}) as Record<string, unknown>);
|
||||
this.runCredentials.set(run.id, credMap);
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
this.runSnippets.set(run.id, snippetMap);
|
||||
const environmentData = await this.environmentRepo
|
||||
.findOneBy({ id: run.environmentId })
|
||||
.then((env) => env?.data ?? {})
|
||||
.catch(() => ({}) as EnvironmentData);
|
||||
this.runEnvironments.set(run.id, environmentData);
|
||||
// Legacy runs (no scenarioVersion) fall back to the live scenario
|
||||
const versioned =
|
||||
run.scenarioVersion != null
|
||||
? await this.scenarioService
|
||||
.findVersion(run.scenarioId, run.scenarioVersion)
|
||||
.catch(() => null)
|
||||
: await this.scenarioService
|
||||
.findOne(run.scenarioId)
|
||||
.catch(() => null);
|
||||
this.runScenarioTimeouts.set(
|
||||
run.id,
|
||||
versioned?.timeoutSeconds ?? null,
|
||||
);
|
||||
this.runScenarioIds.set(run.id, run.scenarioId);
|
||||
this.runTraceModes.set(
|
||||
run.id,
|
||||
run.traceMode ?? this.defaultTraceMode,
|
||||
);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchAll((err) =>
|
||||
Effect.promise(async () => {
|
||||
this.activeRuns.delete(run.id);
|
||||
this.runCredentials.delete(run.id);
|
||||
this.runSnippets.delete(run.id);
|
||||
this.runEnvironments.delete(run.id);
|
||||
this.runScenarioTimeouts.delete(run.id);
|
||||
this.runScenarioIds.delete(run.id);
|
||||
this.runTraceModes.delete(run.id);
|
||||
this.runLogSeq.delete(run.id);
|
||||
this.logger.error(
|
||||
`Run #${run.id}: setup failed — ${String(err)}`,
|
||||
);
|
||||
await this.failRun(
|
||||
run.id,
|
||||
`Run setup failed: ${String(err)}`,
|
||||
).catch(() => {});
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ concurrency: ScenarioSchedulerService.CONCURRENCY_LIMIT },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async processRunToCompletion(runId: string): Promise<void> {
|
||||
const scenarioTimeoutSec =
|
||||
this.runScenarioTimeouts.get(runId) ??
|
||||
ScenarioSchedulerService.DEFAULT_SCENARIO_TIMEOUT_SEC;
|
||||
const scenarioDeadline = Date.now() + scenarioTimeoutSec * 1000;
|
||||
try {
|
||||
let stepRun = await this.runStepRepo.findOne({
|
||||
where: { runId, status: "pending" },
|
||||
relations: ["scenarioStep"],
|
||||
order: { order: "ASC" },
|
||||
});
|
||||
while (stepRun) {
|
||||
if (Date.now() >= scenarioDeadline) {
|
||||
this.logger.error(
|
||||
`Run #${runId}: exceeded scenario timeout of ${scenarioTimeoutSec}s`,
|
||||
);
|
||||
await this.failRun(
|
||||
runId,
|
||||
`Scenario timed out after ${scenarioTimeoutSec}s`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await this.executeStepRun(stepRun);
|
||||
stepRun = await this.runStepRepo.findOne({
|
||||
where: { runId, status: "pending" },
|
||||
relations: ["scenarioStep"],
|
||||
order: { order: "ASC" },
|
||||
});
|
||||
}
|
||||
@@ -152,12 +300,18 @@ export class ScenarioSchedulerService {
|
||||
this.logger.error(
|
||||
`Run #${runId}: unexpected error: ${(err as Error).message}`,
|
||||
);
|
||||
await this.runRepo.update(runId, { status: "fail" });
|
||||
await this.failRun(runId, `Unexpected error: ${(err as Error).message}`);
|
||||
} finally {
|
||||
// Before runLogSeq is cleared, so the trace log entry keeps its order
|
||||
await this.saveTrace(runId);
|
||||
this.activeRuns.delete(runId);
|
||||
this.runCredentials.delete(runId);
|
||||
this.runSnippets.delete(runId);
|
||||
this.runEnvironments.delete(runId);
|
||||
this.runScenarioTimeouts.delete(runId);
|
||||
this.runScenarioIds.delete(runId);
|
||||
this.runTraceModes.delete(runId);
|
||||
this.runLogSeq.delete(runId);
|
||||
await this.maybePreserveSession(runId);
|
||||
}
|
||||
}
|
||||
@@ -217,12 +371,19 @@ export class ScenarioSchedulerService {
|
||||
}
|
||||
|
||||
private async executeStepRun(stepRun: ScenarioRunStepEntity): Promise<void> {
|
||||
const step = stepRun.scenarioStep as ScenarioStepEntity;
|
||||
// Run steps carry a copy of the step from the run's scenario version
|
||||
const step = stepRun;
|
||||
|
||||
stepRun.status = "in_progress";
|
||||
await this.runStepRepo.save(stepRun);
|
||||
this.logger.log(
|
||||
`StepRun #${stepRun.id} (run #${stepRun.runId}, step #${step.id} order=${step.order}) → in_progress`,
|
||||
`StepRun #${stepRun.id} (run #${stepRun.runId}, step #${step.scenarioStepId ?? "deleted"} order=${step.order}) → in_progress`,
|
||||
);
|
||||
this.persistLog(
|
||||
stepRun.runId,
|
||||
stepRun.id,
|
||||
"log",
|
||||
`Step ${step.order} started${step.title ? `: ${step.title}` : ""}`,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -235,6 +396,7 @@ export class ScenarioSchedulerService {
|
||||
const creds = this.runCredentials.get(stepRun.runId);
|
||||
const snips = this.runSnippets.get(stepRun.runId);
|
||||
const env = this.runEnvironments.get(stepRun.runId);
|
||||
const scenarioId = this.runScenarioIds.get(stepRun.runId);
|
||||
const execCtx = new ExecContextBuilder()
|
||||
.page(page)
|
||||
.browser(context)
|
||||
@@ -244,10 +406,38 @@ export class ScenarioSchedulerService {
|
||||
.credentials(creds)
|
||||
.environment(env)
|
||||
.snippets(snips)
|
||||
.scenarioId(scenarioId)
|
||||
.runId(stepRun.runId)
|
||||
.fileService(this.fileStorageService)
|
||||
.build();
|
||||
const { result: execOutput } = await this.codeExecutor.execute(execCtx);
|
||||
|
||||
await this.passStepRun(stepRun, null, execOutput);
|
||||
const scenarioTimeoutSec = this.runScenarioTimeouts.get(stepRun.runId) ?? null;
|
||||
const stepTimeoutSec =
|
||||
step.timeoutSeconds ??
|
||||
scenarioTimeoutSec ??
|
||||
ScenarioSchedulerService.DEFAULT_STEP_TIMEOUT_SEC;
|
||||
const stepTimeoutMs = stepTimeoutSec * 1000;
|
||||
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(
|
||||
() => reject(new Error(`Step timed out after ${stepTimeoutSec}s`)),
|
||||
stepTimeoutMs,
|
||||
);
|
||||
});
|
||||
try {
|
||||
const { result: execOutput } = await Promise.race([
|
||||
this.codeExecutor.execute(execCtx),
|
||||
timeoutPromise,
|
||||
]);
|
||||
await this.passStepRun(stepRun, null, execOutput);
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message ?? String(err);
|
||||
this.logger.error(`StepRun #${stepRun.id} threw: ${msg}`);
|
||||
await this.failStepRun(stepRun, msg);
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message ?? String(err);
|
||||
this.logger.error(`StepRun #${stepRun.id} threw: ${msg}`);
|
||||
@@ -268,9 +458,21 @@ export class ScenarioSchedulerService {
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
let tracing = false;
|
||||
const traceMode = this.runTraceModes.get(runId) ?? this.defaultTraceMode;
|
||||
if (traceMode !== TraceMode.Off) {
|
||||
try {
|
||||
await context.tracing.start({ screenshots: true, snapshots: true });
|
||||
tracing = true;
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Run #${runId}: failed to start tracing — ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const page = await context.newPage();
|
||||
|
||||
const handle: BrowserHandle = { browser, context, page };
|
||||
const handle: BrowserHandle = { browser, context, page, tracing };
|
||||
this.runBrowsers.set(runId, handle);
|
||||
this.logger.log(`Run #${runId}: browser created`);
|
||||
return handle;
|
||||
@@ -290,6 +492,53 @@ export class ScenarioSchedulerService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the run's Playwright trace and uploads it as a `trace.zip` run
|
||||
* artifact. In retain-on-failure mode, traces of runs that did not fail are
|
||||
* discarded.
|
||||
*/
|
||||
private async saveTrace(runId: string): Promise<void> {
|
||||
const handle = this.runBrowsers.get(runId);
|
||||
if (!handle?.tracing) return;
|
||||
handle.tracing = false;
|
||||
|
||||
const run = await this.runRepo.findOneBy({ id: runId }).catch(() => null);
|
||||
const traceMode = this.runTraceModes.get(runId) ?? this.defaultTraceMode;
|
||||
const keep = traceMode === TraceMode.On || run?.status === "fail";
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
try {
|
||||
if (!keep) {
|
||||
await handle.context.tracing.stop();
|
||||
return;
|
||||
}
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "liqa-trace-"));
|
||||
const tracePath = path.join(tmpDir, "trace.zip");
|
||||
await handle.context.tracing.stop({ path: tracePath });
|
||||
const trace = await fs.readFile(tracePath);
|
||||
await this.fileStorageService.createAndSaveRunArtifact(
|
||||
runId,
|
||||
trace,
|
||||
"trace.zip",
|
||||
"application/zip",
|
||||
);
|
||||
this.persistLog(
|
||||
runId,
|
||||
null,
|
||||
"log",
|
||||
"Playwright trace uploaded to run files (open with `npx playwright show-trace trace.zip` or https://trace.playwright.dev)",
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Run #${runId}: failed to save trace — ${(err as Error).message}`,
|
||||
);
|
||||
} finally {
|
||||
if (tmpDir) {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Pass / fail helpers ────────────────────────────────────────────────────
|
||||
|
||||
private async passStepRun(
|
||||
@@ -303,6 +552,12 @@ export class ScenarioSchedulerService {
|
||||
output !== null && output !== undefined ? JSON.stringify(output) : null;
|
||||
await this.runStepRepo.save(stepRun);
|
||||
this.logger.log(`StepRun #${stepRun.id} → pass`);
|
||||
this.persistLog(
|
||||
stepRun.runId,
|
||||
stepRun.id,
|
||||
"log",
|
||||
`Step ${stepRun.order} passed`,
|
||||
);
|
||||
|
||||
// Find the next waiting step in this run (next by order)
|
||||
const nextStep = await this.runStepRepo.findOne({
|
||||
@@ -339,6 +594,14 @@ export class ScenarioSchedulerService {
|
||||
stepRun.description = description;
|
||||
await this.runStepRepo.save(stepRun);
|
||||
this.logger.log(`StepRun #${stepRun.id} → fail: ${description}`);
|
||||
this.persistLog(
|
||||
stepRun.runId,
|
||||
stepRun.id,
|
||||
"error",
|
||||
`Step ${stepRun.order} failed: ${description}`,
|
||||
);
|
||||
|
||||
await this.dumpPageOnFailure(stepRun);
|
||||
|
||||
// Cancel all remaining waiting/pending step runs in this run
|
||||
await this.runStepRepo
|
||||
@@ -353,8 +616,56 @@ export class ScenarioSchedulerService {
|
||||
|
||||
this.logger.log(`Run #${stepRun.runId}: remaining steps cancelled`);
|
||||
|
||||
await this.closeBrowserHandle(stepRun.runId);
|
||||
// Don't close the browser here — maybePreserveSession (called from
|
||||
// processRunToCompletion's finally block) will either preserve it as a
|
||||
// session (saveSession=true) or close it (saveSession=false).
|
||||
await this.runRepo.update(stepRun.runId, { status: "fail" });
|
||||
this.logger.log(`Run #${stepRun.runId} → fail`);
|
||||
}
|
||||
|
||||
// ── Page dump on failure ────────────────────────────────────────────────────
|
||||
|
||||
private async dumpPageOnFailure(
|
||||
stepRun: ScenarioRunStepEntity,
|
||||
): Promise<void> {
|
||||
const handle = this.runBrowsers.get(stepRun.runId);
|
||||
if (!handle) return; // no browser was ever opened for this run (e.g. setup error)
|
||||
|
||||
const namePrefix = `step-${stepRun.order}-failure`;
|
||||
|
||||
try {
|
||||
const screenshot = await handle.page.screenshot({ fullPage: true });
|
||||
await this.fileStorageService.createAndSaveRunArtifact(
|
||||
stepRun.runId,
|
||||
screenshot,
|
||||
`${namePrefix}.png`,
|
||||
"image/png",
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`StepRun #${stepRun.id}: failed to capture failure screenshot — ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const html = await handle.page.content();
|
||||
await this.fileStorageService.createAndSaveRunArtifact(
|
||||
stepRun.runId,
|
||||
Buffer.from(html, "utf-8"),
|
||||
`${namePrefix}.html`,
|
||||
"text/html",
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`StepRun #${stepRun.id}: failed to capture failure page HTML — ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.persistLog(
|
||||
stepRun.runId,
|
||||
stepRun.id,
|
||||
"log",
|
||||
`Step ${stepRun.order} failed: page dump uploaded to run files`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ export class ScenarioStepEntity {
|
||||
@Column({ type: "text", nullable: true })
|
||||
execCode: string | null;
|
||||
|
||||
@Column({ type: "int", nullable: true })
|
||||
timeoutSeconds: number | null;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
Unique,
|
||||
} from "typeorm";
|
||||
import { ScenarioEntity } from "./scenario.entity";
|
||||
|
||||
/** A step as it was at a given scenario version. */
|
||||
export interface ScenarioStepSnapshot {
|
||||
/** Id of the live step this snapshot was taken from (may no longer exist). */
|
||||
id: string | null;
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Immutable snapshot of a scenario's content at one version. The `scenarios`
|
||||
* and `scenario_steps` tables always hold the latest version.
|
||||
*/
|
||||
@Entity("scenario_versions")
|
||||
@Unique(["scenarioId", "version"])
|
||||
export class ScenarioVersionEntity {
|
||||
@PrimaryGeneratedColumn("uuid")
|
||||
id: string;
|
||||
|
||||
@Column("text")
|
||||
scenarioId: string;
|
||||
|
||||
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "scenarioId" })
|
||||
scenario: ScenarioEntity;
|
||||
|
||||
@Column({ type: "int" })
|
||||
version: number;
|
||||
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: "text", nullable: true })
|
||||
environmentId: string | null;
|
||||
|
||||
@Column({ type: "int", nullable: true })
|
||||
timeoutSeconds: number | null;
|
||||
|
||||
@Column("simple-json")
|
||||
steps: ScenarioStepSnapshot[];
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -5,30 +5,39 @@ import {
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
} from "@nestjs/common";
|
||||
import { FileInterceptor } from "@nestjs/platform-express";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { Response } from "express";
|
||||
import type { File as MulterFile } from "multer";
|
||||
import { stringify as yamlStringify } from "yaml";
|
||||
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
|
||||
import { CreateScenarioRunDto } from "./dto/create-scenario-run.dto";
|
||||
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
|
||||
import { CreateScenarioDto } from "./dto/create-scenario.dto";
|
||||
import { PaginationQueryDto } from "./dto/pagination-query.dto";
|
||||
import { ScenarioQueryDto } from "./dto/pagination-query.dto";
|
||||
import { RunsQueryDto } from "./dto/runs-query.dto";
|
||||
import { ScenarioExportDto } from "./dto/scenario-export.dto";
|
||||
import { ExportEntity } from "./dto/scenario-export.dto";
|
||||
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
|
||||
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
|
||||
import { ScenarioOrderBy, ScenarioService } from "./scenario.service";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
import { E2eExportService } from "./e2e-export.service";
|
||||
|
||||
@ApiTags("scenarios")
|
||||
@Controller("scenarios")
|
||||
export class ScenarioController {
|
||||
constructor(private readonly scenarioService: ScenarioService) {}
|
||||
constructor(
|
||||
private readonly scenarioService: ScenarioService,
|
||||
private readonly e2eExportService: E2eExportService,
|
||||
) {}
|
||||
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -40,16 +49,16 @@ export class ScenarioController {
|
||||
}
|
||||
|
||||
@Post("import")
|
||||
@ApiOperation({ summary: "Import a scenario from an export payload" })
|
||||
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" })
|
||||
@ApiResponse({ status: 201, description: "Scenario imported" })
|
||||
importScenario(@Body() dto: ScenarioExportDto) {
|
||||
return this.scenarioService.importScenario(dto);
|
||||
importScenario(@Body() payload: unknown) {
|
||||
return this.scenarioService.importScenario(payload as any);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all scenarios (paginated)" })
|
||||
@ApiResponse({ status: 200 })
|
||||
findAll(@Query() query: PaginationQueryDto<ScenarioOrderBy>) {
|
||||
findAll(@Query() query: ScenarioQueryDto) {
|
||||
return this.scenarioService.findAll(query);
|
||||
}
|
||||
|
||||
@@ -62,6 +71,13 @@ export class ScenarioController {
|
||||
return this.scenarioService.findAllRuns(query);
|
||||
}
|
||||
|
||||
@Get("run-defaults")
|
||||
@ApiOperation({ summary: "Get server-configured defaults for new runs" })
|
||||
@ApiResponse({ status: 200 })
|
||||
getRunDefaults() {
|
||||
return this.scenarioService.getRunDefaults();
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "Get a scenario with its steps" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@@ -90,17 +106,79 @@ export class ScenarioController {
|
||||
return this.scenarioService.remove(id);
|
||||
}
|
||||
|
||||
@Get(":id/versions")
|
||||
@ApiOperation({ summary: "List a scenario's versions, newest first" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
listVersions(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.scenarioService.listVersions(id);
|
||||
}
|
||||
|
||||
@Get(":id/versions/:version")
|
||||
@ApiOperation({ summary: "Get one version of a scenario, with its steps" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario or version not found" })
|
||||
findVersion(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("version", ParseIntPipe) version: number,
|
||||
) {
|
||||
return this.scenarioService.findVersion(id, version);
|
||||
}
|
||||
|
||||
@Get(":id/export")
|
||||
@ApiOperation({ summary: "Export a scenario as portable YAML" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
async exportScenario(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Query("includeEnvironment") includeEnvironment: string,
|
||||
@Query("credentialIds") credentialIds: string | string[] | undefined,
|
||||
@Query("version", new ParseIntPipe({ optional: true }))
|
||||
version: number | undefined,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const payload = await this.scenarioService.exportScenario(id);
|
||||
const credIds: string[] = credentialIds
|
||||
? Array.isArray(credentialIds)
|
||||
? credentialIds
|
||||
: credentialIds.split(",").filter(Boolean)
|
||||
: [];
|
||||
const entities = await this.scenarioService.exportScenario(id, {
|
||||
includeEnvironment: includeEnvironment === "true",
|
||||
credentialIds: credIds,
|
||||
version,
|
||||
});
|
||||
res.setHeader("Content-Type", "application/yaml; charset=utf-8");
|
||||
return yamlStringify(payload);
|
||||
// Serialize as YAML stream: each entity separated by a comment header
|
||||
const kindLabels: Record<string, string> = {
|
||||
environment: "Environment",
|
||||
credential: "Credential",
|
||||
scenario: "Scenario",
|
||||
};
|
||||
const parts = (entities as ExportEntity[]).map((entity) => {
|
||||
const label = kindLabels[entity.kind ?? ""] ?? entity.kind ?? "Entity";
|
||||
const comment = `# --- ${label}: ${
|
||||
(entity as any).name ?? (entity as any).id ?? ""
|
||||
} ---`;
|
||||
return `${comment}\n${yamlStringify(entity)}`;
|
||||
});
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
@Get(":id/export-e2e")
|
||||
@ApiOperation({
|
||||
summary: "Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
|
||||
})
|
||||
@ApiResponse({ status: 200, description: "Zip archive" })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
async exportE2eTest(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const { filename, buffer } = await this.e2eExportService.buildE2eTestPackage(id);
|
||||
res.setHeader("Content-Type", "application/zip");
|
||||
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
||||
res.setHeader("Content-Length", buffer.length);
|
||||
res.send(buffer);
|
||||
}
|
||||
|
||||
// ── Steps ─────────────────────────────────────────────────────────────────
|
||||
@@ -151,6 +229,16 @@ export class ScenarioController {
|
||||
return this.scenarioService.removeStep(id, stepId);
|
||||
}
|
||||
|
||||
@Get(":id/used-snippets")
|
||||
@ApiOperation({
|
||||
summary: "List snippets referenced (directly or transitively) by this scenario's steps",
|
||||
})
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
getUsedSnippets(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.scenarioService.getUsedSnippets(id);
|
||||
}
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────
|
||||
|
||||
@Get(":id/credentials")
|
||||
@@ -218,6 +306,8 @@ export class ScenarioController {
|
||||
id,
|
||||
dto.environmentId,
|
||||
dto.saveSession,
|
||||
dto.traceMode,
|
||||
dto.version,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -233,6 +323,29 @@ export class ScenarioController {
|
||||
return this.scenarioService.findRun(id, runId, q);
|
||||
}
|
||||
|
||||
@Get(":id/run/:runId/logs/export")
|
||||
@ApiOperation({ summary: "Export run logs as CSV or Markdown" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario or run not found" })
|
||||
async exportRunLogs(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("runId", ParseUUIDPipe) runId: string,
|
||||
@Query("format") format: string | undefined,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const fmt = format === "csv" ? "csv" : "md";
|
||||
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
|
||||
const contentType =
|
||||
fmt === "csv" ? "text/csv; charset=utf-8" : "text/markdown; charset=utf-8";
|
||||
const ext = fmt === "csv" ? "csv" : "md";
|
||||
res.setHeader("Content-Type", contentType);
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`attachment; filename="run-${runId}-logs.${ext}"`,
|
||||
);
|
||||
return content;
|
||||
}
|
||||
|
||||
@Post(":id/run/:runId/wait")
|
||||
@HttpCode(200)
|
||||
@ApiOperation({
|
||||
@@ -247,4 +360,91 @@ export class ScenarioController {
|
||||
) {
|
||||
return this.scenarioService.waitForRun(id, runId);
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@Post(":id/files")
|
||||
@UseInterceptors(FileInterceptor("file"))
|
||||
@ApiOperation({ summary: "Upload a file to a scenario" })
|
||||
@ApiResponse({ status: 201, description: "File uploaded" })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
uploadFile(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@UploadedFile() file: MulterFile,
|
||||
@Body() body: { expiresAt?: string },
|
||||
) {
|
||||
return this.scenarioService.uploadFile(id, file, body.expiresAt);
|
||||
}
|
||||
|
||||
@Get(":id/files")
|
||||
@ApiOperation({ summary: "List files attached to a scenario" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
listScenarioFiles(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Query("limit") limit?: string,
|
||||
@Query("offset") offset?: string,
|
||||
) {
|
||||
return this.scenarioService.listScenarioFiles(
|
||||
id,
|
||||
limit ? parseInt(limit, 10) : undefined,
|
||||
offset ? parseInt(offset, 10) : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(":id/files/:fileId/content")
|
||||
@ApiOperation({ summary: "Download file content" })
|
||||
@ApiResponse({ status: 200, description: "File content" })
|
||||
@ApiResponse({ status: 404, description: "Scenario or file not found" })
|
||||
async getScenarioFileContent(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("fileId", ParseUUIDPipe) fileId: string,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
return this.scenarioService.getScenarioFileContent(id, fileId, res);
|
||||
}
|
||||
|
||||
@Get(":id/runs/:runId/files")
|
||||
@ApiOperation({ summary: "List files created during a run" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario or run not found" })
|
||||
listRunFiles(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("runId", ParseUUIDPipe) runId: string,
|
||||
@Query("limit") limit?: string,
|
||||
@Query("offset") offset?: string,
|
||||
) {
|
||||
return this.scenarioService.listRunFiles(
|
||||
id,
|
||||
runId,
|
||||
limit ? parseInt(limit, 10) : undefined,
|
||||
offset ? parseInt(offset, 10) : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(":id/runs/:runId/files/:fileId/content")
|
||||
@ApiOperation({ summary: "Download run artifact file content" })
|
||||
@ApiResponse({ status: 200, description: "File content" })
|
||||
@ApiResponse({ status: 404, description: "Scenario, run, or file not found" })
|
||||
async getRunFileContent(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("runId", ParseUUIDPipe) runId: string,
|
||||
@Param("fileId", ParseUUIDPipe) fileId: string,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
return this.scenarioService.getRunFileContent(id, runId, fileId, res);
|
||||
}
|
||||
|
||||
@Delete(":id/runs/:runId/files/:fileId")
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: "Delete a file from a run" })
|
||||
@ApiResponse({ status: 204, description: "File deleted" })
|
||||
@ApiResponse({ status: 404, description: "Scenario, run, or file not found" })
|
||||
deleteRunFile(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("runId", ParseUUIDPipe) runId: string,
|
||||
@Param("fileId", ParseUUIDPipe) fileId: string,
|
||||
) {
|
||||
return this.scenarioService.deleteRunFile(id, runId, fileId);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@ import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
|
||||
@@ -17,6 +20,23 @@ export class ScenarioEntity {
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ nullable: true, type: "text" })
|
||||
environmentId: string | null;
|
||||
|
||||
@Column({ type: "int", nullable: true })
|
||||
timeoutSeconds: number | null;
|
||||
|
||||
/** Latest version number; incremented whenever the scenario content changes. */
|
||||
@Column({ type: "int", default: 1 })
|
||||
version: number;
|
||||
|
||||
@ManyToOne(() => EnvironmentEntity, { nullable: true, onDelete: "SET NULL", eager: false })
|
||||
@JoinColumn({ name: "environmentId" })
|
||||
environment: EnvironmentEntity | null;
|
||||
|
||||
@OneToMany(() => ScenarioStepEntity, (step) => step.scenario, {
|
||||
cascade: true,
|
||||
eager: false,
|
||||
|
||||
@@ -4,6 +4,9 @@ import { CodeExecutorModule } from "../code-executor/code-executor.module";
|
||||
import { CredentialEntity } from "../credential/credential.entity";
|
||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||
import { EnvironmentModule } from "../environment/environment.module";
|
||||
import { FileModule } from "../file/file.module";
|
||||
import { ScenarioFileEntity } from "../file/scenario-file.entity";
|
||||
import { ScenarioRunFileEntity } from "../file/scenario-run-file.entity";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { SnippetModule } from "../snippet/snippet.module";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
@@ -11,30 +14,36 @@ import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
|
||||
import { ScenarioVersionEntity } from "./scenario-version.entity";
|
||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
import { ScenarioController } from "./scenario.controller";
|
||||
import { ScenarioEntity } from "./scenario.entity";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
import { E2eExportService } from "./e2e-export.service";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([
|
||||
ScenarioEntity,
|
||||
ScenarioStepEntity,
|
||||
ScenarioVersionEntity,
|
||||
ScenarioRunEntity,
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
CredentialEntity,
|
||||
EnvironmentEntity,
|
||||
ScenarioFileEntity,
|
||||
ScenarioRunFileEntity,
|
||||
]),
|
||||
CodeExecutorModule,
|
||||
SessionModule,
|
||||
EnvironmentModule,
|
||||
SnippetModule,
|
||||
FileModule,
|
||||
],
|
||||
controllers: [ScenarioController],
|
||||
providers: [ScenarioService, ScenarioSchedulerService],
|
||||
exports: [ScenarioService],
|
||||
providers: [ScenarioService, ScenarioSchedulerService, E2eExportService],
|
||||
exports: [ScenarioService, E2eExportService],
|
||||
})
|
||||
export class ScenarioModule {}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { SessionOrderBy } from "./session.service";
|
||||
|
||||
const SESSION_ORDER_BY: SessionOrderBy[] = ["id", "sessionName", "status", "lastUsedAt", "createdAt", "updatedAt"];
|
||||
|
||||
export class SessionQueryDto extends PaginationQueryDto<SessionOrderBy> {
|
||||
@ApiPropertyOptional({ enum: SESSION_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(SESSION_ORDER_BY)
|
||||
declare orderBy?: SessionOrderBy;
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { SessionQueryDto } from "./session-query.dto";
|
||||
import { SessionContextService } from "./session-context.service";
|
||||
import { SessionOrderBy, SessionService } from "./session.service";
|
||||
import { SessionService } from "./session.service";
|
||||
|
||||
function maskToken(token: string, head = 6, tail = 4): string {
|
||||
if (token.length <= head + tail + 1) return token;
|
||||
@@ -29,7 +29,7 @@ export class SessionController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all stored sessions (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated sessions" })
|
||||
findAll(@Query() query: PaginationQueryDto<SessionOrderBy>) {
|
||||
findAll(@Query() query: SessionQueryDto) {
|
||||
return this.sessionService.findAll(query);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import {
|
||||
IsIn,
|
||||
IsInt,
|
||||
Min,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
@@ -18,6 +20,11 @@ export class SnippetExportDto {
|
||||
@IsUUID()
|
||||
id?: string;
|
||||
|
||||
@ApiProperty({ description: "Snippet version this export holds" })
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
version: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsIn, IsOptional } from "class-validator";
|
||||
import { PaginationQueryDto } from "../../common/dto/pagination.dto";
|
||||
import { SnippetOrderBy } from "../snippet.service";
|
||||
|
||||
const SNIPPET_ORDER_BY: SnippetOrderBy[] = ["id", "alias", "title"];
|
||||
|
||||
export class SnippetQueryDto extends PaginationQueryDto<SnippetOrderBy> {
|
||||
@ApiPropertyOptional({ enum: SNIPPET_ORDER_BY })
|
||||
@IsOptional()
|
||||
@IsIn(SNIPPET_ORDER_BY)
|
||||
declare orderBy?: SnippetOrderBy;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
Unique,
|
||||
} from "typeorm";
|
||||
import { SnippetEntity } from "./snippet.entity";
|
||||
|
||||
/**
|
||||
* Immutable snapshot of a snippet at one version. The `snippets` table always
|
||||
* holds the latest version. Step code pins a version with
|
||||
* `runSnippet("alias@<version>")`.
|
||||
*/
|
||||
@Entity("snippet_versions")
|
||||
@Unique(["snippetId", "version"])
|
||||
export class SnippetVersionEntity {
|
||||
@PrimaryGeneratedColumn("uuid")
|
||||
id: string;
|
||||
|
||||
@Column("text")
|
||||
snippetId: string;
|
||||
|
||||
@ManyToOne(() => SnippetEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "snippetId" })
|
||||
snippet: SnippetEntity;
|
||||
|
||||
@Column({ type: "int" })
|
||||
version: number;
|
||||
|
||||
@Column()
|
||||
alias: string;
|
||||
|
||||
@Column({ default: "" })
|
||||
title: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column("text")
|
||||
code: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -5,17 +5,18 @@ import {
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { SnippetQueryDto } from "./dto/snippet-query.dto";
|
||||
import { CreateSnippetDto } from "./dto/create-snippet.dto";
|
||||
import { SnippetExportDto } from "./dto/snippet-export.dto";
|
||||
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
|
||||
import { SnippetOrderBy, SnippetService } from "./snippet.service";
|
||||
import { SnippetService } from "./snippet.service";
|
||||
|
||||
@ApiTags("snippets")
|
||||
@Controller("snippets")
|
||||
@@ -40,7 +41,7 @@ export class SnippetController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all snippets (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated snippets" })
|
||||
findAll(@Query() query: PaginationQueryDto<SnippetOrderBy>) {
|
||||
findAll(@Query() query: SnippetQueryDto) {
|
||||
return this.snippetService.findAll(query);
|
||||
}
|
||||
|
||||
@@ -48,9 +49,31 @@ export class SnippetController {
|
||||
@ApiOperation({ summary: "Export a snippet as a plain object" })
|
||||
@ApiResponse({ status: 200, description: "Snippet export payload" })
|
||||
@ApiResponse({ status: 404, description: "Snippet not found" })
|
||||
async exportSnippet(@Param("id", ParseUUIDPipe) id: string) {
|
||||
async exportSnippet(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Query("version", new ParseIntPipe({ optional: true })) version?: number,
|
||||
) {
|
||||
const snippet = await this.snippetService.findOne(id);
|
||||
return this.snippetService.exportSnippet(snippet);
|
||||
return this.snippetService.exportSnippet(snippet, version);
|
||||
}
|
||||
|
||||
@Get(":id/versions")
|
||||
@ApiOperation({ summary: "List a snippet's versions, newest first" })
|
||||
@ApiResponse({ status: 200, description: "Snippet versions" })
|
||||
@ApiResponse({ status: 404, description: "Snippet not found" })
|
||||
listVersions(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.snippetService.listVersions(id);
|
||||
}
|
||||
|
||||
@Get(":id/versions/:version")
|
||||
@ApiOperation({ summary: "Get one version of a snippet" })
|
||||
@ApiResponse({ status: 200, description: "Snippet version" })
|
||||
@ApiResponse({ status: 404, description: "Snippet or version not found" })
|
||||
findVersion(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Param("version", ParseIntPipe) version: number,
|
||||
) {
|
||||
return this.snippetService.findVersion(id, version);
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
|
||||
@@ -30,6 +30,10 @@ export class SnippetEntity {
|
||||
@Column("text")
|
||||
code: string;
|
||||
|
||||
/** Latest version number; incremented whenever the snippet changes. */
|
||||
@Column({ type: "int", default: 1 })
|
||||
version: number;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@ import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { SnippetController } from "./snippet.controller";
|
||||
import { SnippetEntity } from "./snippet.entity";
|
||||
import { SnippetVersionEntity } from "./snippet-version.entity";
|
||||
import { SnippetService } from "./snippet.service";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([SnippetEntity])],
|
||||
imports: [TypeOrmModule.forFeature([SnippetEntity, SnippetVersionEntity])],
|
||||
controllers: [SnippetController],
|
||||
providers: [SnippetService],
|
||||
exports: [SnippetService],
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
OnModuleInit,
|
||||
} from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import { In, Not, Repository } from "typeorm";
|
||||
import {
|
||||
PaginatedResult,
|
||||
PaginationQueryDto,
|
||||
@@ -13,8 +13,20 @@ import {
|
||||
import { CreateSnippetDto } from "./dto/create-snippet.dto";
|
||||
import { SnippetExportDto } from "./dto/snippet-export.dto";
|
||||
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
|
||||
import { SnippetVersionEntity } from "./snippet-version.entity";
|
||||
import { SnippetEntity } from "./snippet.entity";
|
||||
|
||||
type SnippetContent = Pick<
|
||||
SnippetEntity,
|
||||
"alias" | "title" | "description" | "code"
|
||||
>;
|
||||
|
||||
const sameContent = (a: SnippetContent, b: SnippetContent): boolean =>
|
||||
a.alias === b.alias &&
|
||||
a.title === b.title &&
|
||||
(a.description ?? null) === (b.description ?? null) &&
|
||||
a.code === b.code;
|
||||
|
||||
export type SnippetOrderBy =
|
||||
| "id"
|
||||
| "alias"
|
||||
@@ -27,6 +39,8 @@ export class SnippetService implements OnModuleInit {
|
||||
constructor(
|
||||
@InjectRepository(SnippetEntity)
|
||||
private readonly repo: Repository<SnippetEntity>,
|
||||
@InjectRepository(SnippetVersionEntity)
|
||||
private readonly versionRepo: Repository<SnippetVersionEntity>,
|
||||
) {}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
@@ -47,6 +61,32 @@ export class SnippetService implements OnModuleInit {
|
||||
"UPDATE snippets SET title = COALESCE(alias, '') WHERE title IS NULL OR title = ''",
|
||||
);
|
||||
}
|
||||
await this.backfillVersions();
|
||||
}
|
||||
|
||||
/** Records the current content of snippets that have no row for their current version yet. */
|
||||
private async backfillVersions(): Promise<void> {
|
||||
const snippets = await this.repo.find();
|
||||
for (const snippet of snippets) {
|
||||
const exists = await this.versionRepo.existsBy({
|
||||
snippetId: snippet.id,
|
||||
version: snippet.version,
|
||||
});
|
||||
if (!exists) await this.recordVersion(snippet);
|
||||
}
|
||||
}
|
||||
|
||||
private recordVersion(snippet: SnippetEntity): Promise<SnippetVersionEntity> {
|
||||
return this.versionRepo.save(
|
||||
this.versionRepo.create({
|
||||
snippetId: snippet.id,
|
||||
version: snippet.version,
|
||||
alias: snippet.alias,
|
||||
title: snippet.title,
|
||||
description: snippet.description,
|
||||
code: snippet.code,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async create(dto: CreateSnippetDto): Promise<SnippetEntity> {
|
||||
@@ -56,14 +96,17 @@ export class SnippetService implements OnModuleInit {
|
||||
`Snippet alias "${dto.alias}" already exists`,
|
||||
);
|
||||
}
|
||||
return this.repo.save(
|
||||
const snippet = await this.repo.save(
|
||||
this.repo.create({
|
||||
alias: dto.alias,
|
||||
title: dto.title,
|
||||
description: dto.description ?? null,
|
||||
code: dto.code,
|
||||
version: 1,
|
||||
}),
|
||||
);
|
||||
await this.recordVersion(snippet);
|
||||
return snippet;
|
||||
}
|
||||
|
||||
async findAll(
|
||||
@@ -96,8 +139,37 @@ export class SnippetService implements OnModuleInit {
|
||||
`Snippet alias "${dto.alias}" already exists`,
|
||||
);
|
||||
}
|
||||
Object.assign(snippet, dto);
|
||||
return this.repo.save(snippet);
|
||||
const next: SnippetContent = {
|
||||
alias: dto.alias ?? snippet.alias,
|
||||
title: dto.title ?? snippet.title,
|
||||
description:
|
||||
dto.description !== undefined ? dto.description : snippet.description,
|
||||
code: dto.code ?? snippet.code,
|
||||
};
|
||||
if (sameContent(snippet, next)) return snippet;
|
||||
Object.assign(snippet, next, { version: snippet.version + 1 });
|
||||
const saved = await this.repo.save(snippet);
|
||||
await this.recordVersion(saved);
|
||||
return saved;
|
||||
}
|
||||
|
||||
// ── Versions ──────────────────────────────────────────────────────────────
|
||||
|
||||
async listVersions(id: string): Promise<SnippetVersionEntity[]> {
|
||||
await this.findOne(id); // 404 guard
|
||||
return this.versionRepo.find({
|
||||
where: { snippetId: id },
|
||||
order: { version: "DESC" },
|
||||
});
|
||||
}
|
||||
|
||||
async findVersion(id: string, version: number): Promise<SnippetVersionEntity> {
|
||||
await this.findOne(id); // 404 guard
|
||||
const row = await this.versionRepo.findOneBy({ snippetId: id, version });
|
||||
if (!row) {
|
||||
throw new NotFoundException(`Snippet ${id} has no version ${version}`);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
@@ -105,58 +177,111 @@ export class SnippetService implements OnModuleInit {
|
||||
await this.repo.delete(id);
|
||||
}
|
||||
|
||||
/** Returns an alias→code map for all snippets (used by the executor). */
|
||||
/**
|
||||
* Returns the code map used by the executor: `alias` → latest code, plus
|
||||
* `alias@<version>` → that version's code for every stored version. Pinned
|
||||
* references use the snippet's current alias.
|
||||
*/
|
||||
async buildSnippetMap(): Promise<Record<string, string>> {
|
||||
const { data } = await this.findAll({ limit: 1000 });
|
||||
return Object.fromEntries(data.map((s) => [s.alias, s.code]));
|
||||
const map: Record<string, string> = Object.fromEntries(
|
||||
data.map((s) => [s.alias, s.code]),
|
||||
);
|
||||
if (data.length === 0) return map;
|
||||
const aliasById = new Map(data.map((s) => [s.id, s.alias]));
|
||||
const versions = await this.versionRepo.find({
|
||||
where: { snippetId: In([...aliasById.keys()]) },
|
||||
});
|
||||
for (const v of versions) {
|
||||
map[`${aliasById.get(v.snippetId)}@${v.version}`] = v.code;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
exportSnippet(snippet: SnippetEntity): SnippetExportDto {
|
||||
/** Returns the snippet entities matching the given aliases (used by executor/executor consumers). */
|
||||
async findByAliases(aliases: string[]): Promise<SnippetEntity[]> {
|
||||
if (aliases.length === 0) return [];
|
||||
return this.repo.find({ where: { alias: In(aliases) } });
|
||||
}
|
||||
|
||||
/** Exports the latest version, or `version` when given. */
|
||||
async exportSnippet(
|
||||
snippet: SnippetEntity,
|
||||
version?: number,
|
||||
): Promise<SnippetExportDto> {
|
||||
const content: SnippetContent & { version: number } =
|
||||
version === undefined || version === snippet.version
|
||||
? snippet
|
||||
: await this.findVersion(snippet.id, version);
|
||||
return {
|
||||
kind: "snippet",
|
||||
id: snippet.id,
|
||||
alias: snippet.alias,
|
||||
title: snippet.title,
|
||||
description: snippet.description,
|
||||
code: snippet.code,
|
||||
version: content.version,
|
||||
alias: content.alias,
|
||||
title: content.title,
|
||||
description: content.description,
|
||||
code: content.code,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores the exported version: upsert by id + version. An existing version
|
||||
* is left untouched; a new one is stored under its number and becomes the
|
||||
* latest when it is higher than the current latest.
|
||||
*/
|
||||
async importSnippet(dto: SnippetExportDto): Promise<SnippetEntity> {
|
||||
const alias = dto.alias ?? dto.name;
|
||||
if (!alias) {
|
||||
throw new ConflictException("Snippet alias is required");
|
||||
}
|
||||
const title = dto.title ?? alias;
|
||||
const content: SnippetContent = {
|
||||
alias,
|
||||
title: dto.title ?? alias,
|
||||
description: dto.description ?? null,
|
||||
code: dto.code,
|
||||
};
|
||||
|
||||
if (dto.id) {
|
||||
const existing = await this.repo.findOneBy({ id: dto.id });
|
||||
if (existing) {
|
||||
Object.assign(existing, {
|
||||
alias,
|
||||
title,
|
||||
description: dto.description ?? null,
|
||||
code: dto.code,
|
||||
});
|
||||
return this.repo.save(existing);
|
||||
}
|
||||
return this.repo.save(
|
||||
const existing = dto.id ? await this.repo.findOneBy({ id: dto.id }) : null;
|
||||
if (!existing) {
|
||||
await this.assertAliasFree(alias);
|
||||
const created = await this.repo.save(
|
||||
this.repo.create({
|
||||
id: dto.id,
|
||||
alias,
|
||||
title,
|
||||
description: dto.description ?? null,
|
||||
code: dto.code,
|
||||
...(dto.id ? { id: dto.id } : {}),
|
||||
...content,
|
||||
version: dto.version,
|
||||
}),
|
||||
);
|
||||
await this.recordVersion(created);
|
||||
return created;
|
||||
}
|
||||
return this.repo.save(
|
||||
this.repo.create({
|
||||
alias,
|
||||
title,
|
||||
description: dto.description ?? null,
|
||||
code: dto.code,
|
||||
|
||||
const hasVersion = await this.versionRepo.existsBy({
|
||||
snippetId: existing.id,
|
||||
version: dto.version,
|
||||
});
|
||||
if (hasVersion) return existing;
|
||||
|
||||
await this.versionRepo.save(
|
||||
this.versionRepo.create({
|
||||
snippetId: existing.id,
|
||||
version: dto.version,
|
||||
...content,
|
||||
}),
|
||||
);
|
||||
if (dto.version > existing.version) {
|
||||
if (alias !== existing.alias) await this.assertAliasFree(alias, existing.id);
|
||||
Object.assign(existing, content, { version: dto.version });
|
||||
return this.repo.save(existing);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
private async assertAliasFree(alias: string, exceptId?: string): Promise<void> {
|
||||
const conflict = await this.repo.findOneBy(
|
||||
exceptId ? { alias, id: Not(exceptId) } : { alias },
|
||||
);
|
||||
if (conflict) {
|
||||
throw new ConflictException(`Snippet alias "${alias}" already exists`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,16 @@ const makeContext = () => ({
|
||||
cookies: jest.fn().mockResolvedValue([]),
|
||||
addCookies: jest.fn().mockResolvedValue(undefined),
|
||||
addInitScript: jest.fn().mockResolvedValue(undefined),
|
||||
tracing: {
|
||||
start: jest.fn().mockResolvedValue(undefined),
|
||||
// Mimic Playwright writing the trace archive when a path is given
|
||||
stop: jest.fn().mockImplementation(async (opts?: { path?: string }) => {
|
||||
if (opts?.path) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
await require("fs/promises").writeFile(opts.path, "fake trace zip");
|
||||
}
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const makeBrowser = () => ({
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user