Compare commits

..
46 Commits
Author SHA1 Message Date
ars9 7d366e6368 feat(runs): add repeat run action to run detail page, bump to 1.14.0
- start a new run with the same environment and saveSession settings
  and navigate to it; disabled when the run's environment was deleted
- remount the run detail page per run id so per-run state resets
- type ScenarioRun.environmentId as nullable to match the backend
2026-09-30 14:35:31 +03:00
ars9 5ea1e38f25 feat(mcp): add credential CRUD tools, bump to 1.13.0
- add list/get/create/update/delete_credential MCP tools so credentials
  can be created and attached to scenarios entirely via MCP
- update_credential only changes the fields passed, keeping data intact
- add changelog entries for 1.13.0 and the missing 1.12.0 release
2026-09-30 14:26:15 +03:00
ars9andClaude Sonnet 5 d99bb75fc2 chore: sync package-lock.json version to 1.12.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 15:53:21 +03:00
ars9andClaude Sonnet 5 d79415cbb3 feat(scenario): dump page screenshot and HTML to run files on step failure
Captures a full-page screenshot and the current page HTML whenever a
scenario or snippet step fails, and uploads both as run artifacts so
failures can be diagnosed from the run's file list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 15:52:32 +03:00
ars9 1eea4eb8d8 feat(scenario): export scenarios as standalone playwright e2e test projects
- Added E2eExportService to package scenarios as plug-and-play zip archives
  containing package.json, playwright.config.ts, test.spec.ts, .env, credentials.json,
  snippets, and referenced scenario files
- Only bundles credentials, snippets, and files actually referenced (directly or
  transitively) by the scenario's steps, reducing archive size
- Exported test runs entirely offline using a context shim that mirrors liqa's API
  (page, getCredential, runSnippet, getScenarioFiles, downloadFile, assert, etc.)
- Added GET /scenarios/:id/export-e2e HTTP endpoint and export_e2e_test MCP tool
- Added getUsedSnippets() endpoint to list snippets referenced by a scenario
- Added "Used Snippets" section on scenario detail page
- Added archiver@^7.0.1 dependency for zip archive creation
- Bumped version to 1.11.0
2026-09-16 12:33:16 +03:00
ars9 385f51f3ba fix(scenario-logs): fix out-of-order run log persistence
- Add seq column assigned in call order to fix logs racing each other
  as fire-and-forget writes (e.g. a snippet's "started" entry could be
  saved after its "finished" entry)
- Log snippet start/finish/failure via context.runSnippet, matching
  existing step start/pass/fail logging
- Rework Markdown log export to per-entry sections instead of a table
- Version bump: 1.10.0 -> 1.10.1
2026-09-15 13:17:29 +03:00
ars9 540a7ec96b feat(logs): add scenario run logs export
- Backend: logs export endpoint for CSV and Markdown formats
- Frontend: ExportLogsModal with download button on run detail page
- Updated i18n and CHANGELOG
- Version bump: 1.9.1 -> 1.10.0
2026-09-15 13:04:59 +03:00
ars9 4e79d3cd81 feat(scenario): add automatic step boundary logging to run logs
- step start, pass, and fail events logged automatically
- step boundaries visible in run logs without explicit context.log calls
- version bumped from 1.9.0 to 1.9.1
2026-09-15 12:53:33 +03:00
ars9 cbfd4404c1 feat(scenario): add context.assert() API for script assertions
- Add context.assert(fn, description) for function assertions
- Logs outcome on success/failure, throws on assertion failure
- Bump package version from 1.8.0 to 1.9.0
2026-09-15 12:35:17 +03:00
ars9andClaude Sonnet 5 50820b8b40 feat(scenario): let context.downloadFile save data: URLs as run artifacts
Scenario steps can now persist in-script generated content (e.g. an
obtained VC's JWT) as a run file via context.downloadFile('data:...'),
without needing a network fetch. Bumps to 1.8.0.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 10:37:22 +03:00
ars9 502a3e4f2c 1.7.1 2026-04-21 18:09:49 +03:00
ars9 b57b55f3e1 feat(mcp): add file tools for scenarios and runs
- expose scenario file upload, listing, and content retrieval over MCP\n- expose run artifact listing and content retrieval with end-to-end coverage
2026-04-21 18:00:41 +03:00
ars9 06c662042b doc(changelog): add changelog 2026-04-21 17:09:05 +03:00
ars9 461669b3fb 1.7.0 2026-04-21 16:49:46 +03:00
ars9 9580a7b2df fix(files): expose expiry and disable expired downloads
- return expiresAt and createdAt for scenario and run file metadata\n- keep download actions visible while preventing expired file access
2026-04-21 16:46:33 +03:00
ars9 86f9ac5603 feat(files): add file management UI for scenarios and runs
- add scenario upload and download UI with typed file API helpers
- show run artifacts on run detail pages after polling completes
- handle multipart uploads and absolute file paths for downloads
2026-04-21 15:58:04 +03:00
ars9 6a91ce30e3 feat(files): add file storage subsystem with scenario and run artifact support
- add FileEntity, ScenarioFileEntity, ScenarioRunFileEntity with UUID-sharded disk tree
- FileStorageService: write/sha256/expiry, paginated listing, dynamic cleanup cron via SchedulerRegistry
- expose getScenarioFiles() and downloadFile() on ScriptContext for use in exec code
- wire scenarioId, runId, fileService into ExecContextBuilder and scenario scheduler
- add file upload and listing endpoints to ScenarioController
- add FILES_DIR, FILE_RUN_EXPIRATION_DAYS, FILE_CLEANUP_CRON to AppConfig
2026-04-21 13:01:09 +03:00
ars9 aa3bae9020 feat(client): set dynamic page title based on content
- add usePageTitle hook that writes '<title> | Liqa' to document.title
- list pages use section name; detail pages use entity name once loaded
- create/edit pages use static action title, edit includes entity name
2026-04-20 16:32:16 +03:00
ars9 ba46789226 feat(mcp): add snippet CRUD tools to MCP server
- register list_snippets, get_snippet, create_snippet, update_snippet, delete_snippet
- inject SnippetService into McpService and import SnippetModule into McpModule
- cover all five tools with integration tests including error cases
2026-04-20 16:21:52 +03:00
ars9 4e494ce4fd feat(scenarios): show last run status and timestamp on scenarios list
- extend findAll to join latest run per scenario via correlated subquery
- return lastRunStatus and lastRunAt fields in GET /scenarios response
- add Last Run column with badge and timestamp to ScenariosPage
- add integration tests for null and populated lastRunStatus
2026-04-17 15:13:28 +03:00
ars9 8c6158e8e3 1.6.1 2026-04-17 14:49:03 +03:00
ars9 b4cfe050fa perf(scenario-scheduler): parallelize run pickup with effect, add cache cleanup
- replace sequential for-loop in pickUpPendingRuns with Effect.forEach concurrency:10
- extract CONCURRENCY_LIMIT constant shared by both startup and pickup paths
- clear all run caches (creds, snippets, env, timeouts, activeRuns) on setup failure
- call failRun on setup error to leave the db run in a consistent failed state
2026-04-17 14:48:55 +03:00
ars9 a199700878 perf(scenario-scheduler): parallelize stale-run cleanup on startup with effect
- use Effect.forEach with concurrency:10 to fail up to 10 runs in parallel
- isolate each failRun with catchAll so one failure doesn't abort the rest
- log unexpected failRun errors per run without halting the batch
2026-04-17 14:32:25 +03:00
ars9 2a46b355db fix(scenario-runner): harden run failure handling across all paths
- add onModuleInit to fail in_progress runs on server restart
  (playwright sessions cannot be recovered after restart)
- extract failRun() shared method used by restart cleanup, timeout,
  and unexpected error paths for consistent step run status updates
- fix catch path to also fail/cancel step runs (previously left orphaned)
- accept plain {name, steps} payload in importScenario alongside
  full export format; throw BadRequestException for invalid input
- include stepRuns relation in findRuns paginated response
- add scenario-scheduler.spec.ts integration tests for onModuleInit
2026-04-17 14:11:43 +03:00
ars9 a50dce2755 feat(scenarios): add timeoutSeconds to scenarios and steps
- add timeoutSeconds field to scenario and step entities
- add timeoutSeconds to create/update DTOs for scenario and step
- enforce timeout via scheduler: abort run if step exceeds limit
- expose timeoutSeconds in MCP create/update scenario and step tools
- add client-side type, API, i18n, and form support for timeoutSeconds
- add integration tests for timeout persistence via REST and MCP
2026-04-17 13:46:30 +03:00
ars9 8dbd319bba fix(scenario-runner): preserve session on failed runs
- failStepRun was calling closeBrowserHandle immediately, removing the
  handle before maybePreserveSession could read it in the finally block
- delegate browser lifecycle to maybePreserveSession for both pass and
  fail paths so saveSession=true is honoured regardless of run outcome
2026-04-15 18:49:31 +03:00
ars9 67e230a647 fix(credential): stamp lastUsedAt via db CURRENT_TIMESTAMP when run consumes credentials 2026-04-15 12:26:09 +03:00
ars9 ad155e269c feat(table,runs,sessions): add server-side sorting and pagination
- add sortable column support to Table with asc/desc/unsorted icons
- active sort icon uses --color-primary; no header background change
- Table supports server-side mode via total/page/onPageChange props
- wire server-side sort+pagination in ScenariosPage, AllRunsPage, RunsPage, SessionsPage
- remove steps count column from run tables
- fix server: RunsQueryDto now extends PaginationQueryDto with orderBy/orderDir
- fix findAllRuns to use QueryBuilder; sort by scenario.name via JOIN
- add per-resource typed query DTOs with @IsIn allowlist on orderBy
- prevents SQL injection and returns 400 for unknown orderBy values
2026-04-15 12:18:47 +03:00
ars9 f268d0e3eb feat(scenarios): overhaul export/import with multi-entity YAML format
- export now accepts includeEnvironment and credentialIds query params
- output is a YAML stream with comment-delimited environment, credential, and scenario sections
- scenario entity includes credentials array with alias mappings
- import accepts both old single-object and new array format, upserts envs/creds before linking
- new ExportScenarioModal with env and per-credential checkboxes replaces direct download
2026-04-15 00:35:14 +03:00
ars9 a779ab4667 feat(scenarios): link scenarios to a default environment
- add optional ManyToOne relation from scenario to environment entity
- expose environmentId in create/update DTOs, service, and MCP tools
- pre-select linked environment in run modals on detail and list pages
- add environment selector to create/edit scenario forms
- show linked environment as a navigable link on scenario detail page
2026-04-15 00:05:55 +03:00
ars9 e6aacc899d feat(scenarios,environments): add markdown description field
- add optional description to scenario and environment entities
- expose description in create/update DTOs, MCP tools, and export DTOs
- render description as markdown on detail pages
- add description editor (CodeEditor) to create/edit forms for both resources
2026-04-14 23:53:45 +03:00
ars9 4dab218b75 1.6.0 2026-04-14 23:16:44 +03:00
ars9 622924ed53 refactor(nav): reorganize sidebar with dynamic sections at top
- move runs and sessions to top of navigation (most dynamic)
- add visual separator between dynamic and configuration sections
- reorder remaining items: scenarios, snippets, credentials, environments
- implement separator component in nav rendering logic
2026-04-14 23:15:49 +03:00
ars9 6c43b53590 fix(scenarios): add error handling for API calls and dev script with local API
- add catch handler to promises for better error visibility
- use null coalescing operators to prevent undefined accessing
- add dev:compose-api npm script pointing to localhost:13000 API
- include toast dependency in useCallback to avoid stale closures
2026-04-14 23:09:38 +03:00
ars9 e66e53c817 chore: apply code formatting and linting
- format long import statements with consistent line wrapping
- apply consistent indentation across client and server modules
- remove generated tsconfig.tsbuildinfo file
2026-04-14 22:54:03 +03:00
ars9 a71be39076 fix: fix links in scenario service 2026-04-14 21:11:35 +03:00
ars9 5ec9fd0bc3 refactor: add session and environment relationships to scenario run
- add sessionId optional column to ScenarioRunEntity
- add ManyToOne relationship to EnvironmentEntity (with eager loading)
- add ManyToOne relationship to SessionEntity (optional)
- update ScenarioRun client types to include session and environment data
- add environment name and session link to RunDetailPage
- update UI to display save session, environment, and session info
2026-04-14 19:29:48 +03:00
ars9 80d9af42b5 fix: add save session checkbox to run modal on scenarios list page
- add saveSessionFlag state to ScenariosPage
- pass saveSessionFlag to scenarios.run() call
- render save session checkbox in run modal when envs are available
- reset saveSessionFlag after scenario run completes
2026-04-14 19:24:13 +03:00
ars9 dcb002304b feat(run-detail): add expandable step output blocks with json pretty-printing
- add collapsible code blocks for step output with JSON syntax highlighting
- display byte count when output exists but no description available
- support both individual row expansion and header-level expand all toggle
- pretty-print JSON output for improved readability
- wrap log messages in code tags for monospace display
- fix step order numbering to start from 1 instead of 2
2026-04-14 19:19:39 +03:00
ars9 196bf4c2e8 feat: add saveSession flag to create scenario runs
- Add optional `saveSession` boolean parameter to CreateScenarioRunDto
- Add `saveSession` column to ScenarioRunEntity
- When saveSession=true and run completes, preserve the browser context as a named explore session instead of closing it
- Session name follows pattern: run-{runId}
- Automatically extracts token and localStorage for session persistence
- Injected SessionService and SessionContextService into ScenarioSchedulerService
- Updated MCP run_scenario tool to accept saveSession parameter
- Updated UI run dialog with checkbox to enable session preservation
- Client API updated to pass saveSession flag
2026-04-14 18:54:45 +03:00
ars9 0e47623a6b feat(browser,mcp): resolve environment and credentials from DB in exec
- POST /exec now accepts environmentId (UUID) and credentials (alias → UUID)
  instead of raw payloads; resolves entities via EnvironmentService and
  CredentialService before passing data to browserService.exec
- exec_code MCP tool updated with same schema: environmentId + credentials map
- CredentialModule imported into BrowserModule and McpModule
- docs(scenario): rewrite script runtime section for single context argument
- docs(mcp): update exec_code description to reflect new parameter shapes
- style: reorder imports across server source (formatter)
2026-04-14 18:09:28 +03:00
ars9 90be5a5490 refactor(code-executor): migrate user scripts to single context argument
- replace (page, context, helpers) signature with async (context) => {}
- add ScriptContext interface exposing page, browser, env, getEnv,
  getCredential, getStepOutput, runSnippet, dumpDom, log/warn/error
- rename getEnvUrl to getEnv throughout service and docs
- fix step ordering: normalizeStepOrder and run step rows are now 1-based
- migrate existing DB rows (scenario_steps, scenario_run_steps) +1
- update all tests and stored snippet/step code in DB to new API
2026-04-14 17:44:59 +03:00
ars9 1a2e786ca8 feat(browser): add environment, credentials, and script logger to POST /exec
- ExecDto gains optional `environment` and `credentials` fields
- BrowserService.exec forwards both to CodeExecutorService.execute so
  helpers.env, helpers.getEnvUrl(), and helpers.getCredential() work
  identically to scenario-scheduler steps
- script console.log/warn/error now routed through TraceLogger with
  session label prefix
- integration tests cover env/creds injection and missing-alias error
2026-04-14 16:57:06 +03:00
ars9 d34ea9e943 fix(browser): inject snippets into exec_code context; fix(ui): step order starts at 1 in run detail
- BrowserService.exec() now builds snippet map via SnippetService and passes
  it to CodeExecutorService.execute() for both named-session and anonymous paths
- SnippetModule added to BrowserModule imports to wire the dependency
- RunDetailPage step order column renders s.order + 1 (was 0-based)
2026-04-14 16:28:31 +03:00
ars9 310997c3ae feat(mcp): add credential and all-runs tools; replace deprecated z.string().uuid()
- add list_scenario_credentials, add_scenario_credential, remove_scenario_credential tools
- add list_all_runs tool (global across all scenarios)
- replace all deprecated z.string().uuid() with z.uuid() throughout mcp.service
2026-04-14 14:45:55 +03:00
ars9 7acd1bc5a1 feat(client): add nginx config for SPA routing and API proxy
- add try_files fallback to serve index.html for all non-asset paths
- proxy /api/ requests to the server container to avoid HTML being
  returned by nginx for API calls when using full route paths
2026-04-14 13:05:55 +03:00
131 changed files with 9342 additions and 1048 deletions

No files matched your search

+9
View File
@@ -12,3 +12,12 @@ server/dist
client/dist
*storybook.log
storybook-static
tsconfig.tsbuildinfo
# organization
TODO.md
# IDE/editor
.vscode/
.idea/
.github/
+127
View File
@@ -0,0 +1,127 @@
# Changelog
All notable changes to this project will be documented in this file.
## 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.
+1
View File
@@ -15,5 +15,6 @@ RUN npm run -w client build
FROM nginx:alpine AS runtime
COPY --from=builder /app/client/dist /usr/share/nginx/html
COPY client/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+17
View File
@@ -0,0 +1,17 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://server:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+3
View File
@@ -4,10 +4,12 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:compose-api": "VITE_API_URL=http://localhost:13000/api/v1 vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"test:compile": "tsc --noEmit",
"test:storybook": "vitest run --project storybook",
"lint": "eslint src .storybook",
"lint:fix": "eslint src .storybook --fix",
@@ -15,6 +17,7 @@
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.99.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
+6
View File
@@ -95,6 +95,12 @@
background: var(--color-secondary-hover);
}
.navSeparator {
height: var(--border-width);
background: var(--color-border);
margin: var(--space-2) var(--space-2);
}
.main {
flex: 1;
overflow-y: auto;
+39 -26
View File
@@ -11,13 +11,19 @@ const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
);
const EnvironmentDetailPage = lazy(() =>
import('./pages/environment/EnvironmentDetailPage').then((m) => ({ default: m.EnvironmentDetailPage })),
import('./pages/environment/EnvironmentDetailPage').then((m) => ({
default: m.EnvironmentDetailPage,
})),
);
const CreateEnvironmentPage = lazy(() =>
import('./pages/environment/CreateEnvironmentPage').then((m) => ({ default: m.CreateEnvironmentPage })),
import('./pages/environment/CreateEnvironmentPage').then((m) => ({
default: m.CreateEnvironmentPage,
})),
);
const EditEnvironmentPage = lazy(() =>
import('./pages/environment/EditEnvironmentPage').then((m) => ({ default: m.EditEnvironmentPage })),
import('./pages/environment/EditEnvironmentPage').then((m) => ({
default: m.EditEnvironmentPage,
})),
);
const SessionsPage = lazy(() =>
@@ -46,9 +52,7 @@ const EditStepPage = lazy(() =>
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
);
const RunsPage = lazy(() =>
import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })),
);
const RunsPage = lazy(() => import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })));
const RunDetailPage = lazy(() =>
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
);
@@ -60,13 +64,17 @@ const CredentialsPage = lazy(() =>
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
);
const CreateCredentialPage = lazy(() =>
import('./pages/credential/CreateCredentialPage').then((m) => ({ default: m.CreateCredentialPage })),
import('./pages/credential/CreateCredentialPage').then((m) => ({
default: m.CreateCredentialPage,
})),
);
const EditCredentialPage = lazy(() =>
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
);
const CredentialDetailPage = lazy(() =>
import('./pages/credential/CredentialDetailPage').then((m) => ({ default: m.CredentialDetailPage })),
import('./pages/credential/CredentialDetailPage').then((m) => ({
default: m.CredentialDetailPage,
})),
);
const SnippetsPage = lazy(() =>
@@ -82,13 +90,14 @@ const SnippetDetailPage = lazy(() =>
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
);
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
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 },
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
];
export default function App() {
@@ -106,18 +115,22 @@ export default function App() {
>
<div className={styles.sideContent}>
<nav className={styles.nav}>
{NAV.map(({ path, labelKey, Icon }) => (
<NavLink
key={path}
to={path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(labelKey)}
</NavLink>
))}
{NAV.map((item, index) =>
'separator' in item ? (
<div key={`separator-${index}`} className={styles.navSeparator} />
) : (
<NavLink
key={item.path}
to={item.path}
className={({ isActive }) =>
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
}
>
<item.Icon size={16} className={styles.navIcon} aria-hidden="true" />
{t(item.labelKey)}
</NavLink>
),
)}
</nav>
<div className={styles.sideFooter}>
+111 -24
View File
@@ -2,6 +2,8 @@ import type {
PaginatedResponse,
Credential,
Environment,
FileMetadata,
FileListResponse,
ScenarioCredential,
Session,
Scenario,
@@ -15,14 +17,22 @@ import { emitApiErrorToast } from '../lib/toast-events';
// API calls are versioned under /api/v1 by default.
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(/\/$/, '');
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(
/\/$/,
'',
);
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';
@@ -90,7 +100,9 @@ export const snippets = {
get(id: string): Promise<Snippet> {
return request(`/snippets/${id}`);
},
create(payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string }): Promise<Snippet> {
create(
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
): Promise<Snippet> {
return request('/snippets', {
method: 'POST',
body: JSON.stringify(payload),
@@ -128,13 +140,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),
@@ -157,8 +172,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}`);
@@ -171,19 +191,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),
@@ -192,10 +222,10 @@ export const scenarios = {
remove(id: string): Promise<void> {
return request(`/scenarios/${id}`, { method: 'DELETE' });
},
run(id: string, environmentId: string): Promise<ScenarioRun> {
run(id: string, environmentId: string, saveSession?: boolean): Promise<ScenarioRun> {
return request(`/scenarios/${id}/run`, {
method: 'POST',
body: JSON.stringify({ environmentId }),
body: JSON.stringify({ environmentId, saveSession }),
});
},
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
@@ -211,8 +241,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', {
@@ -220,6 +261,12 @@ export const scenarios = {
body: JSON.stringify(payload),
});
},
exportE2eTestUrl(id: string): string {
return `${BASE_URL}/scenarios/${id}/export-e2e`;
},
usedSnippets(id: string): Promise<Snippet[]> {
return request(`/scenarios/${id}/used-snippets`);
},
};
// ── Runs ─────────────────────────────────────────────────────────────────────
@@ -229,12 +276,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}`);
},
@@ -242,13 +287,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 ──────────────────────────────────────────────────────
@@ -274,12 +326,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 = {
@@ -302,3 +356,36 @@ 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`;
},
};
+30 -1
View File
@@ -16,6 +16,7 @@ export interface EnvironmentData {
export interface Environment {
id: string;
name: string;
description?: string;
data: EnvironmentData;
createdAt: string;
updatedAt: string;
@@ -66,6 +67,7 @@ export interface ScenarioStep {
order: number;
title: string | null;
execCode: string | null;
timeoutSeconds: number | null;
createdAt: string;
updatedAt: string;
}
@@ -82,8 +84,14 @@ export interface ScenarioCredential {
export interface Scenario {
id: string;
name: string;
description?: string;
environmentId?: string | null;
timeoutSeconds?: number | null;
environment?: Pick<Environment, 'id' | 'name'>;
steps?: ScenarioStep[];
scenarioCredentials?: ScenarioCredential[];
lastRunStatus?: ScenarioRunStatus | null;
lastRunAt?: string | null;
createdAt: string;
updatedAt: string;
}
@@ -97,8 +105,12 @@ export type LogLevel = 'log' | 'warn' | 'error';
export interface ScenarioRun {
id: string;
scenarioId: string;
environmentId: string;
environmentId: string | null;
sessionId?: string | null;
saveSession: boolean;
scenario?: Pick<Scenario, 'id' | 'name'>;
environment?: Pick<Environment, 'id' | 'name'>;
session?: { id: string; sessionName: string };
status: ScenarioRunStatus;
stepRuns?: ScenarioRunStep[];
createdAt: string;
@@ -131,3 +143,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,45 @@
import { useTranslation } from 'react-i18next';
import { X, Trash2 } from 'lucide-react';
import { Modal, Button } from '../../ui';
export interface DeleteConfirmationModalProps {
open: boolean;
title: string;
message: string;
onClose: () => void;
onConfirm: () => void;
isDeleting: boolean;
}
export function DeleteConfirmationModal({
open,
title,
message,
onClose,
onConfirm,
isDeleting,
}: DeleteConfirmationModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={title}
onClose={() => !isDeleting && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isDeleting}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={onConfirm} disabled={isDeleting}>
<Trash2 size={14} />
{t('common.button_delete')}
</Button>
</>
}
>
{message}
</Modal>
);
}
@@ -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>
);
}
@@ -0,0 +1,80 @@
import { useTranslation } from 'react-i18next';
import { X, Play } from 'lucide-react';
import { Modal, Button, Select } from '../../ui';
import type { Environment } from '../../api';
export interface RunScenarioModalProps {
open: boolean;
environments: Environment[];
selectedEnvId: string;
onEnvSelect: (envId: string) => void;
saveSessionFlag: boolean;
onSaveSessionChange: (flag: boolean) => void;
onClose: () => void;
onRun: () => void;
isRunning: boolean;
actionLabel?: string;
}
export function RunScenarioModal({
open,
environments,
selectedEnvId,
onEnvSelect,
saveSessionFlag,
onSaveSessionChange,
onClose,
onRun,
isRunning,
actionLabel,
}: RunScenarioModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={t('scenarios.run_modal_title')}
onClose={() => !isRunning && onClose()}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isRunning}>
<X size={14} />
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={onRun} disabled={isRunning || !selectedEnvId}>
<Play size={14} />
{actionLabel || t('scenarios.action_run')}
</Button>
</>
}
>
{environments.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
) : (
<>
<Select
label={t('scenarios.run_modal_env_label')}
value={selectedEnvId}
onChange={(e) => onEnvSelect(e.target.value)}
options={environments.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) => onSaveSessionChange(e.target.checked)}
/>
<span>{t('common.save_session')}</span>
</label>
</>
)}
</Modal>
);
}
+8
View File
@@ -0,0 +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';
+17
View File
@@ -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]);
}
+79 -4
View File
@@ -1,4 +1,17 @@
{
"common": {
"button_cancel": "Cancel",
"button_confirm": "Confirm",
"button_delete": "Delete",
"confirm_delete_credential": "Are you sure you want to delete this credential?",
"confirm_delete_environment": "Are you sure you want to delete this environment?",
"confirm_delete_scenario": "Are you sure you want to delete this scenario?",
"confirm_delete_step": "Are you sure you want to delete this step?",
"confirm_delete_session": "Are you sure you want to delete this session?",
"confirm_delete_snippet": "Are you sure you want to delete this snippet?",
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
"save_session": "Save session"
},
"errors": {
"not_found": "Not found",
"not_found_session": "Session {{id}} does not exist or has been deleted.",
@@ -19,8 +32,11 @@
},
"environments": {
"title": "Environments",
"created": "Environment created",
"updated": "Environment updated",
"col_id": "ID",
"col_name": "Name",
"col_description": "Description",
"col_data": "Data",
"col_updated": "Updated",
"empty": "No environments yet.",
@@ -41,16 +57,21 @@
"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"
},
"credentials": {
"title": "Credentials",
"created": "Credential created",
"updated": "Credential updated",
"empty": "No credentials yet.",
"loading": "Loading…",
"menu_label": "Credential options",
@@ -98,9 +119,15 @@
"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_description": "Description",
"col_last_run": "Last Run",
"col_updated": "Updated",
"empty": "No scenarios yet.",
"loading": "Loading…",
@@ -108,6 +135,7 @@
"action_delete": "Delete",
"field_id": "ID",
"field_name": "Name",
"field_description": "Description",
"field_steps": "Steps",
"field_created": "Created",
"field_updated": "Updated",
@@ -121,6 +149,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",
@@ -128,10 +157,16 @@
"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",
"cred_empty": "No credentials assigned.",
"cred_col_alias": "Alias",
"cred_col_name": "Credential",
@@ -149,7 +184,15 @@
"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",
"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",
@@ -165,6 +208,8 @@
"page_size": "Items per page"
},
"steps": {
"created": "Step created",
"updated": "Step updated",
"create_title": "Add Step",
"edit_title": "Edit Step #{{order}}",
"loading": "Loading…",
@@ -183,7 +228,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",
@@ -211,10 +259,20 @@
"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",
"created": "Snippet created",
"updated": "Snippet updated",
"empty": "No snippets yet.",
"loading": "Loading…",
"menu_label": "Snippet options",
@@ -247,5 +305,22 @@
"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",
"expiredTooltip": "File is expired",
"empty": "No files uploaded.",
"totalCount": "Total: {{count}} file(s)",
"artifactsTitle": "Artifacts"
}
}
+6 -5
View File
@@ -6,6 +6,7 @@ export interface ApiErrorToastDetail {
export function emitApiErrorToast(message: string): void {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
detail: { message },
@@ -13,17 +14,17 @@ export function emitApiErrorToast(message: string): void {
);
}
export function subscribeApiErrorToasts(
handler: (message: string) => void,
): () => void {
export function subscribeApiErrorToasts(handler: (message: string) => void): () => void {
if (typeof window === 'undefined') return () => {};
const listener = (event: Event) => {
const custom = event as CustomEvent<ApiErrorToastDetail>;
const message = custom.detail?.message;
if (message) handler(message);
};
window.addEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
window.addEventListener(API_ERROR_TOAST_EVENT, listener);
return () => {
window.removeEventListener(API_ERROR_TOAST_EVENT, listener as EventListener);
window.removeEventListener(API_ERROR_TOAST_EVENT, listener);
};
}
+10 -5
View File
@@ -1,17 +1,22 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './i18n';
import './ui/tokens.css';
import App from './App';
import { ToastProvider } from './ui';
const queryClient = new QueryClient();
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
<QueryClientProvider client={queryClient}>
<ToastProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ToastProvider>
</QueryClientProvider>
</StrictMode>,
);
@@ -1,6 +1,7 @@
import { useState } from 'react';
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();
@@ -16,9 +18,8 @@ export function CreateCredentialPage() {
const [nameError, setNameError] = useState('');
const [dataError, setDataError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -35,14 +36,12 @@ export function CreateCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const credential = await credentials.create(name.trim(), data.trim() || undefined);
toast.success('Credential created');
toast.success(t('credentials.created'));
navigate(`/credentials/${credential.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -54,7 +53,11 @@ export function CreateCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: t('credentials.create_title') },
]}
/>
@@ -1,20 +1,14 @@
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';
import { credentials } from '../../api';
import type { Credential } from '../../api';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function CredentialDetailPage() {
@@ -23,7 +17,7 @@ export function CredentialDetailPage() {
const navigate = useNavigate();
const [credential, setCredential] = useState<Credential | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(credential?.name ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -32,7 +26,6 @@ export function CredentialDetailPage() {
credentials
.get(id)
.then(setCredential)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -65,7 +58,11 @@ export function CredentialDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{ label: credential?.name ?? `#${id}` },
]}
/>
@@ -136,23 +133,14 @@ export function CredentialDetailPage() {
</>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('credentials.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
message={t('common.confirm_delete_credential')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+11 -20
View File
@@ -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';
@@ -11,10 +12,10 @@ import {
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function CredentialCard({
@@ -100,10 +101,10 @@ 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);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -112,7 +113,6 @@ export function CredentialsPage() {
credentials
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -145,8 +145,8 @@ export function CredentialsPage() {
const payload = yamlParse(text) as unknown;
const imported = await credentials.importCredential(payload);
navigate(`/credentials/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -179,23 +179,14 @@ export function CredentialsPage() {
</div>
)}
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('credentials.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('credentials.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this credential?
</Modal>
message={t('common.confirm_delete_credential')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
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,12 +16,16 @@ 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('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -31,11 +36,10 @@ export function EditCredentialPage() {
setName(c.name);
setData(c.data ?? '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!name.trim()) {
@@ -52,17 +56,15 @@ export function EditCredentialPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await credentials.update(id!, {
name: name.trim(),
data: data.trim() || null,
});
toast.success('Credential updated');
toast.success(t('credentials.updated'));
navigate(`/credentials/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -74,7 +76,11 @@ export function EditCredentialPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('credentials.title'), icon: <KeyRound size={14} />, onClick: () => navigate('/credentials') },
{
label: t('credentials.title'),
icon: <KeyRound size={14} />,
onClick: () => navigate('/credentials'),
},
{
label: credential?.name ?? `#${id}`,
onClick: () => navigate(`/credentials/${id}`),
@@ -1,6 +1,7 @@
import { useState } from 'react';
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,17 +9,18 @@ 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('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
@@ -42,14 +44,16 @@ export function CreateEnvironmentPage() {
return;
}
setSaving(true);
setError(null);
try {
const env = await environments.create(name.trim(), parsedData);
toast.success('Environment created');
const env = await environments.create(
name.trim(),
parsedData,
description.trim() || undefined,
);
toast.success(t('environments.created'));
navigate(`/environments/${env.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -61,7 +65,11 @@ export function CreateEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: t('environments.create_title') },
]}
/>
@@ -82,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 } from 'react';
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,12 +16,15 @@ 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('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -29,13 +33,13 @@ export function EditEnvironmentPage() {
.then((data) => {
setEnv(data);
setName(data.name);
setDescription(data.description || '');
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('environments.form_name_required'));
@@ -59,17 +63,16 @@ export function EditEnvironmentPage() {
return;
}
setSaving(true);
setError(null);
try {
await environments.update(id!, {
name: name.trim(),
description: description.trim() || undefined,
data: parsedData,
});
toast.success('Environment updated');
toast.success(t('environments.updated'));
navigate(`/environments/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -81,7 +84,11 @@ export function EditEnvironmentPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{
label: env?.name ?? `#${id}`,
onClick: () => navigate(`/environments/${id}`),
@@ -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,20 +1,32 @@
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Upload, Pencil, Trash2, Globe } from 'lucide-react';
import { usePageTitle } from '../../hooks/usePageTitle';
import { useNavigate, useParams } from 'react-router-dom';
import { stringify as yamlStringify } from 'yaml';
import { environments } from '../../api';
import type { Environment } from '../../api';
import { Breadcrumbs, Button, Card, DescriptionList, Modal, Timestamp, UuidBadge } from '../../ui';
import { environments } from '../../api';
import { DeleteConfirmationModal } from '../../components/modals';
import {
Breadcrumbs,
Button,
Card,
DescriptionList,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
} from '../../ui';
import styles from '../Page.module.css';
export function EnvironmentDetailPage() {
const { t } = useTranslation();
const toast = useToast();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [env, setEnv] = useState<Environment | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(env?.name ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
@@ -24,9 +36,9 @@ export function EnvironmentDetailPage() {
environments
.get(id)
.then(setEnv)
.catch((err: Error) => setError(err.message))
.catch((err: Error) => toast.error((err as Error).message))
.finally(() => setLoading(false));
}, [id]);
}, [id, toast]);
const handleDelete = async () => {
if (!env) return;
@@ -57,7 +69,11 @@ export function EnvironmentDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('environments.title'), icon: <Globe size={14} />, onClick: () => navigate('/environments') },
{
label: t('environments.title'),
icon: <Globe size={14} />,
onClick: () => navigate('/environments'),
},
{ label: env?.name ?? `#${id}` },
]}
/>
@@ -104,15 +120,26 @@ 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>
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
{dataEntries.length === 0 ? (
<p className={styles.muted}>{t('environments.no_data')}</p>
) : (
<DescriptionList
layout="grid"
items={dataEntries.map(([key, value]) => ({
term: key,
detail: (
<a href={value} target="_blank" rel="noopener noreferrer">
@@ -120,30 +147,21 @@ export function EnvironmentDetailPage() {
</a>
),
}))}
/>
)}
</Card>
/>
)}
</Card>
</div>
</>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('environments.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
message={t('common.confirm_delete_environment')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
@@ -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';
@@ -12,10 +13,10 @@ import {
Card,
ContextMenu,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
@@ -117,10 +118,10 @@ 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);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -129,7 +130,6 @@ export function EnvironmentsPage() {
environments
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -162,8 +162,8 @@ export function EnvironmentsPage() {
const payload = yamlParse(text) as unknown;
const imported = await environments.importEnvironment(payload);
navigate(`/environments/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -196,23 +196,14 @@ export function EnvironmentsPage() {
</div>
)}
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('environments.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('environments.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this environment?
</Modal>
message={t('common.confirm_delete_environment')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+53 -42
View File
@@ -1,9 +1,11 @@
import { useCallback, useEffect, useRef, useState } from 'react';
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,49 +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 [items, setItems] = useState<AllRunRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pulseKey, setPulseKey] = useState(0);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const hasDataRef = useRef(false);
const [sortBy, setSortBy] = useState('createdAt');
const [sortDir, setSortDir] = useState<SortDirection>('desc');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const load = useCallback(() => {
if (!hasDataRef.current) setLoading(true);
runs
.listAll()
.then((res) => {
setItems(res.data as AllRunRow[]);
setError(null);
setPulseKey((k) => k + 1);
hasDataRef.current = true;
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
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,
});
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
pollRef.current = setInterval(load, 10_000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, []);
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}
@@ -90,18 +93,14 @@ 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'),
width: 80,
render: (r) => r.stepRuns.length,
},
{
key: 'created',
key: 'createdAt',
header: t('runs.col_created'),
width: 160,
sortable: true,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
@@ -110,18 +109,30 @@ export function AllRunsPage() {
<div>
<div className={styles.pageToolbar}>
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
<AutoRefreshIndicator active pulseKey={pulseKey} error={!!error} onClick={load} />
<AutoRefreshIndicator
active
pulseKey={items.length}
error={!!error}
onClick={() => refetch()}
/>
</div>
<Table
columns={columns}
data={items}
rowKey={(r) => r.id}
loading={loading}
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>
);
+362 -32
View File
@@ -1,7 +1,8 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
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,24 +11,35 @@ import type {
ScenarioRunStatus,
RunStepStatus,
LogLevel,
FileMetadata,
} from '../../api';
import { scenarios } from '../../api';
import { ExportLogsModal, type LogExportFormat } from '../../components/modals';
import {
AutoRefreshIndicator,
Badge,
Button,
Breadcrumbs,
Card,
CodeBlock,
DescriptionList,
Notification,
Pagination,
Search,
Table,
Timestamp,
UuidBadge,
useToast,
type TableColumn,
} from '../../ui';
import type { BadgeVariant } from '../../ui';
import { ClipboardList, Activity } from 'lucide-react';
import {
ChevronDown,
ChevronRight,
ClipboardList,
Activity,
Download,
RotateCcw,
} from 'lucide-react';
import styles from '../Page.module.css';
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
@@ -62,19 +74,36 @@ 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);
const [logPage, setLogPage] = useState(1);
const [logSearch, setLogSearch] = useState('');
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 [repeating, setRepeating] = useState(false);
const logSearchRef = useRef('');
const LOG_PAGE_SIZE = 25;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
@@ -87,6 +116,51 @@ 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);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${newRun.id}`);
} catch (err) {
toast.error((err as Error).message);
} finally {
setRepeating(false);
}
};
const manualRefresh = () => {
if (!id || !runId) return;
runs
@@ -99,6 +173,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);
@@ -125,6 +215,7 @@ export function RunDetailPage() {
if (cancelled) return;
setScenario(sc);
setRun(r);
loadArtifacts();
if (!FINAL.includes(r.status)) {
setPolling(true);
pollRef.current = setInterval(async () => {
@@ -133,7 +224,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();
}
@@ -151,7 +245,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 },
@@ -171,8 +265,110 @@ export function RunDetailPage() {
},
{
key: 'description',
header: t('runs.step_description'),
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
header: (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
}}
>
<span>{t('runs.step_description')}</span>
{run?.stepRuns.some((s) => s.output) && (
<button
onClick={() => {
if (expandAll) {
setExpandAll(false);
setExpandedStepIds(new Set());
} else {
setExpandAll(true);
setExpandedStepIds(
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
);
}
}}
style={{
background: 'none',
border: 'none',
padding: '0 4px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
color: 'inherit',
}}
title={expandAll ? 'Collapse all' : 'Expand all'}
>
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
</div>
),
render: (s) => {
const isExpanded = expandAll || expandedStepIds.has(s.id);
return (
<div>
<div
style={{
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
marginBottom: isExpanded && s.output ? '8px' : 0,
}}
>
{s.output && (
<button
onClick={() => {
const newSet = new Set(expandedStepIds);
if (newSet.has(s.id)) {
newSet.delete(s.id);
} else {
newSet.add(s.id);
}
setExpandedStepIds(newSet);
}}
style={{
background: 'none',
border: 'none',
padding: 0,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
flexShrink: 0,
marginTop: '2px',
}}
>
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
)}
<code style={{ wordBreak: 'break-word' }}>
{s.description ? (
s.description
) : s.output ? (
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
) : (
<span className={styles.muted}>–</span>
)}
</code>
</div>
{isExpanded && s.output && (
<div style={{ marginLeft: '24px' }}>
<CodeBlock
code={(() => {
try {
return JSON.stringify(JSON.parse(s.output), null, 2);
} catch {
return s.output;
}
})()}
language="json"
/>
</div>
)}
</div>
);
},
},
];
@@ -183,7 +379,11 @@ export function RunDetailPage() {
width: 70,
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
},
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
{
key: 'message',
header: t('runs.log_message'),
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
},
{
key: 'time',
header: t('runs.log_time'),
@@ -197,9 +397,13 @@ export function RunDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: scenario?.name ?? `#${id}`,
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `${id}`,
onClick: () => navigate(`/scenarios/${id}`),
},
{
@@ -207,10 +411,30 @@ export function RunDetailPage() {
icon: <Activity size={14} />,
onClick: () => navigate(`/scenarios/${id}/runs`),
},
{ label: `#${runId}` },
{ 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>}
@@ -220,19 +444,48 @@ export function RunDetailPage() {
<Card>
<DescriptionList
layout="grid"
items={[
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
]}
items={(() => {
const items = [
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
{
term: t('runs.field_status'),
detail: (
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
{RUN_STATUS_LABEL[run.status]}
</Badge>
),
},
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
];
if (run.environment) {
items.push({
term: 'Environment',
detail: (
<Link
to={`/environments/${run.environment.id}`}
style={{ color: 'var(--color-link)' }}
>
{run.environment.name}
</Link>
),
});
}
if (run.session) {
items.push({
term: 'Session',
detail: (
<Link
to={`/sessions/${run.session.id}`}
style={{ color: 'var(--color-link)' }}
>
{run.session.sessionName}
</Link>
),
});
}
return items;
})()}
/>
</Card>
@@ -253,11 +506,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}
@@ -276,8 +535,79 @@ 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>
);
},
},
] satisfies TableColumn<FileMetadata>[]
}
emptyMessage={t('files.empty')}
/>
</div>
)}
</>
)}
<ExportLogsModal
open={exportLogsOpen}
format={exportLogsFormat}
onFormatChange={setExportLogsFormat}
onClose={() => setExportLogsOpen(false)}
onExport={handleExportLogs}
isExporting={exportingLogs}
/>
</div>
);
}
+91 -39
View File
@@ -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,30 +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(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
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)
@@ -102,7 +142,7 @@ export function RunsPage() {
setRunning(true);
try {
const run = await scenarios.run(id!, selectedEnvId);
toast.success('Scenario run started');
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
} catch (err) {
@@ -118,18 +158,14 @@ 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'),
width: 80,
render: (r) => r.stepRuns.length,
},
{
key: 'created',
key: 'createdAt',
header: t('runs.col_created'),
width: 160,
sortable: true,
render: (r) => <Timestamp value={r.createdAt} />,
},
];
@@ -139,7 +175,11 @@ export function RunsPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -148,7 +188,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')}
@@ -162,25 +207,32 @@ 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
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
{t('runs.action_run')}
</Button>
</>
)}
}
>
{envs.length === 0 ? (
<p>{t('scenarios.run_modal_no_env')}</p>
@@ -1,36 +1,50 @@
import { useState } 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);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
useEffect(() => {
environments
.list(1, 200)
.then((r) => setEnvs(r?.data ?? []))
.catch(() => {});
}, []);
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
const scenario = await scenarios.create(name.trim());
toast.success('Scenario created');
const scenario = await scenarios.create(
name.trim(),
description.trim() || undefined,
environmentId || undefined,
);
toast.success(t('scenarios.created'));
navigate(`/scenarios/${scenario.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -42,7 +56,11 @@ export function CreateScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: t('scenarios.create_title') },
]}
/>
@@ -63,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}>
+21 -7
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
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,10 +15,11 @@ 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);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -27,20 +29,19 @@ export function CreateStepPage() {
.catch(() => null);
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
setError(null);
try {
await steps.create(id!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
});
toast.success('Step created');
toast.success(t('steps.created'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -52,7 +53,11 @@ export function CreateStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -75,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}>
+59 -12
View File
@@ -1,10 +1,11 @@
import { useEffect, useState } from 'react';
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,10 +16,16 @@ 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);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -27,26 +34,35 @@ export function EditScenarioPage() {
.then((data) => {
setScenario(data);
setName(data.name);
setDescription(data.description || '');
setEnvironmentId(data.environmentId ?? '');
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
environments
.list(1, 200)
.then((r) => setEnvs(r?.data ?? []))
.catch(() => {});
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) {
setNameError(t('scenarios.form_name_required'));
return;
}
setSaving(true);
setError(null);
try {
await scenarios.update(id!, { name: name.trim() });
toast.success('Scenario updated');
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) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -58,7 +74,11 @@ export function EditScenarioPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
label: scenario?.name ?? `#${id}`,
onClick: () => navigate(`/scenarios/${id}`),
@@ -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}>
+25 -9
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
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,11 +16,14 @@ 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);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id || !stepId) return;
@@ -29,25 +33,24 @@ export function EditStepPage() {
setStep(st);
setTitle(st.title ?? '');
setExecCode(st.execCode ?? '');
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id, stepId]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
setError(null);
try {
await steps.update(id!, stepId!, {
title: title.trim() || undefined,
execCode: execCode.trim() || undefined,
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
});
toast.success('Step updated');
toast.success(t('steps.updated'));
navigate(`/scenarios/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -59,12 +62,16 @@ export function EditStepPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{
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}>
+375 -41
View File
@@ -1,10 +1,36 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState, useCallback, SubmitEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Play, Pencil, Plus, History, Trash2, Upload, GripVertical, ClipboardList } from 'lucide-react';
import { stringify as yamlStringify } from 'yaml';
import { environments, scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
import type { Scenario, ScenarioStep, ScenarioCredential, Credential, Environment } from '../../api';
import { usePageTitle } from '../../hooks/usePageTitle';
import {
Play,
Pencil,
Plus,
History,
Download,
Trash2,
Upload,
GripVertical,
ClipboardList,
FileArchive,
} from 'lucide-react';
import {
environments,
scenarios,
steps,
scenarioCredentials,
scenarioFiles,
credentials as credentialsApi,
} from '../../api';
import type {
Scenario,
ScenarioStep,
ScenarioCredential,
Credential,
Environment,
FileMetadata,
Snippet,
} from '../../api';
import {
Breadcrumbs,
Button,
@@ -16,9 +42,11 @@ import {
Table,
Timestamp,
UuidBadge,
MarkdownContent,
useToast,
type TableColumn,
} from '../../ui';
import { ExportScenarioModal } from '../../components/modals';
import styles from '../Page.module.css';
export function ScenarioDetailPage() {
@@ -28,7 +56,7 @@ export function ScenarioDetailPage() {
const toast = useToast();
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(scenario?.name ?? null);
// Credentials state
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
@@ -44,13 +72,44 @@ export function ScenarioDetailPage() {
const [reorderingSteps, setReorderingSteps] = useState(false);
const [runModalOpen, setRunModalOpen] = useState(false);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
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<Snippet[]>([]);
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
@@ -59,8 +118,12 @@ export function ScenarioDetailPage() {
setScenario(s);
setScenarioCreds(s.scenarioCredentials ?? []);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
void loadFiles();
scenarios
.usedSnippets(id)
.then(setUsedSnippets)
.catch(() => {});
credentialsApi
.list(1, 200)
.then((r) => setAllCredentials(r.data))
@@ -69,16 +132,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 () => {
@@ -89,10 +164,11 @@ export function ScenarioDetailPage() {
}
setRunning(true);
try {
const run = await scenarios.run(scenario.id, selectedEnvId);
toast.success('Scenario run started');
const run = await scenarios.run(scenario.id, selectedEnvId, saveSessionFlag);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${id}/runs/${run.id}`);
setRunModalOpen(false);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
@@ -106,19 +182,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();
@@ -138,7 +265,7 @@ export function ScenarioDetailPage() {
}
};
const handleAddCredential = async (e: React.FormEvent) => {
const handleAddCredential = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!addCredId) {
@@ -231,7 +358,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'),
@@ -319,7 +446,11 @@ export function ScenarioDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('scenarios.title'), icon: <ClipboardList size={14} />, onClick: () => navigate('/scenarios') },
{
label: t('scenarios.title'),
icon: <ClipboardList size={14} />,
onClick: () => navigate('/scenarios'),
},
{ label: scenario?.name ?? `#${id}` },
]}
/>
@@ -333,15 +464,29 @@ 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')}
</Button>
<Button variant="danger" size="sm" onClick={() => setPendingDelete({ type: 'scenario' })}>
<Button
variant="danger"
size="sm"
onClick={() => setPendingDelete({ type: 'scenario' })}
>
<Trash2 size={14} />
{t('scenarios.action_delete')}
</Button>
@@ -359,6 +504,24 @@ export function ScenarioDetailPage() {
items={[
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
{ term: t('scenarios.field_name'), detail: scenario.name },
...(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} />,
@@ -371,6 +534,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}>
@@ -498,6 +672,131 @@ 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<Snippet>
data={usedSnippets}
rowKey={(s) => s.id}
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,
},
] satisfies TableColumn<Snippet>[]
}
/>
</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>
</>
)}
@@ -511,48 +810,83 @@ export function ScenarioDetailPage() {
: t('scenarios.action_delete')
}
onClose={() => !deleting && setPendingDelete(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
Confirm
{t('common.button_confirm')}
</Button>
</>
)}
}
>
{pendingDelete?.type === 'step' && 'Are you sure you want to delete this step?'}
{pendingDelete?.type === 'credential' && 'Are you sure you want to remove this credential from scenario?'}
{pendingDelete?.type === 'scenario' && 'Are you sure you want to delete this scenario?'}
{pendingDelete?.type === 'step' && t('common.confirm_delete_step')}
{pendingDelete?.type === 'credential' && t('common.confirm_remove_credential')}
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
</Modal>
<Modal
open={runModalOpen}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunModalOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
Cancel
{t('common.button_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 }))}
/>
<>
<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>
<ExportScenarioModal
open={exportModalOpen}
scenario={scenario}
scenarioCredentials={scenarioCreds}
environment={
scenario?.environment ?? envs.find((e) => e.id === scenario?.environmentId) ?? null
}
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>
);
}
+128 -35
View File
@@ -1,68 +1,124 @@
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 {
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[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
const [running, setRunning] = useState(false);
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
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: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
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);
}
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);
toast.success('Scenario run started');
const run = await scenarios.run(runScenarioId, selectedEnvId, saveSessionFlag);
toast.success(t('scenarios.run_started'));
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
setRunScenarioId(null);
setSaveSessionFlag(false);
} catch (err) {
toast.error((err as Error).message);
} finally {
@@ -75,8 +131,7 @@ export function ScenariosPage() {
setDeleting(true);
try {
await scenarios.remove(deleteId);
setLoading(true);
load();
load(sortBy, sortDir, page, pageSize);
setDeleteId(null);
} finally {
setDeleting(false);
@@ -92,18 +147,37 @@ export function ScenariosPage() {
const payload = yamlParse(text) as unknown;
const imported = await scenarios.importScenario(payload);
navigate(`/scenarios/${imported.id}`);
} catch (err) {
setError((err as Error).message);
} catch {
// Import errors are silently ignored
}
};
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: '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} />,
},
{
@@ -167,34 +241,41 @@ 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
open={deleteId != null}
title={t('scenarios.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('scenarios.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this scenario?
{t('common.confirm_delete_scenario')}
</Modal>
<Modal
open={runScenarioId != null}
title={t('scenarios.run_modal_title')}
onClose={() => !running && setRunScenarioId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
Cancel
@@ -203,17 +284,29 @@ export function ScenariosPage() {
{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 }))}
/>
<>
<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>
</div>
+15 -28
View File
@@ -1,19 +1,12 @@
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';
import {
Badge,
Breadcrumbs,
Button,
Card,
DescriptionList,
Modal,
Timestamp,
UuidBadge,
} from '../../ui';
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
import styles from '../Page.module.css';
export function SessionDetailPage() {
@@ -22,7 +15,7 @@ export function SessionDetailPage() {
const navigate = useNavigate();
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(session?.sessionName ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -31,7 +24,6 @@ export function SessionDetailPage() {
sessions
.get(id)
.then(setSession)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -52,7 +44,11 @@ export function SessionDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('sessions.title'), icon: <Monitor size={14} />, onClick: () => navigate('/sessions') },
{
label: t('sessions.title'),
icon: <Monitor size={14} />,
onClick: () => navigate('/sessions'),
},
{ label: session?.sessionName ?? `#${id}` },
]}
/>
@@ -102,23 +98,14 @@ export function SessionDetailPage() {
</Card>
)}
<Modal
<DeleteConfirmationModal
open={confirmDeleteOpen}
title={t('sessions.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
message={t('common.confirm_delete_session')}
onClose={() => setConfirmDeleteOpen(false)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+50 -28
View File
@@ -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';
@@ -8,42 +9,56 @@ import {
Badge,
Breadcrumbs,
Button,
Modal,
Table,
type TableColumn,
type SortDirection,
Timestamp,
UuidBadge,
} from '../../ui';
import { DeleteConfirmationModal } from '../../components/modals';
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 [error, setError] = useState<string | null>(null);
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))
.catch((err: Error) => setError(err.message))
.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);
@@ -52,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} /> : '—'),
},
{
@@ -97,28 +119,28 @@ 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}`)}
/>
<Modal
<DeleteConfirmationModal
open={deleteId != null}
title={t('sessions.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('sessions.action_delete')}
</Button>
</>
)}
>
Are you sure you want to delete this session?
</Modal>
message={t('common.confirm_delete_session')}
onClose={() => setDeleteId(null)}
onConfirm={handleDelete}
isDeleting={deleting}
/>
</div>
);
}
+10 -7
View File
@@ -1,6 +1,7 @@
import { useState } from 'react';
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();
@@ -19,9 +21,8 @@ export function CreateSnippetPage() {
const [titleError, setTitleError] = useState('');
const [codeError, setCodeError] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
@@ -38,7 +39,6 @@ export function CreateSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
const snippet = await snippets.create({
alias: alias.trim(),
@@ -46,11 +46,10 @@ export function CreateSnippetPage() {
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet created');
toast.success(t('snippets.created'));
navigate(`/snippets/${snippet.id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -62,7 +61,11 @@ export function CreateSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: t('snippets.create_title') },
]}
/>
+12 -8
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
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('');
@@ -23,7 +27,6 @@ export function EditSnippetPage() {
const [codeError, setCodeError] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -36,11 +39,10 @@ export function EditSnippetPage() {
setDescription(s.description ?? '');
setCode(s.code);
})
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
let valid = true;
if (!alias.trim()) {
@@ -57,7 +59,6 @@ export function EditSnippetPage() {
}
if (!valid) return;
setSaving(true);
setError(null);
try {
await snippets.update(id!, {
alias: alias.trim(),
@@ -65,11 +66,10 @@ export function EditSnippetPage() {
description: description.trim() || undefined,
code: code.trim(),
});
toast.success('Snippet updated');
toast.success(t('snippets.updated'));
navigate(`/snippets/${id}`);
} catch (err) {
const message = (err as Error).message;
setError(message);
toast.error(message);
} finally {
setSaving(false);
@@ -81,7 +81,11 @@ export function EditSnippetPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{
label: snippet?.title ?? `#${id}`,
onClick: () => navigate(`/snippets/${id}`),
+16 -8
View File
@@ -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,7 +25,7 @@ export function SnippetDetailPage() {
const navigate = useNavigate();
const [snippet, setSnippet] = useState<Snippet | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
usePageTitle(snippet?.title ?? null);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -33,7 +34,6 @@ export function SnippetDetailPage() {
snippets
.get(id)
.then(setSnippet)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
@@ -66,7 +66,11 @@ export function SnippetDetailPage() {
<div className={styles.pageToolbar}>
<Breadcrumbs
items={[
{ label: t('snippets.title'), icon: <Braces size={14} />, onClick: () => navigate('/snippets') },
{
label: t('snippets.title'),
icon: <Braces size={14} />,
onClick: () => navigate('/snippets'),
},
{ label: snippet?.title ?? `#${id}` },
]}
/>
@@ -141,18 +145,22 @@ export function SnippetDetailPage() {
open={confirmDeleteOpen}
title={t('snippets.action_delete')}
onClose={() => !deleting && setConfirmDeleteOpen(false)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setConfirmDeleteOpen(false)} disabled={deleting}>
Cancel
<Button
variant="secondary"
onClick={() => setConfirmDeleteOpen(false)}
disabled={deleting}
>
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this snippet?
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
+23 -19
View File
@@ -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';
@@ -17,7 +18,10 @@ import {
} from '../../ui';
import styles from '../Page.module.css';
function firstParagraphBlocks(markdown: string, limit = 2): { preview: string; truncated: boolean } {
function firstParagraphBlocks(
markdown: string,
limit = 2,
): { preview: string; truncated: boolean } {
const blocks = markdown
.split(/\n\s*\n/g)
.map((block) => block.trim())
@@ -81,16 +85,17 @@ function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: s
<p className={styles.muted}>
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
</p>
{snippet.description && (() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
{snippet.description &&
(() => {
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
if (!preview) return null;
return (
<>
<MarkdownContent content={preview} />
{truncated && <p className={styles.muted}>...</p>}
</>
);
})()}
</Card>
);
}
@@ -110,10 +115,10 @@ 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);
const [error, setError] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -122,7 +127,6 @@ export function SnippetsPage() {
snippets
.list()
.then((res) => setItems(res.data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
};
@@ -155,8 +159,8 @@ export function SnippetsPage() {
const payload = yamlParse(text) as unknown;
const imported = await snippets.importSnippet(payload);
navigate(`/snippets/${imported.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} catch {
// Import errors are silently ignored
}
};
@@ -195,18 +199,18 @@ export function SnippetsPage() {
open={deleteId != null}
title={t('snippets.action_delete')}
onClose={() => !deleting && setDeleteId(null)}
footer={(
footer={
<>
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
Cancel
{t('common.button_cancel')}
</Button>
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
{t('snippets.action_delete')}
</Button>
</>
)}
}
>
Are you sure you want to delete this snippet?
{t('common.confirm_delete_snippet')}
</Modal>
</div>
);
+6 -3
View File
@@ -36,15 +36,18 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
<li key={i} className={styles.item}>
{isLast ? (
<span className={styles.current} aria-current="page">
{item.icon}{item.label}
{item.icon}
{item.label}
</span>
) : item.href ? (
<a href={item.href} className={styles.link} onClick={item.onClick}>
{item.icon}{item.label}
{item.icon}
{item.label}
</a>
) : (
<button type="button" className={styles.link} onClick={item.onClick}>
{item.icon}{item.label}
{item.icon}
{item.label}
</button>
)}
{!isLast && <span className={styles.separator}>{sep}</span>}
+29
View File
@@ -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
View File
@@ -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
}
+34 -45
View File
@@ -1,9 +1,8 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import styles from './ToastProvider.module.css';
import { subscribeApiErrorToasts } from '../../lib/toast-events';
type ToastVariant = 'success' | 'error' | 'info';
import { ToastContext, type ToastApi, type ToastVariant } from './toast-context';
interface ToastItem {
id: number;
@@ -12,15 +11,6 @@ interface ToastItem {
closing: boolean;
}
interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
const ToastContext = createContext<ToastApi | null>(null);
const ICONS: Record<ToastVariant, React.ReactNode> = {
success: <CheckCircle2 size={16} />,
error: <AlertCircle size={16} />,
@@ -41,33 +31,38 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
setItems((prev) => prev.filter((item) => item.id !== id));
}, []);
const dismiss = useCallback((id: number) => {
setItems((prev) =>
prev.map((item) =>
item.id === id ? { ...item, closing: true } : item,
),
);
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
}, [remove]);
const dismiss = useCallback(
(id: number) => {
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, closing: true } : item)));
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
},
[remove],
);
const show = useCallback((message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const show = useCallback(
(message: string, variant: ToastVariant = 'info') => {
const now = Date.now();
const dedupeKey = `${variant}:${message}`;
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
if (now - previousTs < 600) return;
lastShownAtRef.current.set(dedupeKey, now);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
}, [dismiss, durationMs]);
const id = Date.now() + Math.floor(Math.random() * 1000);
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
window.setTimeout(() => dismiss(id), durationMs);
},
[dismiss, durationMs],
);
const api = useMemo<ToastApi>(() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}), [show]);
const api = useMemo<ToastApi>(
() => ({
show,
success: (message: string) => show(message, 'success'),
error: (message: string) => show(message, 'error'),
info: (message: string) => show(message, 'info'),
}),
[show],
);
useEffect(() => {
return subscribeApiErrorToasts((message) => api.error(message));
@@ -86,7 +81,9 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
role="status"
>
<div className={styles.content}>
<span className={styles.icon} aria-hidden="true">{ICONS[item.variant]}</span>
<span className={styles.icon} aria-hidden="true">
{ICONS[item.variant]}
</span>
<p className={styles.message}>{item.message}</p>
</div>
<button
@@ -103,11 +100,3 @@ export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProp
</ToastContext.Provider>
);
}
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
+12
View File
@@ -0,0 +1,12 @@
import { createContext } from 'react';
export type ToastVariant = 'success' | 'error' | 'info';
export interface ToastApi {
show: (message: string, variant?: ToastVariant) => void;
success: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
}
export const ToastContext = createContext<ToastApi | null>(null);
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { ToastContext, type ToastApi } from './toast-context';
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) {
throw new Error('useToast must be used within ToastProvider');
}
return ctx;
}
+3 -2
View File
@@ -27,8 +27,9 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { ToastProvider, useToast } from './Toast/ToastProvider';
export { ToastProvider } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider';
export { useToast } from './Toast/useToast';
export { Timestamp } from './Timestamp/Timestamp';
export type { TimestampProps } from './Timestamp/Timestamp';
@@ -61,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';
-1
View File
@@ -1 +0,0 @@
{"root":["./src/App.tsx","./src/declarations.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/index.ts","./src/api/types.ts","./src/hooks/useTheme.ts","./src/i18n/index.ts","./src/lib/hljs.ts","./src/lib/toast-events.ts","./src/pages/credential/CreateCredentialPage.tsx","./src/pages/credential/CredentialDetailPage.tsx","./src/pages/credential/CredentialsPage.tsx","./src/pages/credential/EditCredentialPage.tsx","./src/pages/environment/CreateEnvironmentPage.tsx","./src/pages/environment/EditEnvironmentPage.tsx","./src/pages/environment/EnvironmentDetailPage.tsx","./src/pages/environment/EnvironmentsPage.tsx","./src/pages/run/AllRunsPage.tsx","./src/pages/run/RunDetailPage.tsx","./src/pages/run/RunsPage.tsx","./src/pages/scenario/CreateScenarioPage.tsx","./src/pages/scenario/CreateStepPage.tsx","./src/pages/scenario/EditScenarioPage.tsx","./src/pages/scenario/EditStepPage.tsx","./src/pages/scenario/ScenarioDetailPage.tsx","./src/pages/scenario/ScenariosPage.tsx","./src/pages/session/SessionDetailPage.tsx","./src/pages/session/SessionsPage.tsx","./src/pages/snippet/CreateSnippetPage.tsx","./src/pages/snippet/EditSnippetPage.tsx","./src/pages/snippet/SnippetDetailPage.tsx","./src/pages/snippet/SnippetsPage.tsx","./src/ui/index.ts","./src/ui/AutoRefreshIndicator/AutoRefreshIndicator.tsx","./src/ui/Badge/Badge.tsx","./src/ui/Breadcrumbs/Breadcrumbs.tsx","./src/ui/Button/Button.tsx","./src/ui/Card/Card.tsx","./src/ui/CodeBlock/CodeBlock.tsx","./src/ui/CodeEditor/CodeEditor.tsx","./src/ui/ContextMenu/ContextMenu.tsx","./src/ui/DescriptionList/DescriptionList.tsx","./src/ui/Input/Input.tsx","./src/ui/MarkdownContent/MarkdownContent.tsx","./src/ui/Modal/Modal.tsx","./src/ui/Notification/Notification.tsx","./src/ui/Pagination/Pagination.tsx","./src/ui/Search/Search.tsx","./src/ui/Select/Select.tsx","./src/ui/SidePanel/SidePanel.tsx","./src/ui/Table/Table.tsx","./src/ui/Textarea/Textarea.tsx","./src/ui/ThemeSwitcher/ThemeSwitcher.tsx","./src/ui/Timestamp/Timestamp.tsx","./src/ui/Toast/ToastProvider.tsx","./src/ui/UuidBadge/UuidBadge.tsx"],"version":"5.8.3"}
+23 -1
View File
@@ -28,7 +28,7 @@ The server currently registers the following tools.
| Tool | Description |
|---|---|
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
| `exec_code` | Execute Playwright JS with `page` and `context` in scope |
| `exec_code` | Execute Playwright JS — script receives a single `context` argument (see `scenario.md`). Optional `environmentId` (UUID) resolves environment from DB for `context.getEnv()`. Optional `credentials` (`{ alias: credentialUUID }`) resolves credentials from DB for `context.getCredential(alias)`. |
## Scenarios
@@ -50,7 +50,29 @@ The server currently registers the following tools.
| `export_scenario` | Export scenario payload |
| `import_scenario` | Import scenario payload |
## 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 artifacts are read-only and inherit expiry from the run artifact subsystem |
## 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.
+22 -15
View File
@@ -17,24 +17,31 @@ Current scheduler behavior is exec-centric:
## Script runtime
`execCode` and `validateCode` execute as async JavaScript with:
`execCode` and `validateCode` execute as async JavaScript with a single `context` argument:
- `page`: Playwright `Page`
- `context`: Playwright `BrowserContext`
- `helpers`: utility object
```js
async (context) => {
// your code here
}
```
Available in scope:
- `context.page`: Playwright `Page`
- `context.browser`: Playwright `BrowserContext`
- `context.env`: shallow copy of environment key/value map
- `context.getEnv(key)`: required environment value lookup (throws if missing)
- `context.getCredential(alias)`: credential payload assigned to the scenario alias
- `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.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
- `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`, which is the value returned by `execCode`.
## Available helpers
- `helpers.dumpDom(selector?)`: simplified DOM snapshot
- `helpers.log(...args)`, `helpers.warn(...args)`, `helpers.error(...args)`: structured step logs
- `helpers.getStepOutput(order)`: prior step output by absolute order (`0`, `1`, ...) or relative (`-1` previous step)
- `helpers.getCredential(alias)`: credential payload assigned to the scenario alias
- `helpers.env`: shallow copy of environment URL map
- `helpers.getEnvUrl(key)`: required environment URL lookup (throws if missing)
- `helpers.runSnippet(name, ...args)`: execute stored snippet code in the same page/context/helpers scope
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
## Validation contract
+741 -7
View File
@@ -1,12 +1,12 @@
{
"name": "liqa",
"version": "1.5.0",
"version": "1.14.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "liqa",
"version": "1.5.0",
"version": "1.14.0",
"workspaces": [
"server",
"client"
@@ -16,6 +16,7 @@
"name": "liqa-client",
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.99.0",
"highlight.js": "^11.11.1",
"i18next": "^26.0.4",
"lucide-react": "^1.7.0",
@@ -3978,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": {
@@ -4202,6 +4202,30 @@
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/@tanstack/query-core": {
"version": "5.99.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.99.0.tgz",
"integrity": "sha512-3Jv3WQG0BCcH7G+7lf/bP8QyBfJOXeY+T08Rin3GZ1bshvwlbPt7NrDHMEzGdKIOmOzvIQmxjk28YEQX60k7pQ==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.99.0",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.99.0.tgz",
"integrity": "sha512-OY2bCqPemT1LlqJ8Y2CUau4KELnIhhG9Ol3ZndPbdnB095pRbPo1cHuXTndg8iIwtoHTgwZjyaDnQ0xD0mYwAw==",
"dependencies": {
"@tanstack/query-core": "5.99.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
@@ -4641,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",
@@ -5541,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",
@@ -5736,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",
@@ -5818,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",
@@ -5850,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",
@@ -5965,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",
@@ -6157,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",
@@ -6656,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",
@@ -6741,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",
@@ -6785,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",
@@ -7194,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",
@@ -7917,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",
@@ -8093,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",
@@ -8106,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",
@@ -8649,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": {
@@ -9264,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"
@@ -10451,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",
@@ -11939,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"
@@ -12565,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",
@@ -12867,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",
@@ -13741,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",
@@ -14068,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",
@@ -14203,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",
@@ -15902,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",
@@ -15959,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",
@@ -15975,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",
@@ -15994,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
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.5.0",
"version": "1.14.0",
"private": true,
"workspaces": [
"server",
+1 -1
View File
@@ -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
+3
View File
@@ -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",
+19 -11
View File
@@ -1,23 +1,27 @@
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { AppConfig, validateAppConfig } from "./config/app.config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ScheduleModule } from "@nestjs/schedule";
import { HealthModule } from "./health/health.module";
import { TypeOrmModule } from "@nestjs/typeorm";
import { BrowserModule } from "./browser/browser.module";
import { SessionEntity } from "./session/session.entity";
import { EnvironmentEntity } from "./environment/environment.entity";
import { EnvironmentModule } from "./environment/environment.module";
import { AppConfig, validateAppConfig } from "./config/app.config";
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 { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
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 { ScenarioEntity } from "./scenario/scenario.entity";
import { ScenarioModule } from "./scenario/scenario.module";
import { SessionEntity } from "./session/session.entity";
import { SnippetEntity } from "./snippet/snippet.entity";
import { SnippetModule } from "./snippet/snippet.module";
@@ -45,6 +49,9 @@ import { SnippetModule } from "./snippet/snippet.module";
ScenarioRunLogEntity,
ScenarioCredentialEntity,
SnippetEntity,
FileEntity,
ScenarioFileEntity,
ScenarioRunFileEntity,
],
synchronize: true,
}),
@@ -54,6 +61,7 @@ import { SnippetModule } from "./snippet/snippet.module";
CredentialModule,
ScenarioModule,
SnippetModule,
FileModule,
McpModule,
HealthModule,
],
+32 -4
View File
@@ -1,9 +1,11 @@
import { Body, Controller, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { OpenDto } from "./dto/open.dto";
import { CredentialService } from "../credential/credential.service";
import { EnvironmentService } from "../environment/environment.service";
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
import { ExecDto } from "./dto/exec.dto";
import { OpenDto } from "./dto/open.dto";
@ApiTags("browser")
@Controller()
@@ -11,6 +13,8 @@ export class BrowserController {
constructor(
private readonly browserService: BrowserService,
private readonly codeExecutor: CodeExecutorService,
private readonly environmentService: EnvironmentService,
private readonly credentialService: CredentialService,
) {}
@Post("open")
@@ -54,8 +58,32 @@ export class BrowserController {
@ApiResponse({ status: 400, description: "Invalid input" })
@ApiResponse({ status: 404, description: "Session not found" })
@ApiResponse({ status: 500, description: "Execution failed" })
exec(@Body() dto: ExecDto): Promise<ExecResult> {
async exec(@Body() dto: ExecDto): Promise<ExecResult> {
this.codeExecutor.validate(dto.code);
return this.browserService.exec(dto.sessionName, dto.code, dto.url);
// Resolve environment from DB
let environment: Record<string, string | undefined> | undefined;
if (dto.environmentId) {
const env = await this.environmentService.findOne(dto.environmentId);
environment = env.data;
}
// Resolve credentials from DB (alias → payload)
let credentials: Record<string, unknown> | undefined;
if (dto.credentials && Object.keys(dto.credentials).length > 0) {
credentials = {};
for (const [alias, credId] of Object.entries(dto.credentials)) {
const cred = await this.credentialService.findOne(credId);
credentials[alias] = cred.data ? JSON.parse(cred.data) : {};
}
}
return this.browserService.exec(
dto.sessionName,
dto.code,
dto.url,
environment,
credentials,
);
}
}
+12 -3
View File
@@ -1,11 +1,20 @@
import { Module } from "@nestjs/common";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
import { CredentialModule } from "../credential/credential.module";
import { EnvironmentModule } from "../environment/environment.module";
import { SessionModule } from "../session/session.module";
import { SnippetModule } from "../snippet/snippet.module";
import { BrowserController } from "./browser.controller";
import { BrowserService } from "./browser.service";
import { SessionModule } from "../session/session.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
@Module({
imports: [SessionModule, CodeExecutorModule],
imports: [
SessionModule,
CodeExecutorModule,
SnippetModule,
EnvironmentModule,
CredentialModule,
],
controllers: [BrowserController],
providers: [BrowserService],
exports: [BrowserService],
+50 -14
View File
@@ -1,18 +1,22 @@
import { Readability } from "@mozilla/readability";
import {
Injectable,
HttpException,
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { chromium } from "playwright";
import type { BrowserContext } from "playwright";
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import type { BrowserContext, Cookie } from "playwright";
import { chromium } from "playwright";
import type {
ExecResult,
ScriptLogger,
} from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { TraceLogger } from "../common/trace-logger";
import type { EnvironmentData } from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import type { ExecResult } from "../code-executor/code-executor.service";
import type { Cookie } from "playwright";
import { SnippetService } from "../snippet/snippet.service";
export type { ExecResult } from "../code-executor/code-executor.service";
@@ -30,6 +34,7 @@ export class BrowserService {
private readonly sessionContextService: SessionContextService,
private readonly sessionService: SessionService,
private readonly codeExecutor: CodeExecutorService,
private readonly snippetService: SnippetService,
) {}
private parseCookies(raw: string | null | undefined): Cookie[] {
@@ -164,20 +169,34 @@ export class BrowserService {
sessionName: string | undefined,
code: string,
url?: string,
environment?: EnvironmentData,
credentials?: Record<string, unknown>,
): Promise<ExecResult> {
const label = sessionName ?? "anonymous";
if (sessionName) {
const { page, context } =
await this.getOrCreateNamedHandle(sessionName);
const { page, context } = await this.getOrCreateNamedHandle(sessionName);
this.logger.log(`[${label}] exec: using persistent context`);
const snippets = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
try {
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
await page.goto(url, { waitUntil: "networkidle" });
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: context,
code,
log: scriptLogger,
credentials,
environment,
snippets,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
@@ -186,13 +205,20 @@ export class BrowserService {
}
// Anonymous — ephemeral browser
const snippetMap = await this.snippetService
.buildSnippetMap()
.catch(() => ({}) as Record<string, string>);
// TODO: instantiate one browser per server instance and reuse contexts for anonymous sessions,
// instead of launching a new browser for each request.
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
const browserContext = await browser.newContext();
const page = await browserContext.newPage();
if (url) {
this.logger.log(`[${label}] exec: navigating to ${url}`);
@@ -200,7 +226,17 @@ export class BrowserService {
}
this.logger.log(`[${label}] exec: running user code`);
const result = await this.codeExecutor.execute(page, context, code);
const scriptLogger: ScriptLogger = (level, msg) =>
this.logger[level](`[${label}] script: ${msg}`);
const result = await this.codeExecutor.execute({
page,
browser: browserContext,
code,
log: scriptLogger,
credentials,
environment,
snippets: snippetMap,
});
this.logger.log(`[${label}] exec: done`);
return result;
} catch (err) {
+21 -3
View File
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsUrl } from "class-validator";
import { IsObject, IsOptional, IsString, IsUUID, IsUrl } from "class-validator";
export class ExecDto {
@ApiPropertyOptional({
@@ -22,9 +22,27 @@ export class ExecDto {
@ApiProperty({
description:
"JavaScript code to execute. Receives `page` (Playwright Page) and `context` (BrowserContext) as arguments. May be async. Return value is serialised and returned.",
example: "return await page.title();",
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
example: "return await context.page.title();",
})
@IsString()
code: string;
@ApiPropertyOptional({
description:
"UUID of an existing environment entity. Its key/value data is available via `context.env` and `context.getEnv()` in the script.",
example: "a6a1fca5-0f61-48ed-ae97-011dc7236387",
})
@IsOptional()
@IsUUID()
environmentId?: string;
@ApiPropertyOptional({
description:
"Map of alias → credential UUID. Each credential is loaded from the DB and available via `context.getCredential(alias)` in the script.",
example: { pkcs_key: "e3b0c442-98fc-11d8-9669-0800200c9a66" },
})
@IsOptional()
@IsObject()
credentials?: Record<string, string>;
}
+207 -48
View File
@@ -3,12 +3,16 @@ import {
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import { expect as playwrightExpect } from "@playwright/test";
import { dumpDom } from "./dom-helpers";
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";
export interface ExecResult {
result: unknown;
@@ -19,6 +23,63 @@ export type ScriptLogger = (
message: string,
) => void;
/** The `context` object available inside user scripts as the sole argument. */
export interface ScriptContext {
/** Playwright Page for the current session. */
page: Page;
/** Playwright BrowserContext for the current session. */
browser: BrowserContext;
/** All environment values for the current run (empty object if none set). */
env: Record<string, string | undefined>;
/** Returns the environment value for `key`, or throws if not defined. */
getEnv: (key: string) => string;
/** Returns the credential value for `alias`, or throws if not found. */
getCredential: (alias: string) => unknown;
/** Returns the serialised output of a previous step by order index (negative = relative). */
getStepOutput: (order: number) => Promise<unknown>;
/** Dumps the DOM of the current page, optionally scoped to a CSS selector. */
dumpDom: (selector?: string) => Promise<DomNode>;
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 {
page: Page;
browser: BrowserContext;
code: string;
log?: ScriptLogger;
getStepOutput?: (order: number) => Promise<unknown>;
credentials?: Record<string, unknown>;
environment?: EnvironmentData | null;
snippets?: Record<string, string> | null;
result?: unknown;
scenarioId?: string;
runId?: string;
fileService?: FileStorageService;
}
@Injectable()
export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name);
@@ -28,7 +89,7 @@ export class CodeExecutorService {
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
const wrapped = `async function __validate__(context) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
@@ -40,20 +101,25 @@ export class CodeExecutorService {
}
/**
* Executes `code` as an async function body with `page` and `context` in
* scope. Always call `validate()` before this method.
* Executes `code` as an async function body with a single `context` argument
* that exposes page, browser, env helpers, credentials, snippets, and logging.
* Always call `validate()` before this method.
*/
async execute(
page: Page,
context: BrowserContext,
code: string,
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
credentials?: Record<string, unknown>,
environment?: EnvironmentData | null,
snippets?: Record<string, string> | null,
result?: unknown,
): Promise<ExecResult> {
async execute(ctx: ExecContext): Promise<ExecResult> {
const {
page,
browser,
code,
log,
getStepOutput,
credentials,
environment,
snippets,
result,
scenarioId,
runId,
fileService,
} = ctx;
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
const toStr = (args: unknown[]) =>
@@ -65,9 +131,8 @@ export class CodeExecutorService {
const envData: EnvironmentData = environment ?? {};
const snippetMap: Record<string, string> = snippets ?? {};
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
let pageHelpers: Record<string, unknown>;
// scriptContext is referenced by runSnippet, so we declare it first.
let scriptContext: ScriptContext;
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
@@ -78,11 +143,35 @@ export class CodeExecutorService {
};
try {
pageHelpers = {
scriptContext = {
page,
browser,
dumpDom: (selector?: string) => dumpDom(page, selector),
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)) {
@@ -92,10 +181,8 @@ export class CodeExecutorService {
}
return credMap[alias];
},
/** All values defined for the current environment (may be empty if no environment is set). */
env: { ...envData },
/** Returns the value for the given key, or throws if it is not defined. */
getEnvUrl: (key: string): string => {
getEnv: (key: string): string => {
const value = envData[key];
if (value == null) {
throw new Error(
@@ -104,12 +191,6 @@ export class CodeExecutorService {
}
return value;
},
/**
* Runs a snippet by alias. Snippets receive the same page/context/helpers
* as regular exec code, plus any positional args you pass.
*
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
*/
runSnippet: async (
alias: string,
...args: unknown[]
@@ -118,41 +199,97 @@ export class CodeExecutorService {
if (snippetCode == null) {
throw new Error(`Snippet alias "${alias}" not found`);
}
scriptLog("log", `Snippet "${alias}" started`);
const snippetFn = new Function(
"page",
"context",
"helpers",
"console",
"snippetArgs",
"expect",
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
);
return snippetFn(
page,
context,
pageHelpers,
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),
};
},
};
// Passing `console` and `expect` as named parameters exposes them in script scope.
// `console`, `result`, and `expect` are injected as named parameters so
// existing scripts that reference them directly still work.
const fn = new Function(
"page",
"context",
"helpers",
"console",
"result",
"expect",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
`return (async (context) => { ${code} })(context)`,
);
this.logger.debug("Executing user code");
const execResult = await fn(
page,
context,
pageHelpers,
scriptContext,
fakeConsole,
result,
playwrightExpect,
@@ -165,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";
}
}
@@ -0,0 +1,77 @@
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 {
private readonly ctx: Partial<ExecContext> = {};
page(page: Page): this {
this.ctx.page = page;
return this;
}
browser(browser: BrowserContext): this {
this.ctx.browser = browser;
return this;
}
code(code: string): this {
this.ctx.code = code;
return this;
}
log(log: ScriptLogger): this {
this.ctx.log = log;
return this;
}
getStepOutput(fn: (order: number) => Promise<unknown>): this {
this.ctx.getStepOutput = fn;
return this;
}
credentials(credentials: Record<string, unknown>): this {
this.ctx.credentials = credentials;
return this;
}
environment(environment: EnvironmentData | null): this {
this.ctx.environment = environment;
return this;
}
snippets(snippets: Record<string, string> | null): this {
this.ctx.snippets = snippets;
return this;
}
result(result: unknown): this {
this.ctx.result = result;
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)
throw new Error("ExecContextBuilder: browser is required");
if (this.ctx.code === undefined)
throw new Error("ExecContextBuilder: code is required");
return this.ctx as ExecContext;
}
}
+93
View File
@@ -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();
});
}
+34
View File
@@ -0,0 +1,34 @@
/** 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;
}
+11 -2
View File
@@ -1,6 +1,5 @@
import { IsInt, IsString, Min, Max } from "class-validator";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import { IsInt, IsString, Max, Min, validateSync } from "class-validator";
import pkg from "../../package.json";
@@ -32,6 +31,16 @@ 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 * * *";
}
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
@@ -11,12 +11,11 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { CredentialQueryDto } from "./dto/credential-query.dto";
import { CredentialService } from "./credential.service";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { CredentialOrderBy } from "./credential.service";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
@ApiTags("credentials")
@Controller("credentials")
@@ -40,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);
}
+2 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { CredentialController } from "./credential.controller";
import { CredentialEntity } from "./credential.entity";
import { CredentialService } from "./credential.service";
import { CredentialController } from "./credential.controller";
@Module({
imports: [TypeOrmModule.forFeature([CredentialEntity])],
+5 -5
View File
@@ -1,14 +1,14 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CredentialEntity } from "./credential.entity";
import { CreateCredentialDto } from "./dto/create-credential.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
import { CredentialExportDto } from "./dto/credential-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
} from "../common/dto/pagination.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
export type CredentialOrderBy =
| "id"
@@ -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,12 +11,11 @@ import {
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { EnvironmentService } from "./environment.service";
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { PaginationQueryDto } from "../common/dto/pagination.dto";
import { EnvironmentOrderBy } from "./environment.service";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentService } from "./environment.service";
@ApiTags("environments")
@Controller("environments")
@@ -41,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);
}
+5 -2
View File
@@ -1,8 +1,8 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
@@ -18,6 +18,9 @@ export class EnvironmentEntity {
@Column({ unique: true })
name: string;
@Column("text", { nullable: true })
description: string | null;
@Column("simple-json")
data: EnvironmentData;
+1 -1
View File
@@ -1,8 +1,8 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { EnvironmentController } from "./environment.controller";
import { EnvironmentEntity } from "./environment.entity";
import { EnvironmentService } from "./environment.service";
import { EnvironmentController } from "./environment.controller";
@Module({
imports: [TypeOrmModule.forFeature([EnvironmentEntity])],
+31 -10
View File
@@ -5,14 +5,14 @@ import {
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { EnvironmentEntity } from "./environment.entity";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import {
PaginationQueryDto,
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentEntity } from "./environment.entity";
export type EnvironmentOrderBy = "id" | "name" | "createdAt" | "updatedAt";
@@ -71,26 +71,47 @@ export class EnvironmentService {
kind: "environment",
id: env.id,
name: env.name,
description: env.description ?? undefined,
data: env.data,
};
}
async importEnvironment(dto: EnvironmentExportDto): Promise<EnvironmentEntity> {
async importEnvironment(
dto: EnvironmentExportDto,
): Promise<EnvironmentEntity> {
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,
}),
);
}
}
+281
View File
@@ -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),
};
}
}
+28
View File
@@ -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;
}
+13
View File
@@ -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 {}
+33
View File
@@ -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;
}
+1 -1
View File
@@ -6,8 +6,8 @@ import {
HttpException,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import type { Request, Response } from "express";
import { TraceLogger } from "../common/trace-logger";
@Catch(BadRequestException, InternalServerErrorException)
export class HttpExceptionFilter implements ExceptionFilter {
@@ -4,9 +4,9 @@ import {
Injectable,
NestInterceptor,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import type { Request, Response } from "express";
import { Observable, tap } from "rxjs";
import { TraceLogger } from "../common/trace-logger";
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
+1 -1
View File
@@ -4,8 +4,8 @@ import {
Injectable,
NestInterceptor,
} from "@nestjs/common";
import type { Request } from "express";
import * as crypto from "crypto";
import type { Request } from "express";
import { Observable } from "rxjs";
import { traceStorage } from "../common/trace-context";
+24 -12
View File
@@ -1,14 +1,29 @@
import { NestFactory } from "@nestjs/core";
import { ConfigService } from "@nestjs/config";
import { AppConfig } from "./config/app.config";
import { RequestMethod, ValidationPipe } from "@nestjs/common";
import { TraceLogger } from "./common/trace-logger";
import { ConfigService } from "@nestjs/config";
import { NestFactory } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "./app.module";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { TraceInterceptor } from "./interceptors/trace.interceptor";
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
import { name as pkgName, version as pkgVersion } from "../package.json";
import { AppModule } from "./app.module";
import { TraceLogger } from "./common/trace-logger";
import { AppConfig } from "./config/app.config";
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";
@@ -34,10 +49,7 @@ async function bootstrap() {
const nodeEnv = config.get("NODE_ENV");
app.enableCors({
origin: [
"http://localhost:5173",
"http://127.0.0.1:5173",
],
origin: ["http://localhost:5173", "http://127.0.0.1:5173"],
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
credentials: true,
});
+8 -4
View File
@@ -1,19 +1,23 @@
import { Module } from "@nestjs/common";
import { McpController } from "./mcp.controller";
import { McpService } from "./mcp.service";
import { SessionModule } from "../session/session.module";
import { EnvironmentModule } from "../environment/environment.module";
import { BrowserModule } from "../browser/browser.module";
import { CodeExecutorModule } from "../code-executor/code-executor.module";
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";
@Module({
imports: [
SessionModule,
EnvironmentModule,
CredentialModule,
BrowserModule,
CodeExecutorModule,
ScenarioModule,
SnippetModule,
],
controllers: [McpController],
providers: [McpService],
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,11 @@
import { IsNotEmpty, IsUUID } from "class-validator";
import { IsBoolean, IsNotEmpty, IsOptional, IsUUID } from "class-validator";
export class CreateScenarioRunDto {
@IsUUID()
@IsNotEmpty()
environmentId: string;
@IsBoolean()
@IsOptional()
saveSession?: boolean;
}
@@ -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" })
@@ -13,4 +13,9 @@ export class CreateScenarioStepDto {
@IsNotEmpty()
execCode?: string;
@ApiPropertyOptional({ description: "Step timeout in seconds (default: 60)" })
@IsOptional()
@IsInt()
@Min(1)
timeoutSeconds?: number;
}
+18 -2
View File
@@ -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;
}
+9 -14
View File
@@ -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"],
@@ -4,11 +4,13 @@ import {
IsArray,
IsIn,
IsNotEmpty,
IsObject,
IsOptional,
IsString,
IsUUID,
ValidateNested,
} from "class-validator";
import { EnvironmentData } from "../../environment/environment.entity";
export class ScenarioStepExportDto {
@ApiPropertyOptional()
@@ -22,7 +24,65 @@ export class ScenarioStepExportDto {
@IsString()
@IsNotEmpty()
execCode: string | 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 {
@@ -47,9 +107,32 @@ export class ScenarioExportDto {
@IsNotEmpty()
name: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
description?: string;
@ApiPropertyOptional()
@IsOptional()
@IsUUID()
environmentId?: string;
@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;
@@ -19,4 +19,9 @@ export class UpdateScenarioStepDto {
@IsNotEmpty()
execCode?: string;
@ApiPropertyOptional({ description: "Step timeout in seconds (null to use default of 60)" })
@IsOptional()
@IsInt()
@Min(1)
timeoutSeconds?: number | null;
}
+17 -1
View File
@@ -1,5 +1,5 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsNotEmpty } 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;
}
+473
View File
@@ -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();
});
}
}
@@ -1,14 +1,14 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
Unique,
} from "typeorm";
import { ScenarioEntity } from "./scenario.entity";
import { CredentialEntity } from "../credential/credential.entity";
import { ScenarioEntity } from "./scenario.entity";
@Entity("scenario_credentials")
@Unique(["scenarioId", "alias"])
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more