diff --git a/.DS_Store b/.DS_Store
deleted file mode 100644
index 25df859..0000000
Binary files a/.DS_Store and /dev/null differ
diff --git a/.dockerignore b/.dockerignore
index 4609ae1..09dc6ca 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -2,8 +2,10 @@
.run
.cursor
**/node_modules
+**/.env
backend/bin
backend/web/dist
+backend/web/public/downloads/*.zip
backend/dev-console/dist
frontend/dist
**/*_test.go
diff --git a/.gitignore b/.gitignore
index 1fdb34d..eae3dac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,10 @@
# --- secrets / env ---
deploy/.env
deploy/.env.dev
+deploy/.env.prod
infra/.env
*.env
+**/.env
!.env.example
!*.env.example
@@ -16,6 +18,7 @@ backend/web/dist/
backend/dev-console/dist/
frontend/dist/
dist/
+backend/web/public/downloads/*.zip
# --- dependencies ---
node_modules/
diff --git a/AGENTS.md b/AGENTS.md
index 76d5958..8cdad13 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -22,6 +22,7 @@
## 設計文件
- `docs/job-system-plan.md`:通用 job system 規劃,包含 template、run、schedule、Redis queue/lock、取消語意與 API 草案。
+- `docs/post-project-plan.md`:發文計畫(文案任務 Flow A 砍掉重做)— 主題發想、風格分析、矩陣產 N 篇草稿、定時發送。
- `docs/scan-placement-plan.md`:海巡獲客(流程 B)— 知識圖譜、Brave 擴展、雙軌爬取(7 天重點 / 30 天補充)、產品匹配、島民交接。
## 新增 API 流程
diff --git a/Makefile b/Makefile
index f677a7e..c81c64b 100644
--- a/Makefile
+++ b/Makefile
@@ -2,6 +2,12 @@ SHELL := /bin/bash
BACKEND_DIR := backend
WEB_DIR := backend/web
+INFRA_DIR := infra
+DEPLOY_DIR := deploy
+
+INFRA_DEV_COMPOSE := docker compose --env-file $(DEPLOY_DIR)/.env.dev -f $(INFRA_DIR)/docker-compose.yml
+INFRA_PROD_COMPOSE := docker compose --env-file $(DEPLOY_DIR)/.env.prod -f $(INFRA_DIR)/docker-compose.yml
+DEPLOY_COMPOSE := docker compose --env-file $(DEPLOY_DIR)/.env.prod -f $(DEPLOY_DIR)/docker-compose.yml
.DEFAULT_GOAL := help
@@ -26,6 +32,14 @@ test: ## 執行後端測試
run: ## 啟動後端 API
$(MAKE) -C $(BACKEND_DIR) run
+.PHONY: dev-all
+dev-all: ## 啟動本機完整 dev stack(API、Go workers、Node workers、web)
+ ./scripts/dev-all.sh
+
+.PHONY: dev-all-stop
+dev-all-stop: ## 停止本機 dev stack(釋放 8890 / 9101 / 9102 / web 等埠)
+ ./scripts/dev-all-stop.sh
+
.PHONY: web-dev
web-dev: ## 啟動正式前端 dev server
cd $(WEB_DIR) && npm install && npm run dev
@@ -36,3 +50,42 @@ web-build: ## 建置正式前端
.PHONY: verify
verify: test web-build ## 後端測試與前端建置
+
+.PHONY: dev-infra
+dev-infra: ## 啟動本機 dev 資料服務(Mongo / Redis 容器,讀 deploy/.env.dev)
+ @test -f $(DEPLOY_DIR)/.env.dev || cp $(DEPLOY_DIR)/.env.dev.example $(DEPLOY_DIR)/.env.dev
+ @echo ">>> 請先編輯 $(DEPLOY_DIR)/.env.dev 再執行後續指令" >&2
+ $(INFRA_DEV_COMPOSE) up -d
+ $(INFRA_DEV_COMPOSE) ps
+
+.PHONY: dev-infra-down
+dev-infra-down: ## 關閉本機 dev 資料服務(保留資料 volume)
+ $(INFRA_DEV_COMPOSE) down
+
+.PHONY: prod-install
+prod-install: ## 一鍵安裝 prod:複製 .env.prod、啟動 infra、init、啟動 app
+ @test -f $(DEPLOY_DIR)/.env.prod || cp $(DEPLOY_DIR)/.env.prod.example $(DEPLOY_DIR)/.env.prod
+ @echo ">>> 請先編輯 $(DEPLOY_DIR)/.env.prod 再執行後續指令" >&2
+ $(INFRA_PROD_COMPOSE) up -d
+ $(INFRA_PROD_COMPOSE) ps
+ $(DEPLOY_COMPOSE) pull
+ $(DEPLOY_COMPOSE) up -d
+ $(DEPLOY_COMPOSE) --profile init run --rm init
+ $(DEPLOY_COMPOSE) ps
+
+.PHONY: prod-rebuild
+prod-rebuild: ## 重新拉取 image 並重建 prod stack(infra + app)
+ $(INFRA_PROD_COMPOSE) pull
+ $(INFRA_PROD_COMPOSE) up -d
+ $(DEPLOY_COMPOSE) pull
+ $(DEPLOY_COMPOSE) up -d
+ $(DEPLOY_COMPOSE) ps
+
+.PHONY: prod-stop
+prod-stop: ## 關閉 prod app stack(保留 infra 與資料)
+ $(DEPLOY_COMPOSE) down
+
+.PHONY: prod-stop-all
+prod-stop-all: ## 關閉 prod app + infra(保留資料 volume)
+ $(DEPLOY_COMPOSE) down
+ $(INFRA_PROD_COMPOSE) down
diff --git a/backend/.DS_Store b/backend/.DS_Store
deleted file mode 100644
index 3397521..0000000
Binary files a/backend/.DS_Store and /dev/null differ
diff --git a/backend/Dockerfile b/backend/Dockerfile
new file mode 100644
index 0000000..883b3ab
--- /dev/null
+++ b/backend/Dockerfile
@@ -0,0 +1,24 @@
+FROM golang:1.24-alpine AS build
+
+WORKDIR /src
+RUN apk add --no-cache ca-certificates git
+COPY backend/go.mod backend/go.sum ./
+RUN go mod download
+COPY backend/ ./
+RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/gateway ./gateway.go \
+ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/worker ./cmd/worker \
+ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/tool ./cmd/tool
+
+FROM alpine:3.20
+
+RUN apk add --no-cache ca-certificates tzdata \
+ && addgroup -S haixun \
+ && adduser -S -G haixun -h /app haixun
+WORKDIR /app
+COPY --from=build /out/gateway /app/gateway
+COPY --from=build /out/worker /app/worker
+COPY --from=build /out/tool /app/tool
+COPY backend/etc /app/etc
+USER haixun
+EXPOSE 8890
+CMD ["/app/gateway", "-f", "/app/etc/gateway.prod.yaml"]
diff --git a/backend/Makefile b/backend/Makefile
index 5bed275..2be65f9 100644
--- a/backend/Makefile
+++ b/backend/Makefile
@@ -2,10 +2,25 @@
API_FILE := generate/api/gateway.api
GOCTL_HOME := generate/goctl
+GOCTL ?= $(shell go env GOPATH)/bin/goctl
+
+ENV_FILE ?= ../deploy/.env.dev
+
+ifneq ($(wildcard $(ENV_FILE)),)
+# 把 deploy/.env.dev 的值 export 出來(給 make run / native binary 用;dev-all.sh 自行 source 故不走這條)
+include $(ENV_FILE)
+export HAIXUN_MONGO_URI HAIXUN_MONGO_DB HAIXUN_REDIS_ADDR HAIXUN_REDIS_PASSWORD
+export HAIXUN_JWT_ACCESS_SECRET HAIXUN_JWT_REFRESH_SECRET HAIXUN_WORKER_SECRET
+export HAIXUN_SECRETS_KEY HAIXUN_BACKEND_URL
+export HAIXUN_WORKER_POLL_MS HAIXUN_8D_TARGET_SAMPLES PLAYWRIGHT_HEADLESS
+endif
+
+export HAIXUN_JOB_WORKER_TYPE ?= go-demo
+export HAIXUN_JOB_WORKER_ID ?= local-go-demo
# 修改 generate/api/*.api 後執行,重新產生 routes / types / handler(logic 已存在則保留實作)
gen-api:
- goctl api go -api $(API_FILE) -dir . -style go_zero -home $(GOCTL_HOME)
+ $(GOCTL) api go -api $(API_FILE) -dir . -style go_zero -home $(GOCTL_HOME)
fmt:
go fmt ./...
@@ -25,4 +40,4 @@ web-dev:
cd web && npm install && npm run dev
web-build:
- cd web && npm install && npm run build
\ No newline at end of file
+ cd web && npm install && npm run build
diff --git a/backend/cmd/tool/main.go b/backend/cmd/tool/main.go
index 837a0dc..c6b8c35 100644
--- a/backend/cmd/tool/main.go
+++ b/backend/cmd/tool/main.go
@@ -15,6 +15,8 @@ import (
)
func main() {
+ bootstrap.LoadInfraEnv()
+
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
@@ -37,7 +39,7 @@ func runInit(args []string) error {
configFile := fs.String("f", "etc/gateway.yaml", "config file")
tenantID := fs.String("tenant", envOr("INIT_TENANT_ID", "default"), "tenant id for admin and role permissions")
email := fs.String("email", envOr("INIT_ADMIN_EMAIL", "admin@30cm.net"), "bootstrap admin email")
- password := fs.String("password", envOr("INIT_ADMIN_PASSWORD", "Fafafa54088"), "bootstrap admin password")
+ password := fs.String("password", envOr("INIT_ADMIN_PASSWORD", ""), "bootstrap admin password")
displayName := fs.String("display-name", envOr("INIT_ADMIN_DISPLAY_NAME", "Admin"), "bootstrap admin display name")
if err := fs.Parse(args); err != nil {
return err
diff --git a/backend/cmd/worker/main.go b/backend/cmd/worker/main.go
index e80b632..d54f0a0 100644
--- a/backend/cmd/worker/main.go
+++ b/backend/cmd/worker/main.go
@@ -8,6 +8,7 @@ import (
"os/signal"
"syscall"
+ "haixun-backend/internal/bootstrap"
"haixun-backend/internal/config"
"haixun-backend/internal/svc"
@@ -18,11 +19,12 @@ var configFile = flag.String("f", "etc/gateway.worker.yaml", "config file")
func main() {
flag.Parse()
+ bootstrap.LoadInfraEnv()
var c config.Config
conf.MustLoad(*configFile, &c, conf.UseEnv())
- if !c.JobWorker.Enabled {
- fmt.Fprintln(os.Stderr, "[worker] JobWorker.Enabled must be true")
+ if !c.JobWorker.Enabled && !c.JobScheduler.Enabled && !c.JobReaper.Enabled && !c.ThreadsTokenRefresh.Enabled && !c.ThreadsPublishQueue.Enabled {
+ fmt.Fprintln(os.Stderr, "[worker] at least one worker, scheduler, reaper, token sweeper, or publish queue sweeper must be enabled")
os.Exit(1)
}
@@ -30,10 +32,13 @@ func main() {
defer sc.Close(context.Background())
fmt.Printf(
- "[worker] started type=%s (scheduler=%v reaper=%v)\n",
+ "[worker] started type=%s (job=%v scheduler=%v reaper=%v token_sweeper=%v publish_sweeper=%v)\n",
c.JobWorker.WorkerType,
+ c.JobWorker.Enabled,
c.JobScheduler.Enabled,
c.JobReaper.Enabled,
+ c.ThreadsTokenRefresh.Enabled,
+ c.ThreadsPublishQueue.Enabled,
)
ch := make(chan os.Signal, 1)
diff --git a/backend/dev-console/node_modules/.bin/esbuild b/backend/dev-console/node_modules/.bin/esbuild
deleted file mode 120000
index c83ac07..0000000
--- a/backend/dev-console/node_modules/.bin/esbuild
+++ /dev/null
@@ -1 +0,0 @@
-../esbuild/bin/esbuild
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/.bin/nanoid b/backend/dev-console/node_modules/.bin/nanoid
deleted file mode 120000
index e2be547..0000000
--- a/backend/dev-console/node_modules/.bin/nanoid
+++ /dev/null
@@ -1 +0,0 @@
-../nanoid/bin/nanoid.cjs
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/.bin/rollup b/backend/dev-console/node_modules/.bin/rollup
deleted file mode 120000
index 5939621..0000000
--- a/backend/dev-console/node_modules/.bin/rollup
+++ /dev/null
@@ -1 +0,0 @@
-../rollup/dist/bin/rollup
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/.bin/vite b/backend/dev-console/node_modules/.bin/vite
deleted file mode 120000
index 6d1e3be..0000000
--- a/backend/dev-console/node_modules/.bin/vite
+++ /dev/null
@@ -1 +0,0 @@
-../vite/bin/vite.js
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/.package-lock.json b/backend/dev-console/node_modules/.package-lock.json
deleted file mode 100644
index 49d52dd..0000000
--- a/backend/dev-console/node_modules/.package-lock.json
+++ /dev/null
@@ -1,320 +0,0 @@
-{
- "name": "haixun-dev-console",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "node_modules/@esbuild/darwin-arm64": {
- "version": "0.25.12",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
- "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@rollup/rollup-darwin-arm64": {
- "version": "4.62.2",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz",
- "integrity": "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@types/estree": {
- "version": "1.0.9",
- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
- "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/esbuild": {
- "version": "0.25.12",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
- "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
- "dev": true,
- "hasInstallScript": true,
- "license": "MIT",
- "bin": {
- "esbuild": "bin/esbuild"
- },
- "engines": {
- "node": ">=18"
- },
- "optionalDependencies": {
- "@esbuild/aix-ppc64": "0.25.12",
- "@esbuild/android-arm": "0.25.12",
- "@esbuild/android-arm64": "0.25.12",
- "@esbuild/android-x64": "0.25.12",
- "@esbuild/darwin-arm64": "0.25.12",
- "@esbuild/darwin-x64": "0.25.12",
- "@esbuild/freebsd-arm64": "0.25.12",
- "@esbuild/freebsd-x64": "0.25.12",
- "@esbuild/linux-arm": "0.25.12",
- "@esbuild/linux-arm64": "0.25.12",
- "@esbuild/linux-ia32": "0.25.12",
- "@esbuild/linux-loong64": "0.25.12",
- "@esbuild/linux-mips64el": "0.25.12",
- "@esbuild/linux-ppc64": "0.25.12",
- "@esbuild/linux-riscv64": "0.25.12",
- "@esbuild/linux-s390x": "0.25.12",
- "@esbuild/linux-x64": "0.25.12",
- "@esbuild/netbsd-arm64": "0.25.12",
- "@esbuild/netbsd-x64": "0.25.12",
- "@esbuild/openbsd-arm64": "0.25.12",
- "@esbuild/openbsd-x64": "0.25.12",
- "@esbuild/openharmony-arm64": "0.25.12",
- "@esbuild/sunos-x64": "0.25.12",
- "@esbuild/win32-arm64": "0.25.12",
- "@esbuild/win32-ia32": "0.25.12",
- "@esbuild/win32-x64": "0.25.12"
- }
- },
- "node_modules/fdir": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- }
- },
- "node_modules/nanoid": {
- "version": "3.3.15",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
- "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
- "dev": true,
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "license": "MIT",
- "bin": {
- "nanoid": "bin/nanoid.cjs"
- },
- "engines": {
- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
- }
- },
- "node_modules/picocolors": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
- "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
- "dev": true,
- "license": "ISC"
- },
- "node_modules/picomatch": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
- "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
- "node_modules/postcss": {
- "version": "8.5.16",
- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
- "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
- "dev": true,
- "funding": [
- {
- "type": "opencollective",
- "url": "https://opencollective.com/postcss/"
- },
- {
- "type": "tidelift",
- "url": "https://tidelift.com/funding/github/npm/postcss"
- },
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "nanoid": "^3.3.12",
- "picocolors": "^1.1.1",
- "source-map-js": "^1.2.1"
- },
- "engines": {
- "node": "^10 || ^12 || >=14"
- }
- },
- "node_modules/rollup": {
- "version": "4.62.2",
- "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
- "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/estree": "1.0.9"
- },
- "bin": {
- "rollup": "dist/bin/rollup"
- },
- "engines": {
- "node": ">=18.0.0",
- "npm": ">=8.0.0"
- },
- "optionalDependencies": {
- "@rollup/rollup-android-arm-eabi": "4.62.2",
- "@rollup/rollup-android-arm64": "4.62.2",
- "@rollup/rollup-darwin-arm64": "4.62.2",
- "@rollup/rollup-darwin-x64": "4.62.2",
- "@rollup/rollup-freebsd-arm64": "4.62.2",
- "@rollup/rollup-freebsd-x64": "4.62.2",
- "@rollup/rollup-linux-arm-gnueabihf": "4.62.2",
- "@rollup/rollup-linux-arm-musleabihf": "4.62.2",
- "@rollup/rollup-linux-arm64-gnu": "4.62.2",
- "@rollup/rollup-linux-arm64-musl": "4.62.2",
- "@rollup/rollup-linux-loong64-gnu": "4.62.2",
- "@rollup/rollup-linux-loong64-musl": "4.62.2",
- "@rollup/rollup-linux-ppc64-gnu": "4.62.2",
- "@rollup/rollup-linux-ppc64-musl": "4.62.2",
- "@rollup/rollup-linux-riscv64-gnu": "4.62.2",
- "@rollup/rollup-linux-riscv64-musl": "4.62.2",
- "@rollup/rollup-linux-s390x-gnu": "4.62.2",
- "@rollup/rollup-linux-x64-gnu": "4.62.2",
- "@rollup/rollup-linux-x64-musl": "4.62.2",
- "@rollup/rollup-openbsd-x64": "4.62.2",
- "@rollup/rollup-openharmony-arm64": "4.62.2",
- "@rollup/rollup-win32-arm64-msvc": "4.62.2",
- "@rollup/rollup-win32-ia32-msvc": "4.62.2",
- "@rollup/rollup-win32-x64-gnu": "4.62.2",
- "@rollup/rollup-win32-x64-msvc": "4.62.2",
- "fsevents": "~2.3.2"
- }
- },
- "node_modules/source-map-js": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
- "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
- "dev": true,
- "license": "BSD-3-Clause",
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/tinyglobby": {
- "version": "0.2.17",
- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
- "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "fdir": "^6.5.0",
- "picomatch": "^4.0.4"
- },
- "engines": {
- "node": ">=12.0.0"
- },
- "funding": {
- "url": "https://github.com/sponsors/SuperchupuDev"
- }
- },
- "node_modules/vite": {
- "version": "6.4.3",
- "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
- "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "esbuild": "^0.25.0",
- "fdir": "^6.4.4",
- "picomatch": "^4.0.2",
- "postcss": "^8.5.3",
- "rollup": "^4.34.9",
- "tinyglobby": "^0.2.13"
- },
- "bin": {
- "vite": "bin/vite.js"
- },
- "engines": {
- "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
- },
- "funding": {
- "url": "https://github.com/vitejs/vite?sponsor=1"
- },
- "optionalDependencies": {
- "fsevents": "~2.3.3"
- },
- "peerDependencies": {
- "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
- "jiti": ">=1.21.0",
- "less": "*",
- "lightningcss": "^1.21.0",
- "sass": "*",
- "sass-embedded": "*",
- "stylus": "*",
- "sugarss": "*",
- "terser": "^5.16.0",
- "tsx": "^4.8.1",
- "yaml": "^2.4.2"
- },
- "peerDependenciesMeta": {
- "@types/node": {
- "optional": true
- },
- "jiti": {
- "optional": true
- },
- "less": {
- "optional": true
- },
- "lightningcss": {
- "optional": true
- },
- "sass": {
- "optional": true
- },
- "sass-embedded": {
- "optional": true
- },
- "stylus": {
- "optional": true
- },
- "sugarss": {
- "optional": true
- },
- "terser": {
- "optional": true
- },
- "tsx": {
- "optional": true
- },
- "yaml": {
- "optional": true
- }
- }
- }
- }
-}
diff --git a/backend/dev-console/node_modules/.vite/deps/_metadata.json b/backend/dev-console/node_modules/.vite/deps/_metadata.json
deleted file mode 100644
index c7c42b5..0000000
--- a/backend/dev-console/node_modules/.vite/deps/_metadata.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "hash": "fb6aa1ca",
- "configHash": "038289f4",
- "lockfileHash": "c3f7f58e",
- "browserHash": "a03a034c",
- "optimized": {},
- "chunks": {}
-}
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/.vite/deps/package.json b/backend/dev-console/node_modules/.vite/deps/package.json
deleted file mode 100644
index 3dbc1ca..0000000
--- a/backend/dev-console/node_modules/.vite/deps/package.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "type": "module"
-}
diff --git a/backend/dev-console/node_modules/@esbuild/darwin-arm64/README.md b/backend/dev-console/node_modules/@esbuild/darwin-arm64/README.md
deleted file mode 100644
index c2c0398..0000000
--- a/backend/dev-console/node_modules/@esbuild/darwin-arm64/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# esbuild
-
-This is the macOS ARM 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
diff --git a/backend/dev-console/node_modules/@esbuild/darwin-arm64/bin/esbuild b/backend/dev-console/node_modules/@esbuild/darwin-arm64/bin/esbuild
deleted file mode 100755
index 0cd9ea7..0000000
Binary files a/backend/dev-console/node_modules/@esbuild/darwin-arm64/bin/esbuild and /dev/null differ
diff --git a/backend/dev-console/node_modules/@esbuild/darwin-arm64/package.json b/backend/dev-console/node_modules/@esbuild/darwin-arm64/package.json
deleted file mode 100644
index 3f0242c..0000000
--- a/backend/dev-console/node_modules/@esbuild/darwin-arm64/package.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "name": "@esbuild/darwin-arm64",
- "version": "0.25.12",
- "description": "The macOS ARM 64-bit binary for esbuild, a JavaScript bundler.",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/evanw/esbuild.git"
- },
- "license": "MIT",
- "preferUnplugged": true,
- "engines": {
- "node": ">=18"
- },
- "os": [
- "darwin"
- ],
- "cpu": [
- "arm64"
- ]
-}
diff --git a/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/README.md b/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/README.md
deleted file mode 100644
index c29619c..0000000
--- a/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# `@rollup/rollup-darwin-arm64`
-
-This is the **aarch64-apple-darwin** binary for `rollup`
diff --git a/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/package.json b/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/package.json
deleted file mode 100644
index 259548c..0000000
--- a/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/package.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "name": "@rollup/rollup-darwin-arm64",
- "version": "4.62.2",
- "os": [
- "darwin"
- ],
- "cpu": [
- "arm64"
- ],
- "files": [
- "rollup.darwin-arm64.node"
- ],
- "description": "Native bindings for Rollup",
- "author": "Lukas Taegert-Atkinson",
- "homepage": "https://rollupjs.org/",
- "license": "MIT",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/rollup/rollup.git"
- },
- "main": "./rollup.darwin-arm64.node"
-}
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/rollup.darwin-arm64.node b/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/rollup.darwin-arm64.node
deleted file mode 100644
index 6b208b8..0000000
Binary files a/backend/dev-console/node_modules/@rollup/rollup-darwin-arm64/rollup.darwin-arm64.node and /dev/null differ
diff --git a/backend/dev-console/node_modules/@types/estree/LICENSE b/backend/dev-console/node_modules/@types/estree/LICENSE
deleted file mode 100644
index 9e841e7..0000000
--- a/backend/dev-console/node_modules/@types/estree/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
- MIT License
-
- Copyright (c) Microsoft Corporation.
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE
diff --git a/backend/dev-console/node_modules/@types/estree/README.md b/backend/dev-console/node_modules/@types/estree/README.md
deleted file mode 100644
index 3e3e70f..0000000
--- a/backend/dev-console/node_modules/@types/estree/README.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Installation
-> `npm install --save @types/estree`
-
-# Summary
-This package contains type definitions for estree (https://github.com/estree/estree).
-
-# Details
-Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree.
-
-### Additional Details
- * Last updated: Wed, 06 May 2026 21:01:00 GMT
- * Dependencies: none
-
-# Credits
-These definitions were written by [RReverser](https://github.com/RReverser).
diff --git a/backend/dev-console/node_modules/@types/estree/flow.d.ts b/backend/dev-console/node_modules/@types/estree/flow.d.ts
deleted file mode 100644
index 9d001a9..0000000
--- a/backend/dev-console/node_modules/@types/estree/flow.d.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-declare namespace ESTree {
- interface FlowTypeAnnotation extends Node {}
-
- interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {}
-
- interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {}
-
- interface FlowDeclaration extends Declaration {}
-
- interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {}
-
- interface ArrayTypeAnnotation extends FlowTypeAnnotation {
- elementType: FlowTypeAnnotation;
- }
-
- interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {}
-
- interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {}
-
- interface ClassImplements extends Node {
- id: Identifier;
- typeParameters?: TypeParameterInstantiation | null;
- }
-
- interface ClassProperty {
- key: Expression;
- value?: Expression | null;
- typeAnnotation?: TypeAnnotation | null;
- computed: boolean;
- static: boolean;
- }
-
- interface DeclareClass extends FlowDeclaration {
- id: Identifier;
- typeParameters?: TypeParameterDeclaration | null;
- body: ObjectTypeAnnotation;
- extends: InterfaceExtends[];
- }
-
- interface DeclareFunction extends FlowDeclaration {
- id: Identifier;
- }
-
- interface DeclareModule extends FlowDeclaration {
- id: Literal | Identifier;
- body: BlockStatement;
- }
-
- interface DeclareVariable extends FlowDeclaration {
- id: Identifier;
- }
-
- interface FunctionTypeAnnotation extends FlowTypeAnnotation {
- params: FunctionTypeParam[];
- returnType: FlowTypeAnnotation;
- rest?: FunctionTypeParam | null;
- typeParameters?: TypeParameterDeclaration | null;
- }
-
- interface FunctionTypeParam {
- name: Identifier;
- typeAnnotation: FlowTypeAnnotation;
- optional: boolean;
- }
-
- interface GenericTypeAnnotation extends FlowTypeAnnotation {
- id: Identifier | QualifiedTypeIdentifier;
- typeParameters?: TypeParameterInstantiation | null;
- }
-
- interface InterfaceExtends extends Node {
- id: Identifier | QualifiedTypeIdentifier;
- typeParameters?: TypeParameterInstantiation | null;
- }
-
- interface InterfaceDeclaration extends FlowDeclaration {
- id: Identifier;
- typeParameters?: TypeParameterDeclaration | null;
- extends: InterfaceExtends[];
- body: ObjectTypeAnnotation;
- }
-
- interface IntersectionTypeAnnotation extends FlowTypeAnnotation {
- types: FlowTypeAnnotation[];
- }
-
- interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {}
-
- interface NullableTypeAnnotation extends FlowTypeAnnotation {
- typeAnnotation: TypeAnnotation;
- }
-
- interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {}
-
- interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {}
-
- interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {}
-
- interface StringTypeAnnotation extends FlowBaseTypeAnnotation {}
-
- interface TupleTypeAnnotation extends FlowTypeAnnotation {
- types: FlowTypeAnnotation[];
- }
-
- interface TypeofTypeAnnotation extends FlowTypeAnnotation {
- argument: FlowTypeAnnotation;
- }
-
- interface TypeAlias extends FlowDeclaration {
- id: Identifier;
- typeParameters?: TypeParameterDeclaration | null;
- right: FlowTypeAnnotation;
- }
-
- interface TypeAnnotation extends Node {
- typeAnnotation: FlowTypeAnnotation;
- }
-
- interface TypeCastExpression extends Expression {
- expression: Expression;
- typeAnnotation: TypeAnnotation;
- }
-
- interface TypeParameterDeclaration extends Node {
- params: Identifier[];
- }
-
- interface TypeParameterInstantiation extends Node {
- params: FlowTypeAnnotation[];
- }
-
- interface ObjectTypeAnnotation extends FlowTypeAnnotation {
- properties: ObjectTypeProperty[];
- indexers: ObjectTypeIndexer[];
- callProperties: ObjectTypeCallProperty[];
- }
-
- interface ObjectTypeCallProperty extends Node {
- value: FunctionTypeAnnotation;
- static: boolean;
- }
-
- interface ObjectTypeIndexer extends Node {
- id: Identifier;
- key: FlowTypeAnnotation;
- value: FlowTypeAnnotation;
- static: boolean;
- }
-
- interface ObjectTypeProperty extends Node {
- key: Expression;
- value: FlowTypeAnnotation;
- optional: boolean;
- static: boolean;
- }
-
- interface QualifiedTypeIdentifier extends Node {
- qualification: Identifier | QualifiedTypeIdentifier;
- id: Identifier;
- }
-
- interface UnionTypeAnnotation extends FlowTypeAnnotation {
- types: FlowTypeAnnotation[];
- }
-
- interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {}
-}
diff --git a/backend/dev-console/node_modules/@types/estree/index.d.ts b/backend/dev-console/node_modules/@types/estree/index.d.ts
deleted file mode 100644
index 7d4ab36..0000000
--- a/backend/dev-console/node_modules/@types/estree/index.d.ts
+++ /dev/null
@@ -1,694 +0,0 @@
-// This definition file follows a somewhat unusual format. ESTree allows
-// runtime type checks based on the `type` parameter. In order to explain this
-// to typescript we want to use discriminated union types:
-// https://github.com/Microsoft/TypeScript/pull/9163
-//
-// For ESTree this is a bit tricky because the high level interfaces like
-// Node or Function are pulling double duty. We want to pass common fields down
-// to the interfaces that extend them (like Identifier or
-// ArrowFunctionExpression), but you can't extend a type union or enforce
-// common fields on them. So we've split the high level interfaces into two
-// types, a base type which passes down inherited fields, and a type union of
-// all types which extend the base type. Only the type union is exported, and
-// the union is how other types refer to the collection of inheriting types.
-//
-// This makes the definitions file here somewhat more difficult to maintain,
-// but it has the notable advantage of making ESTree much easier to use as
-// an end user.
-
-export interface BaseNodeWithoutComments {
- // Every leaf interface that extends BaseNode must specify a type property.
- // The type property should be a string literal. For example, Identifier
- // has: `type: "Identifier"`
- type: string;
- loc?: SourceLocation | null | undefined;
- range?: [number, number] | undefined;
-}
-
-export interface BaseNode extends BaseNodeWithoutComments {
- leadingComments?: Comment[] | undefined;
- trailingComments?: Comment[] | undefined;
-}
-
-export interface NodeMap {
- AssignmentProperty: AssignmentProperty;
- CatchClause: CatchClause;
- Class: Class;
- ClassBody: ClassBody;
- Expression: Expression;
- Function: Function;
- Identifier: Identifier;
- Literal: Literal;
- MethodDefinition: MethodDefinition;
- ModuleDeclaration: ModuleDeclaration;
- ModuleSpecifier: ModuleSpecifier;
- Pattern: Pattern;
- PrivateIdentifier: PrivateIdentifier;
- Program: Program;
- Property: Property;
- PropertyDefinition: PropertyDefinition;
- SpreadElement: SpreadElement;
- Statement: Statement;
- Super: Super;
- SwitchCase: SwitchCase;
- TemplateElement: TemplateElement;
- VariableDeclarator: VariableDeclarator;
-}
-
-export type Node = NodeMap[keyof NodeMap];
-
-export interface Comment extends BaseNodeWithoutComments {
- type: "Line" | "Block";
- value: string;
-}
-
-export interface SourceLocation {
- source?: string | null | undefined;
- start: Position;
- end: Position;
-}
-
-export interface Position {
- /** >= 1 */
- line: number;
- /** >= 0 */
- column: number;
-}
-
-export interface Program extends BaseNode {
- type: "Program";
- sourceType: "script" | "module";
- body: Array;
- comments?: Comment[] | undefined;
-}
-
-export interface Directive extends BaseNode {
- type: "ExpressionStatement";
- expression: Literal;
- directive: string;
-}
-
-export interface BaseFunction extends BaseNode {
- params: Pattern[];
- generator?: boolean | undefined;
- async?: boolean | undefined;
- // The body is either BlockStatement or Expression because arrow functions
- // can have a body that's either. FunctionDeclarations and
- // FunctionExpressions have only BlockStatement bodies.
- body: BlockStatement | Expression;
-}
-
-export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
-
-export type Statement =
- | ExpressionStatement
- | BlockStatement
- | StaticBlock
- | EmptyStatement
- | DebuggerStatement
- | WithStatement
- | ReturnStatement
- | LabeledStatement
- | BreakStatement
- | ContinueStatement
- | IfStatement
- | SwitchStatement
- | ThrowStatement
- | TryStatement
- | WhileStatement
- | DoWhileStatement
- | ForStatement
- | ForInStatement
- | ForOfStatement
- | Declaration;
-
-export interface BaseStatement extends BaseNode {}
-
-export interface EmptyStatement extends BaseStatement {
- type: "EmptyStatement";
-}
-
-export interface BlockStatement extends BaseStatement {
- type: "BlockStatement";
- body: Statement[];
- innerComments?: Comment[] | undefined;
-}
-
-export interface StaticBlock extends Omit {
- type: "StaticBlock";
-}
-
-export interface ExpressionStatement extends BaseStatement {
- type: "ExpressionStatement";
- expression: Expression;
-}
-
-export interface IfStatement extends BaseStatement {
- type: "IfStatement";
- test: Expression;
- consequent: Statement;
- alternate?: Statement | null | undefined;
-}
-
-export interface LabeledStatement extends BaseStatement {
- type: "LabeledStatement";
- label: Identifier;
- body: Statement;
-}
-
-export interface BreakStatement extends BaseStatement {
- type: "BreakStatement";
- label?: Identifier | null | undefined;
-}
-
-export interface ContinueStatement extends BaseStatement {
- type: "ContinueStatement";
- label?: Identifier | null | undefined;
-}
-
-export interface WithStatement extends BaseStatement {
- type: "WithStatement";
- object: Expression;
- body: Statement;
-}
-
-export interface SwitchStatement extends BaseStatement {
- type: "SwitchStatement";
- discriminant: Expression;
- cases: SwitchCase[];
-}
-
-export interface ReturnStatement extends BaseStatement {
- type: "ReturnStatement";
- argument?: Expression | null | undefined;
-}
-
-export interface ThrowStatement extends BaseStatement {
- type: "ThrowStatement";
- argument: Expression;
-}
-
-export interface TryStatement extends BaseStatement {
- type: "TryStatement";
- block: BlockStatement;
- handler?: CatchClause | null | undefined;
- finalizer?: BlockStatement | null | undefined;
-}
-
-export interface WhileStatement extends BaseStatement {
- type: "WhileStatement";
- test: Expression;
- body: Statement;
-}
-
-export interface DoWhileStatement extends BaseStatement {
- type: "DoWhileStatement";
- body: Statement;
- test: Expression;
-}
-
-export interface ForStatement extends BaseStatement {
- type: "ForStatement";
- init?: VariableDeclaration | Expression | null | undefined;
- test?: Expression | null | undefined;
- update?: Expression | null | undefined;
- body: Statement;
-}
-
-export interface BaseForXStatement extends BaseStatement {
- left: VariableDeclaration | Pattern;
- right: Expression;
- body: Statement;
-}
-
-export interface ForInStatement extends BaseForXStatement {
- type: "ForInStatement";
-}
-
-export interface DebuggerStatement extends BaseStatement {
- type: "DebuggerStatement";
-}
-
-export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
-
-export interface BaseDeclaration extends BaseStatement {}
-
-export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
- type: "FunctionDeclaration";
- /** It is null when a function declaration is a part of the `export default function` statement */
- id: Identifier | null;
- body: BlockStatement;
-}
-
-export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
- id: Identifier;
-}
-
-export interface VariableDeclaration extends BaseDeclaration {
- type: "VariableDeclaration";
- declarations: VariableDeclarator[];
- kind: "var" | "let" | "const" | "using" | "await using";
-}
-
-export interface VariableDeclarator extends BaseNode {
- type: "VariableDeclarator";
- id: Pattern;
- init?: Expression | null | undefined;
-}
-
-export interface ExpressionMap {
- ArrayExpression: ArrayExpression;
- ArrowFunctionExpression: ArrowFunctionExpression;
- AssignmentExpression: AssignmentExpression;
- AwaitExpression: AwaitExpression;
- BinaryExpression: BinaryExpression;
- CallExpression: CallExpression;
- ChainExpression: ChainExpression;
- ClassExpression: ClassExpression;
- ConditionalExpression: ConditionalExpression;
- FunctionExpression: FunctionExpression;
- Identifier: Identifier;
- ImportExpression: ImportExpression;
- Literal: Literal;
- LogicalExpression: LogicalExpression;
- MemberExpression: MemberExpression;
- MetaProperty: MetaProperty;
- NewExpression: NewExpression;
- ObjectExpression: ObjectExpression;
- SequenceExpression: SequenceExpression;
- TaggedTemplateExpression: TaggedTemplateExpression;
- TemplateLiteral: TemplateLiteral;
- ThisExpression: ThisExpression;
- UnaryExpression: UnaryExpression;
- UpdateExpression: UpdateExpression;
- YieldExpression: YieldExpression;
-}
-
-export type Expression = ExpressionMap[keyof ExpressionMap];
-
-export interface BaseExpression extends BaseNode {}
-
-export type ChainElement = SimpleCallExpression | MemberExpression;
-
-export interface ChainExpression extends BaseExpression {
- type: "ChainExpression";
- expression: ChainElement;
-}
-
-export interface ThisExpression extends BaseExpression {
- type: "ThisExpression";
-}
-
-export interface ArrayExpression extends BaseExpression {
- type: "ArrayExpression";
- elements: Array;
-}
-
-export interface ObjectExpression extends BaseExpression {
- type: "ObjectExpression";
- properties: Array;
-}
-
-export interface PrivateIdentifier extends BaseNode {
- type: "PrivateIdentifier";
- name: string;
-}
-
-export interface Property extends BaseNode {
- type: "Property";
- key: Expression;
- value: Expression | Pattern; // Could be an AssignmentProperty
- kind: "init" | "get" | "set";
- method: boolean;
- shorthand: boolean;
- computed: boolean;
-}
-
-export interface PropertyDefinition extends BaseNode {
- type: "PropertyDefinition";
- key: Expression | PrivateIdentifier;
- value?: Expression | null | undefined;
- computed: boolean;
- static: boolean;
-}
-
-export interface FunctionExpression extends BaseFunction, BaseExpression {
- id?: Identifier | null | undefined;
- type: "FunctionExpression";
- body: BlockStatement;
-}
-
-export interface SequenceExpression extends BaseExpression {
- type: "SequenceExpression";
- expressions: Expression[];
-}
-
-export interface UnaryExpression extends BaseExpression {
- type: "UnaryExpression";
- operator: UnaryOperator;
- prefix: true;
- argument: Expression;
-}
-
-export interface BinaryExpression extends BaseExpression {
- type: "BinaryExpression";
- operator: BinaryOperator;
- left: Expression | PrivateIdentifier;
- right: Expression;
-}
-
-export interface AssignmentExpression extends BaseExpression {
- type: "AssignmentExpression";
- operator: AssignmentOperator;
- left: Pattern | MemberExpression;
- right: Expression;
-}
-
-export interface UpdateExpression extends BaseExpression {
- type: "UpdateExpression";
- operator: UpdateOperator;
- argument: Expression;
- prefix: boolean;
-}
-
-export interface LogicalExpression extends BaseExpression {
- type: "LogicalExpression";
- operator: LogicalOperator;
- left: Expression;
- right: Expression;
-}
-
-export interface ConditionalExpression extends BaseExpression {
- type: "ConditionalExpression";
- test: Expression;
- alternate: Expression;
- consequent: Expression;
-}
-
-export interface BaseCallExpression extends BaseExpression {
- callee: Expression | Super;
- arguments: Array;
-}
-export type CallExpression = SimpleCallExpression | NewExpression;
-
-export interface SimpleCallExpression extends BaseCallExpression {
- type: "CallExpression";
- optional: boolean;
-}
-
-export interface NewExpression extends BaseCallExpression {
- type: "NewExpression";
-}
-
-export interface MemberExpression extends BaseExpression, BasePattern {
- type: "MemberExpression";
- object: Expression | Super;
- property: Expression | PrivateIdentifier;
- computed: boolean;
- optional: boolean;
-}
-
-export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
-
-export interface BasePattern extends BaseNode {}
-
-export interface SwitchCase extends BaseNode {
- type: "SwitchCase";
- test?: Expression | null | undefined;
- consequent: Statement[];
-}
-
-export interface CatchClause extends BaseNode {
- type: "CatchClause";
- param: Pattern | null;
- body: BlockStatement;
-}
-
-export interface Identifier extends BaseNode, BaseExpression, BasePattern {
- type: "Identifier";
- name: string;
-}
-
-export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
-
-export interface SimpleLiteral extends BaseNode, BaseExpression {
- type: "Literal";
- value: string | boolean | number | null;
- raw?: string | undefined;
-}
-
-export interface RegExpLiteral extends BaseNode, BaseExpression {
- type: "Literal";
- value?: RegExp | null | undefined;
- regex: {
- pattern: string;
- flags: string;
- };
- raw?: string | undefined;
-}
-
-export interface BigIntLiteral extends BaseNode, BaseExpression {
- type: "Literal";
- value?: bigint | null | undefined;
- bigint: string;
- raw?: string | undefined;
-}
-
-export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
-
-export type BinaryOperator =
- | "=="
- | "!="
- | "==="
- | "!=="
- | "<"
- | "<="
- | ">"
- | ">="
- | "<<"
- | ">>"
- | ">>>"
- | "+"
- | "-"
- | "*"
- | "/"
- | "%"
- | "**"
- | "|"
- | "^"
- | "&"
- | "in"
- | "instanceof";
-
-export type LogicalOperator = "||" | "&&" | "??";
-
-export type AssignmentOperator =
- | "="
- | "+="
- | "-="
- | "*="
- | "/="
- | "%="
- | "**="
- | "<<="
- | ">>="
- | ">>>="
- | "|="
- | "^="
- | "&="
- | "||="
- | "&&="
- | "??=";
-
-export type UpdateOperator = "++" | "--";
-
-export interface ForOfStatement extends BaseForXStatement {
- type: "ForOfStatement";
- await: boolean;
-}
-
-export interface Super extends BaseNode {
- type: "Super";
-}
-
-export interface SpreadElement extends BaseNode {
- type: "SpreadElement";
- argument: Expression;
-}
-
-export interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
- type: "ArrowFunctionExpression";
- expression: boolean;
- body: BlockStatement | Expression;
-}
-
-export interface YieldExpression extends BaseExpression {
- type: "YieldExpression";
- argument?: Expression | null | undefined;
- delegate: boolean;
-}
-
-export interface TemplateLiteral extends BaseExpression {
- type: "TemplateLiteral";
- quasis: TemplateElement[];
- expressions: Expression[];
-}
-
-export interface TaggedTemplateExpression extends BaseExpression {
- type: "TaggedTemplateExpression";
- tag: Expression;
- quasi: TemplateLiteral;
-}
-
-export interface TemplateElement extends BaseNode {
- type: "TemplateElement";
- tail: boolean;
- value: {
- /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
- cooked?: string | null | undefined;
- raw: string;
- };
-}
-
-export interface AssignmentProperty extends Property {
- value: Pattern;
- kind: "init";
- method: boolean; // false
-}
-
-export interface ObjectPattern extends BasePattern {
- type: "ObjectPattern";
- properties: Array;
-}
-
-export interface ArrayPattern extends BasePattern {
- type: "ArrayPattern";
- elements: Array;
-}
-
-export interface RestElement extends BasePattern {
- type: "RestElement";
- argument: Pattern;
-}
-
-export interface AssignmentPattern extends BasePattern {
- type: "AssignmentPattern";
- left: Pattern;
- right: Expression;
-}
-
-export type Class = ClassDeclaration | ClassExpression;
-export interface BaseClass extends BaseNode {
- superClass?: Expression | null | undefined;
- body: ClassBody;
-}
-
-export interface ClassBody extends BaseNode {
- type: "ClassBody";
- body: Array;
-}
-
-export interface MethodDefinition extends BaseNode {
- type: "MethodDefinition";
- key: Expression | PrivateIdentifier;
- value: FunctionExpression;
- kind: "constructor" | "method" | "get" | "set";
- computed: boolean;
- static: boolean;
-}
-
-export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
- type: "ClassDeclaration";
- /** It is null when a class declaration is a part of the `export default class` statement */
- id: Identifier | null;
-}
-
-export interface ClassDeclaration extends MaybeNamedClassDeclaration {
- id: Identifier;
-}
-
-export interface ClassExpression extends BaseClass, BaseExpression {
- type: "ClassExpression";
- id?: Identifier | null | undefined;
-}
-
-export interface MetaProperty extends BaseExpression {
- type: "MetaProperty";
- meta: Identifier;
- property: Identifier;
-}
-
-export type ModuleDeclaration =
- | ImportDeclaration
- | ExportNamedDeclaration
- | ExportDefaultDeclaration
- | ExportAllDeclaration;
-export interface BaseModuleDeclaration extends BaseNode {}
-
-export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
-export interface BaseModuleSpecifier extends BaseNode {
- local: Identifier;
-}
-
-export interface ImportDeclaration extends BaseModuleDeclaration {
- type: "ImportDeclaration";
- specifiers: Array;
- attributes: ImportAttribute[];
- source: Literal;
-}
-
-export interface ImportSpecifier extends BaseModuleSpecifier {
- type: "ImportSpecifier";
- imported: Identifier | Literal;
-}
-
-export interface ImportAttribute extends BaseNode {
- type: "ImportAttribute";
- key: Identifier | Literal;
- value: Literal;
-}
-
-export interface ImportExpression extends BaseExpression {
- type: "ImportExpression";
- source: Expression;
- options?: Expression | null | undefined;
-}
-
-export interface ImportDefaultSpecifier extends BaseModuleSpecifier {
- type: "ImportDefaultSpecifier";
-}
-
-export interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
- type: "ImportNamespaceSpecifier";
-}
-
-export interface ExportNamedDeclaration extends BaseModuleDeclaration {
- type: "ExportNamedDeclaration";
- declaration?: Declaration | null | undefined;
- specifiers: ExportSpecifier[];
- attributes: ImportAttribute[];
- source?: Literal | null | undefined;
-}
-
-export interface ExportSpecifier extends Omit {
- type: "ExportSpecifier";
- local: Identifier | Literal;
- exported: Identifier | Literal;
-}
-
-export interface ExportDefaultDeclaration extends BaseModuleDeclaration {
- type: "ExportDefaultDeclaration";
- declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
-}
-
-export interface ExportAllDeclaration extends BaseModuleDeclaration {
- type: "ExportAllDeclaration";
- exported: Identifier | Literal | null;
- attributes: ImportAttribute[];
- source: Literal;
-}
-
-export interface AwaitExpression extends BaseExpression {
- type: "AwaitExpression";
- argument: Expression;
-}
diff --git a/backend/dev-console/node_modules/@types/estree/package.json b/backend/dev-console/node_modules/@types/estree/package.json
deleted file mode 100644
index 367a5d9..0000000
--- a/backend/dev-console/node_modules/@types/estree/package.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "name": "@types/estree",
- "version": "1.0.9",
- "description": "TypeScript definitions for estree",
- "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree",
- "license": "MIT",
- "contributors": [
- {
- "name": "RReverser",
- "githubUsername": "RReverser",
- "url": "https://github.com/RReverser"
- }
- ],
- "main": "",
- "types": "index.d.ts",
- "repository": {
- "type": "git",
- "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
- "directory": "types/estree"
- },
- "scripts": {},
- "dependencies": {},
- "peerDependencies": {},
- "typesPublisherContentHash": "db16da859cb0bee641414117047a4becba2e9f39d3e14a6745f887c47ef68482",
- "typeScriptVersion": "5.3",
- "nonNpm": true
-}
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/esbuild/LICENSE.md b/backend/dev-console/node_modules/esbuild/LICENSE.md
deleted file mode 100644
index 2027e8d..0000000
--- a/backend/dev-console/node_modules/esbuild/LICENSE.md
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 Evan Wallace
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/backend/dev-console/node_modules/esbuild/README.md b/backend/dev-console/node_modules/esbuild/README.md
deleted file mode 100644
index 93863d1..0000000
--- a/backend/dev-console/node_modules/esbuild/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# esbuild
-
-This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details.
diff --git a/backend/dev-console/node_modules/esbuild/bin/esbuild b/backend/dev-console/node_modules/esbuild/bin/esbuild
deleted file mode 100755
index 0cd9ea7..0000000
Binary files a/backend/dev-console/node_modules/esbuild/bin/esbuild and /dev/null differ
diff --git a/backend/dev-console/node_modules/esbuild/install.js b/backend/dev-console/node_modules/esbuild/install.js
deleted file mode 100644
index 1019e62..0000000
--- a/backend/dev-console/node_modules/esbuild/install.js
+++ /dev/null
@@ -1,289 +0,0 @@
-"use strict";
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
- // If the importer is in node compatibility mode or this is not an ESM
- // file that has been converted to a CommonJS file using a Babel-
- // compatible transform (i.e. "__esModule" has not been set), then set
- // "default" to the CommonJS "module.exports" for node compatibility.
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
- mod
-));
-
-// lib/npm/node-platform.ts
-var fs = require("fs");
-var os = require("os");
-var path = require("path");
-var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
-var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
-var knownWindowsPackages = {
- "win32 arm64 LE": "@esbuild/win32-arm64",
- "win32 ia32 LE": "@esbuild/win32-ia32",
- "win32 x64 LE": "@esbuild/win32-x64"
-};
-var knownUnixlikePackages = {
- "aix ppc64 BE": "@esbuild/aix-ppc64",
- "android arm64 LE": "@esbuild/android-arm64",
- "darwin arm64 LE": "@esbuild/darwin-arm64",
- "darwin x64 LE": "@esbuild/darwin-x64",
- "freebsd arm64 LE": "@esbuild/freebsd-arm64",
- "freebsd x64 LE": "@esbuild/freebsd-x64",
- "linux arm LE": "@esbuild/linux-arm",
- "linux arm64 LE": "@esbuild/linux-arm64",
- "linux ia32 LE": "@esbuild/linux-ia32",
- "linux mips64el LE": "@esbuild/linux-mips64el",
- "linux ppc64 LE": "@esbuild/linux-ppc64",
- "linux riscv64 LE": "@esbuild/linux-riscv64",
- "linux s390x BE": "@esbuild/linux-s390x",
- "linux x64 LE": "@esbuild/linux-x64",
- "linux loong64 LE": "@esbuild/linux-loong64",
- "netbsd arm64 LE": "@esbuild/netbsd-arm64",
- "netbsd x64 LE": "@esbuild/netbsd-x64",
- "openbsd arm64 LE": "@esbuild/openbsd-arm64",
- "openbsd x64 LE": "@esbuild/openbsd-x64",
- "sunos x64 LE": "@esbuild/sunos-x64"
-};
-var knownWebAssemblyFallbackPackages = {
- "android arm LE": "@esbuild/android-arm",
- "android x64 LE": "@esbuild/android-x64",
- "openharmony arm64 LE": "@esbuild/openharmony-arm64"
-};
-function pkgAndSubpathForCurrentPlatform() {
- let pkg;
- let subpath;
- let isWASM = false;
- let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
- if (platformKey in knownWindowsPackages) {
- pkg = knownWindowsPackages[platformKey];
- subpath = "esbuild.exe";
- } else if (platformKey in knownUnixlikePackages) {
- pkg = knownUnixlikePackages[platformKey];
- subpath = "bin/esbuild";
- } else if (platformKey in knownWebAssemblyFallbackPackages) {
- pkg = knownWebAssemblyFallbackPackages[platformKey];
- subpath = "bin/esbuild";
- isWASM = true;
- } else {
- throw new Error(`Unsupported platform: ${platformKey}`);
- }
- return { pkg, subpath, isWASM };
-}
-function downloadedBinPath(pkg, subpath) {
- const esbuildLibDir = path.dirname(require.resolve("esbuild"));
- return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
-}
-
-// lib/npm/node-install.ts
-var fs2 = require("fs");
-var os2 = require("os");
-var path2 = require("path");
-var zlib = require("zlib");
-var https = require("https");
-var child_process = require("child_process");
-var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;
-var toPath = path2.join(__dirname, "bin", "esbuild");
-var isToPathJS = true;
-function validateBinaryVersion(...command) {
- command.push("--version");
- let stdout;
- try {
- stdout = child_process.execFileSync(command.shift(), command, {
- // Without this, this install script strangely crashes with the error
- // "EACCES: permission denied, write" but only on Ubuntu Linux when node is
- // installed from the Snap Store. This is not a problem when you download
- // the official version of node. The problem appears to be that stderr
- // (i.e. file descriptor 2) isn't writable?
- //
- // More info:
- // - https://snapcraft.io/ (what the Snap Store is)
- // - https://nodejs.org/dist/ (download the official version of node)
- // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
- //
- stdio: "pipe"
- }).toString().trim();
- } catch (err) {
- if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {
- let os3 = "this version of macOS";
- try {
- os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();
- } catch {
- }
- throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.
-
-The Go compiler (which esbuild relies on) no longer supports ${os3},
-which means the "esbuild" binary executable can't be run. You can either:
-
- * Update your version of macOS to one that the Go compiler supports
- * Use the "esbuild-wasm" package instead of the "esbuild" package
- * Build esbuild yourself using an older version of the Go compiler
-`);
- }
- throw err;
- }
- if (stdout !== versionFromPackageJSON) {
- throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);
- }
-}
-function isYarn() {
- const { npm_config_user_agent } = process.env;
- if (npm_config_user_agent) {
- return /\byarn\//.test(npm_config_user_agent);
- }
- return false;
-}
-function fetch(url) {
- return new Promise((resolve, reject) => {
- https.get(url, (res) => {
- if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
- return fetch(res.headers.location).then(resolve, reject);
- if (res.statusCode !== 200)
- return reject(new Error(`Server responded with ${res.statusCode}`));
- let chunks = [];
- res.on("data", (chunk) => chunks.push(chunk));
- res.on("end", () => resolve(Buffer.concat(chunks)));
- }).on("error", reject);
- });
-}
-function extractFileFromTarGzip(buffer, subpath) {
- try {
- buffer = zlib.unzipSync(buffer);
- } catch (err) {
- throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
- }
- let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
- let offset = 0;
- subpath = `package/${subpath}`;
- while (offset < buffer.length) {
- let name = str(offset, 100);
- let size = parseInt(str(offset + 124, 12), 8);
- offset += 512;
- if (!isNaN(size)) {
- if (name === subpath) return buffer.subarray(offset, offset + size);
- offset += size + 511 & ~511;
- }
- }
- throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
-}
-function installUsingNPM(pkg, subpath, binPath) {
- const env = { ...process.env, npm_config_global: void 0 };
- const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
- const installDir = path2.join(esbuildLibDir, "npm-install");
- fs2.mkdirSync(installDir);
- try {
- fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
- child_process.execSync(
- `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,
- { cwd: installDir, stdio: "pipe", env }
- );
- const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
- fs2.renameSync(installedBinPath, binPath);
- } finally {
- try {
- removeRecursive(installDir);
- } catch {
- }
- }
-}
-function removeRecursive(dir) {
- for (const entry of fs2.readdirSync(dir)) {
- const entryPath = path2.join(dir, entry);
- let stats;
- try {
- stats = fs2.lstatSync(entryPath);
- } catch {
- continue;
- }
- if (stats.isDirectory()) removeRecursive(entryPath);
- else fs2.unlinkSync(entryPath);
- }
- fs2.rmdirSync(dir);
-}
-function applyManualBinaryPathOverride(overridePath) {
- const pathString = JSON.stringify(overridePath);
- fs2.writeFileSync(toPath, `#!/usr/bin/env node
-require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
-`);
- const libMain = path2.join(__dirname, "lib", "main.js");
- const code = fs2.readFileSync(libMain, "utf8");
- fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
-${code}`);
-}
-function maybeOptimizePackage(binPath) {
- const { isWASM } = pkgAndSubpathForCurrentPlatform();
- if (os2.platform() !== "win32" && !isYarn() && !isWASM) {
- const tempPath = path2.join(__dirname, "bin-esbuild");
- try {
- fs2.linkSync(binPath, tempPath);
- fs2.renameSync(tempPath, toPath);
- isToPathJS = false;
- fs2.unlinkSync(tempPath);
- } catch {
- }
- }
-}
-async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
- const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;
- console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
- try {
- fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
- fs2.chmodSync(binPath, 493);
- } catch (e) {
- console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
- throw e;
- }
-}
-async function checkAndPreparePackage() {
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
- if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
- console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
- } else {
- applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
- return;
- }
- }
- const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
- let binPath;
- try {
- binPath = require.resolve(`${pkg}/${subpath}`);
- } catch (e) {
- console.error(`[esbuild] Failed to find package "${pkg}" on the file system
-
-This can happen if you use the "--no-optional" flag. The "optionalDependencies"
-package.json feature is used by esbuild to install the correct binary executable
-for your current platform. This install script will now attempt to work around
-this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
-`);
- binPath = downloadedBinPath(pkg, subpath);
- try {
- console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
- installUsingNPM(pkg, subpath, binPath);
- } catch (e2) {
- console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
- try {
- await downloadDirectlyFromNPM(pkg, subpath, binPath);
- } catch (e3) {
- throw new Error(`Failed to install package "${pkg}"`);
- }
- }
- }
- maybeOptimizePackage(binPath);
-}
-checkAndPreparePackage().then(() => {
- if (isToPathJS) {
- validateBinaryVersion(process.execPath, toPath);
- } else {
- validateBinaryVersion(toPath);
- }
-});
diff --git a/backend/dev-console/node_modules/esbuild/lib/main.d.ts b/backend/dev-console/node_modules/esbuild/lib/main.d.ts
deleted file mode 100644
index 9e69c39..0000000
--- a/backend/dev-console/node_modules/esbuild/lib/main.d.ts
+++ /dev/null
@@ -1,716 +0,0 @@
-export type Platform = 'browser' | 'node' | 'neutral'
-export type Format = 'iife' | 'cjs' | 'esm'
-export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx'
-export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent'
-export type Charset = 'ascii' | 'utf8'
-export type Drop = 'console' | 'debugger'
-export type AbsPaths = 'code' | 'log' | 'metafile'
-
-interface CommonOptions {
- /** Documentation: https://esbuild.github.io/api/#sourcemap */
- sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both'
- /** Documentation: https://esbuild.github.io/api/#legal-comments */
- legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external'
- /** Documentation: https://esbuild.github.io/api/#source-root */
- sourceRoot?: string
- /** Documentation: https://esbuild.github.io/api/#sources-content */
- sourcesContent?: boolean
-
- /** Documentation: https://esbuild.github.io/api/#format */
- format?: Format
- /** Documentation: https://esbuild.github.io/api/#global-name */
- globalName?: string
- /** Documentation: https://esbuild.github.io/api/#target */
- target?: string | string[]
- /** Documentation: https://esbuild.github.io/api/#supported */
- supported?: Record
- /** Documentation: https://esbuild.github.io/api/#platform */
- platform?: Platform
-
- /** Documentation: https://esbuild.github.io/api/#mangle-props */
- mangleProps?: RegExp
- /** Documentation: https://esbuild.github.io/api/#mangle-props */
- reserveProps?: RegExp
- /** Documentation: https://esbuild.github.io/api/#mangle-props */
- mangleQuoted?: boolean
- /** Documentation: https://esbuild.github.io/api/#mangle-props */
- mangleCache?: Record
- /** Documentation: https://esbuild.github.io/api/#drop */
- drop?: Drop[]
- /** Documentation: https://esbuild.github.io/api/#drop-labels */
- dropLabels?: string[]
- /** Documentation: https://esbuild.github.io/api/#minify */
- minify?: boolean
- /** Documentation: https://esbuild.github.io/api/#minify */
- minifyWhitespace?: boolean
- /** Documentation: https://esbuild.github.io/api/#minify */
- minifyIdentifiers?: boolean
- /** Documentation: https://esbuild.github.io/api/#minify */
- minifySyntax?: boolean
- /** Documentation: https://esbuild.github.io/api/#line-limit */
- lineLimit?: number
- /** Documentation: https://esbuild.github.io/api/#charset */
- charset?: Charset
- /** Documentation: https://esbuild.github.io/api/#tree-shaking */
- treeShaking?: boolean
- /** Documentation: https://esbuild.github.io/api/#ignore-annotations */
- ignoreAnnotations?: boolean
-
- /** Documentation: https://esbuild.github.io/api/#jsx */
- jsx?: 'transform' | 'preserve' | 'automatic'
- /** Documentation: https://esbuild.github.io/api/#jsx-factory */
- jsxFactory?: string
- /** Documentation: https://esbuild.github.io/api/#jsx-fragment */
- jsxFragment?: string
- /** Documentation: https://esbuild.github.io/api/#jsx-import-source */
- jsxImportSource?: string
- /** Documentation: https://esbuild.github.io/api/#jsx-development */
- jsxDev?: boolean
- /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */
- jsxSideEffects?: boolean
-
- /** Documentation: https://esbuild.github.io/api/#define */
- define?: { [key: string]: string }
- /** Documentation: https://esbuild.github.io/api/#pure */
- pure?: string[]
- /** Documentation: https://esbuild.github.io/api/#keep-names */
- keepNames?: boolean
-
- /** Documentation: https://esbuild.github.io/api/#abs-paths */
- absPaths?: AbsPaths[]
- /** Documentation: https://esbuild.github.io/api/#color */
- color?: boolean
- /** Documentation: https://esbuild.github.io/api/#log-level */
- logLevel?: LogLevel
- /** Documentation: https://esbuild.github.io/api/#log-limit */
- logLimit?: number
- /** Documentation: https://esbuild.github.io/api/#log-override */
- logOverride?: Record
-
- /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */
- tsconfigRaw?: string | TsconfigRaw
-}
-
-export interface TsconfigRaw {
- compilerOptions?: {
- alwaysStrict?: boolean
- baseUrl?: string
- experimentalDecorators?: boolean
- importsNotUsedAsValues?: 'remove' | 'preserve' | 'error'
- jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev'
- jsxFactory?: string
- jsxFragmentFactory?: string
- jsxImportSource?: string
- paths?: Record
- preserveValueImports?: boolean
- strict?: boolean
- target?: string
- useDefineForClassFields?: boolean
- verbatimModuleSyntax?: boolean
- }
-}
-
-export interface BuildOptions extends CommonOptions {
- /** Documentation: https://esbuild.github.io/api/#bundle */
- bundle?: boolean
- /** Documentation: https://esbuild.github.io/api/#splitting */
- splitting?: boolean
- /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */
- preserveSymlinks?: boolean
- /** Documentation: https://esbuild.github.io/api/#outfile */
- outfile?: string
- /** Documentation: https://esbuild.github.io/api/#metafile */
- metafile?: boolean
- /** Documentation: https://esbuild.github.io/api/#outdir */
- outdir?: string
- /** Documentation: https://esbuild.github.io/api/#outbase */
- outbase?: string
- /** Documentation: https://esbuild.github.io/api/#external */
- external?: string[]
- /** Documentation: https://esbuild.github.io/api/#packages */
- packages?: 'bundle' | 'external'
- /** Documentation: https://esbuild.github.io/api/#alias */
- alias?: Record
- /** Documentation: https://esbuild.github.io/api/#loader */
- loader?: { [ext: string]: Loader }
- /** Documentation: https://esbuild.github.io/api/#resolve-extensions */
- resolveExtensions?: string[]
- /** Documentation: https://esbuild.github.io/api/#main-fields */
- mainFields?: string[]
- /** Documentation: https://esbuild.github.io/api/#conditions */
- conditions?: string[]
- /** Documentation: https://esbuild.github.io/api/#write */
- write?: boolean
- /** Documentation: https://esbuild.github.io/api/#allow-overwrite */
- allowOverwrite?: boolean
- /** Documentation: https://esbuild.github.io/api/#tsconfig */
- tsconfig?: string
- /** Documentation: https://esbuild.github.io/api/#out-extension */
- outExtension?: { [ext: string]: string }
- /** Documentation: https://esbuild.github.io/api/#public-path */
- publicPath?: string
- /** Documentation: https://esbuild.github.io/api/#entry-names */
- entryNames?: string
- /** Documentation: https://esbuild.github.io/api/#chunk-names */
- chunkNames?: string
- /** Documentation: https://esbuild.github.io/api/#asset-names */
- assetNames?: string
- /** Documentation: https://esbuild.github.io/api/#inject */
- inject?: string[]
- /** Documentation: https://esbuild.github.io/api/#banner */
- banner?: { [type: string]: string }
- /** Documentation: https://esbuild.github.io/api/#footer */
- footer?: { [type: string]: string }
- /** Documentation: https://esbuild.github.io/api/#entry-points */
- entryPoints?: (string | { in: string, out: string })[] | Record
- /** Documentation: https://esbuild.github.io/api/#stdin */
- stdin?: StdinOptions
- /** Documentation: https://esbuild.github.io/plugins/ */
- plugins?: Plugin[]
- /** Documentation: https://esbuild.github.io/api/#working-directory */
- absWorkingDir?: string
- /** Documentation: https://esbuild.github.io/api/#node-paths */
- nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
-}
-
-export interface StdinOptions {
- contents: string | Uint8Array
- resolveDir?: string
- sourcefile?: string
- loader?: Loader
-}
-
-export interface Message {
- id: string
- pluginName: string
- text: string
- location: Location | null
- notes: Note[]
-
- /**
- * Optional user-specified data that is passed through unmodified. You can
- * use this to stash the original error, for example.
- */
- detail: any
-}
-
-export interface Note {
- text: string
- location: Location | null
-}
-
-export interface Location {
- file: string
- namespace: string
- /** 1-based */
- line: number
- /** 0-based, in bytes */
- column: number
- /** in bytes */
- length: number
- lineText: string
- suggestion: string
-}
-
-export interface OutputFile {
- path: string
- contents: Uint8Array
- hash: string
- /** "contents" as text (changes automatically with "contents") */
- readonly text: string
-}
-
-export interface BuildResult {
- errors: Message[]
- warnings: Message[]
- /** Only when "write: false" */
- outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined)
- /** Only when "metafile: true" */
- metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined)
- /** Only when "mangleCache" is present */
- mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
-}
-
-export interface BuildFailure extends Error {
- errors: Message[]
- warnings: Message[]
-}
-
-/** Documentation: https://esbuild.github.io/api/#serve-arguments */
-export interface ServeOptions {
- port?: number
- host?: string
- servedir?: string
- keyfile?: string
- certfile?: string
- fallback?: string
- cors?: CORSOptions
- onRequest?: (args: ServeOnRequestArgs) => void
-}
-
-/** Documentation: https://esbuild.github.io/api/#cors */
-export interface CORSOptions {
- origin?: string | string[]
-}
-
-export interface ServeOnRequestArgs {
- remoteAddress: string
- method: string
- path: string
- status: number
- /** The time to generate the response, not to send it */
- timeInMS: number
-}
-
-/** Documentation: https://esbuild.github.io/api/#serve-return-values */
-export interface ServeResult {
- port: number
- hosts: string[]
-}
-
-export interface TransformOptions extends CommonOptions {
- /** Documentation: https://esbuild.github.io/api/#sourcefile */
- sourcefile?: string
- /** Documentation: https://esbuild.github.io/api/#loader */
- loader?: Loader
- /** Documentation: https://esbuild.github.io/api/#banner */
- banner?: string
- /** Documentation: https://esbuild.github.io/api/#footer */
- footer?: string
-}
-
-export interface TransformResult {
- code: string
- map: string
- warnings: Message[]
- /** Only when "mangleCache" is present */
- mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
- /** Only when "legalComments" is "external" */
- legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined)
-}
-
-export interface TransformFailure extends Error {
- errors: Message[]
- warnings: Message[]
-}
-
-export interface Plugin {
- name: string
- setup: (build: PluginBuild) => (void | Promise)
-}
-
-export interface PluginBuild {
- /** Documentation: https://esbuild.github.io/plugins/#build-options */
- initialOptions: BuildOptions
-
- /** Documentation: https://esbuild.github.io/plugins/#resolve */
- resolve(path: string, options?: ResolveOptions): Promise
-
- /** Documentation: https://esbuild.github.io/plugins/#on-start */
- onStart(callback: () =>
- (OnStartResult | null | void | Promise)): void
-
- /** Documentation: https://esbuild.github.io/plugins/#on-end */
- onEnd(callback: (result: BuildResult) =>
- (OnEndResult | null | void | Promise)): void
-
- /** Documentation: https://esbuild.github.io/plugins/#on-resolve */
- onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) =>
- (OnResolveResult | null | undefined | Promise)): void
-
- /** Documentation: https://esbuild.github.io/plugins/#on-load */
- onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) =>
- (OnLoadResult | null | undefined | Promise)): void
-
- /** Documentation: https://esbuild.github.io/plugins/#on-dispose */
- onDispose(callback: () => void): void
-
- // This is a full copy of the esbuild library in case you need it
- esbuild: {
- context: typeof context,
- build: typeof build,
- buildSync: typeof buildSync,
- transform: typeof transform,
- transformSync: typeof transformSync,
- formatMessages: typeof formatMessages,
- formatMessagesSync: typeof formatMessagesSync,
- analyzeMetafile: typeof analyzeMetafile,
- analyzeMetafileSync: typeof analyzeMetafileSync,
- initialize: typeof initialize,
- version: typeof version,
- }
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#resolve-options */
-export interface ResolveOptions {
- pluginName?: string
- importer?: string
- namespace?: string
- resolveDir?: string
- kind?: ImportKind
- pluginData?: any
- with?: Record
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#resolve-results */
-export interface ResolveResult {
- errors: Message[]
- warnings: Message[]
-
- path: string
- external: boolean
- sideEffects: boolean
- namespace: string
- suffix: string
- pluginData: any
-}
-
-export interface OnStartResult {
- errors?: PartialMessage[]
- warnings?: PartialMessage[]
-}
-
-export interface OnEndResult {
- errors?: PartialMessage[]
- warnings?: PartialMessage[]
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */
-export interface OnResolveOptions {
- filter: RegExp
- namespace?: string
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */
-export interface OnResolveArgs {
- path: string
- importer: string
- namespace: string
- resolveDir: string
- kind: ImportKind
- pluginData: any
- with: Record
-}
-
-export type ImportKind =
- | 'entry-point'
-
- // JS
- | 'import-statement'
- | 'require-call'
- | 'dynamic-import'
- | 'require-resolve'
-
- // CSS
- | 'import-rule'
- | 'composes-from'
- | 'url-token'
-
-/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */
-export interface OnResolveResult {
- pluginName?: string
-
- errors?: PartialMessage[]
- warnings?: PartialMessage[]
-
- path?: string
- external?: boolean
- sideEffects?: boolean
- namespace?: string
- suffix?: string
- pluginData?: any
-
- watchFiles?: string[]
- watchDirs?: string[]
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#on-load-options */
-export interface OnLoadOptions {
- filter: RegExp
- namespace?: string
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */
-export interface OnLoadArgs {
- path: string
- namespace: string
- suffix: string
- pluginData: any
- with: Record
-}
-
-/** Documentation: https://esbuild.github.io/plugins/#on-load-results */
-export interface OnLoadResult {
- pluginName?: string
-
- errors?: PartialMessage[]
- warnings?: PartialMessage[]
-
- contents?: string | Uint8Array
- resolveDir?: string
- loader?: Loader
- pluginData?: any
-
- watchFiles?: string[]
- watchDirs?: string[]
-}
-
-export interface PartialMessage {
- id?: string
- pluginName?: string
- text?: string
- location?: Partial | null
- notes?: PartialNote[]
- detail?: any
-}
-
-export interface PartialNote {
- text?: string
- location?: Partial | null
-}
-
-/** Documentation: https://esbuild.github.io/api/#metafile */
-export interface Metafile {
- inputs: {
- [path: string]: {
- bytes: number
- imports: {
- path: string
- kind: ImportKind
- external?: boolean
- original?: string
- with?: Record
- }[]
- format?: 'cjs' | 'esm'
- with?: Record
- }
- }
- outputs: {
- [path: string]: {
- bytes: number
- inputs: {
- [path: string]: {
- bytesInOutput: number
- }
- }
- imports: {
- path: string
- kind: ImportKind | 'file-loader'
- external?: boolean
- }[]
- exports: string[]
- entryPoint?: string
- cssBundle?: string
- }
- }
-}
-
-export interface FormatMessagesOptions {
- kind: 'error' | 'warning'
- color?: boolean
- terminalWidth?: number
-}
-
-export interface AnalyzeMetafileOptions {
- color?: boolean
- verbose?: boolean
-}
-
-/** Documentation: https://esbuild.github.io/api/#watch-arguments */
-export interface WatchOptions {
- delay?: number // In milliseconds
-}
-
-export interface BuildContext {
- /** Documentation: https://esbuild.github.io/api/#rebuild */
- rebuild(): Promise>
-
- /** Documentation: https://esbuild.github.io/api/#watch */
- watch(options?: WatchOptions): Promise
-
- /** Documentation: https://esbuild.github.io/api/#serve */
- serve(options?: ServeOptions): Promise
-
- cancel(): Promise
- dispose(): Promise
-}
-
-// This is a TypeScript type-level function which replaces any keys in "In"
-// that aren't in "Out" with "never". We use this to reject properties with
-// typos in object literals. See: https://stackoverflow.com/questions/49580725
-type SameShape = In & { [Key in Exclude]: never }
-
-/**
- * This function invokes the "esbuild" command-line tool for you. It returns a
- * promise that either resolves with a "BuildResult" object or rejects with a
- * "BuildFailure" object.
- *
- * - Works in node: yes
- * - Works in browser: yes
- *
- * Documentation: https://esbuild.github.io/api/#build
- */
-export declare function build(options: SameShape): Promise>
-
-/**
- * This is the advanced long-running form of "build" that supports additional
- * features such as watch mode and a local development server.
- *
- * - Works in node: yes
- * - Works in browser: no
- *
- * Documentation: https://esbuild.github.io/api/#build
- */
-export declare function context(options: SameShape): Promise>
-
-/**
- * This function transforms a single JavaScript file. It can be used to minify
- * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
- * to older JavaScript. It returns a promise that is either resolved with a
- * "TransformResult" object or rejected with a "TransformFailure" object.
- *
- * - Works in node: yes
- * - Works in browser: yes
- *
- * Documentation: https://esbuild.github.io/api/#transform
- */
-export declare function transform(input: string | Uint8Array, options?: SameShape): Promise>
-
-/**
- * Converts log messages to formatted message strings suitable for printing in
- * the terminal. This allows you to reuse the built-in behavior of esbuild's
- * log message formatter. This is a batch-oriented API for efficiency.
- *
- * - Works in node: yes
- * - Works in browser: yes
- */
-export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise
-
-/**
- * Pretty-prints an analysis of the metafile JSON to a string. This is just for
- * convenience to be able to match esbuild's pretty-printing exactly. If you want
- * to customize it, you can just inspect the data in the metafile yourself.
- *
- * - Works in node: yes
- * - Works in browser: yes
- *
- * Documentation: https://esbuild.github.io/api/#analyze
- */
-export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise
-
-/**
- * A synchronous version of "build".
- *
- * - Works in node: yes
- * - Works in browser: no
- *
- * Documentation: https://esbuild.github.io/api/#build
- */
-export declare function buildSync(options: SameShape): BuildResult
-
-/**
- * A synchronous version of "transform".
- *
- * - Works in node: yes
- * - Works in browser: no
- *
- * Documentation: https://esbuild.github.io/api/#transform
- */
-export declare function transformSync(input: string | Uint8Array, options?: SameShape): TransformResult
-
-/**
- * A synchronous version of "formatMessages".
- *
- * - Works in node: yes
- * - Works in browser: no
- */
-export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[]
-
-/**
- * A synchronous version of "analyzeMetafile".
- *
- * - Works in node: yes
- * - Works in browser: no
- *
- * Documentation: https://esbuild.github.io/api/#analyze
- */
-export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string
-
-/**
- * This configures the browser-based version of esbuild. It is necessary to
- * call this first and wait for the returned promise to be resolved before
- * making other API calls when using esbuild in the browser.
- *
- * - Works in node: yes
- * - Works in browser: yes ("options" is required)
- *
- * Documentation: https://esbuild.github.io/api/#browser
- */
-export declare function initialize(options: InitializeOptions): Promise
-
-export interface InitializeOptions {
- /**
- * The URL of the "esbuild.wasm" file. This must be provided when running
- * esbuild in the browser.
- */
- wasmURL?: string | URL
-
- /**
- * The result of calling "new WebAssembly.Module(buffer)" where "buffer"
- * is a typed array or ArrayBuffer containing the binary code of the
- * "esbuild.wasm" file.
- *
- * You can use this as an alternative to "wasmURL" for environments where it's
- * not possible to download the WebAssembly module.
- */
- wasmModule?: WebAssembly.Module
-
- /**
- * By default esbuild runs the WebAssembly-based browser API in a web worker
- * to avoid blocking the UI thread. This can be disabled by setting "worker"
- * to false.
- */
- worker?: boolean
-}
-
-export let version: string
-
-// Call this function to terminate esbuild's child process. The child process
-// is not terminated and re-created after each API call because it's more
-// efficient to keep it around when there are multiple API calls.
-//
-// In node this happens automatically before the parent node process exits. So
-// you only need to call this if you know you will not make any more esbuild
-// API calls and you want to clean up resources.
-//
-// Unlike node, Deno lacks the necessary APIs to clean up child processes
-// automatically. You must manually call stop() in Deno when you're done
-// using esbuild or Deno will continue running forever.
-//
-// Another reason you might want to call this is if you are using esbuild from
-// within a Deno test. Deno fails tests that create a child process without
-// killing it before the test ends, so you have to call this function (and
-// await the returned promise) in every Deno test that uses esbuild.
-export declare function stop(): Promise
-
-// Note: These declarations exist to avoid type errors when you omit "dom" from
-// "lib" in your "tsconfig.json" file. TypeScript confusingly declares the
-// global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do
-// with the browser DOM and is present in many non-browser JavaScript runtimes
-// (e.g. node and deno). Declaring it here allows esbuild's API to be used in
-// these scenarios.
-//
-// There's an open issue about getting this problem corrected (although these
-// declarations will need to remain even if this is fixed for backward
-// compatibility with older TypeScript versions):
-//
-// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826
-//
-declare global {
- namespace WebAssembly {
- interface Module {
- }
- }
- interface URL {
- }
-}
diff --git a/backend/dev-console/node_modules/esbuild/lib/main.js b/backend/dev-console/node_modules/esbuild/lib/main.js
deleted file mode 100644
index 87aa87b..0000000
--- a/backend/dev-console/node_modules/esbuild/lib/main.js
+++ /dev/null
@@ -1,2242 +0,0 @@
-"use strict";
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
- // If the importer is in node compatibility mode or this is not an ESM
- // file that has been converted to a CommonJS file using a Babel-
- // compatible transform (i.e. "__esModule" has not been set), then set
- // "default" to the CommonJS "module.exports" for node compatibility.
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
- mod
-));
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// lib/npm/node.ts
-var node_exports = {};
-__export(node_exports, {
- analyzeMetafile: () => analyzeMetafile,
- analyzeMetafileSync: () => analyzeMetafileSync,
- build: () => build,
- buildSync: () => buildSync,
- context: () => context,
- default: () => node_default,
- formatMessages: () => formatMessages,
- formatMessagesSync: () => formatMessagesSync,
- initialize: () => initialize,
- stop: () => stop,
- transform: () => transform,
- transformSync: () => transformSync,
- version: () => version
-});
-module.exports = __toCommonJS(node_exports);
-
-// lib/shared/stdio_protocol.ts
-function encodePacket(packet) {
- let visit = (value) => {
- if (value === null) {
- bb.write8(0);
- } else if (typeof value === "boolean") {
- bb.write8(1);
- bb.write8(+value);
- } else if (typeof value === "number") {
- bb.write8(2);
- bb.write32(value | 0);
- } else if (typeof value === "string") {
- bb.write8(3);
- bb.write(encodeUTF8(value));
- } else if (value instanceof Uint8Array) {
- bb.write8(4);
- bb.write(value);
- } else if (value instanceof Array) {
- bb.write8(5);
- bb.write32(value.length);
- for (let item of value) {
- visit(item);
- }
- } else {
- let keys = Object.keys(value);
- bb.write8(6);
- bb.write32(keys.length);
- for (let key of keys) {
- bb.write(encodeUTF8(key));
- visit(value[key]);
- }
- }
- };
- let bb = new ByteBuffer();
- bb.write32(0);
- bb.write32(packet.id << 1 | +!packet.isRequest);
- visit(packet.value);
- writeUInt32LE(bb.buf, bb.len - 4, 0);
- return bb.buf.subarray(0, bb.len);
-}
-function decodePacket(bytes) {
- let visit = () => {
- switch (bb.read8()) {
- case 0:
- return null;
- case 1:
- return !!bb.read8();
- case 2:
- return bb.read32();
- case 3:
- return decodeUTF8(bb.read());
- case 4:
- return bb.read();
- case 5: {
- let count = bb.read32();
- let value2 = [];
- for (let i = 0; i < count; i++) {
- value2.push(visit());
- }
- return value2;
- }
- case 6: {
- let count = bb.read32();
- let value2 = {};
- for (let i = 0; i < count; i++) {
- value2[decodeUTF8(bb.read())] = visit();
- }
- return value2;
- }
- default:
- throw new Error("Invalid packet");
- }
- };
- let bb = new ByteBuffer(bytes);
- let id = bb.read32();
- let isRequest = (id & 1) === 0;
- id >>>= 1;
- let value = visit();
- if (bb.ptr !== bytes.length) {
- throw new Error("Invalid packet");
- }
- return { id, isRequest, value };
-}
-var ByteBuffer = class {
- constructor(buf = new Uint8Array(1024)) {
- this.buf = buf;
- this.len = 0;
- this.ptr = 0;
- }
- _write(delta) {
- if (this.len + delta > this.buf.length) {
- let clone = new Uint8Array((this.len + delta) * 2);
- clone.set(this.buf);
- this.buf = clone;
- }
- this.len += delta;
- return this.len - delta;
- }
- write8(value) {
- let offset = this._write(1);
- this.buf[offset] = value;
- }
- write32(value) {
- let offset = this._write(4);
- writeUInt32LE(this.buf, value, offset);
- }
- write(bytes) {
- let offset = this._write(4 + bytes.length);
- writeUInt32LE(this.buf, bytes.length, offset);
- this.buf.set(bytes, offset + 4);
- }
- _read(delta) {
- if (this.ptr + delta > this.buf.length) {
- throw new Error("Invalid packet");
- }
- this.ptr += delta;
- return this.ptr - delta;
- }
- read8() {
- return this.buf[this._read(1)];
- }
- read32() {
- return readUInt32LE(this.buf, this._read(4));
- }
- read() {
- let length = this.read32();
- let bytes = new Uint8Array(length);
- let ptr = this._read(bytes.length);
- bytes.set(this.buf.subarray(ptr, ptr + length));
- return bytes;
- }
-};
-var encodeUTF8;
-var decodeUTF8;
-var encodeInvariant;
-if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
- let encoder = new TextEncoder();
- let decoder = new TextDecoder();
- encodeUTF8 = (text) => encoder.encode(text);
- decodeUTF8 = (bytes) => decoder.decode(bytes);
- encodeInvariant = 'new TextEncoder().encode("")';
-} else if (typeof Buffer !== "undefined") {
- encodeUTF8 = (text) => Buffer.from(text);
- decodeUTF8 = (bytes) => {
- let { buffer, byteOffset, byteLength } = bytes;
- return Buffer.from(buffer, byteOffset, byteLength).toString();
- };
- encodeInvariant = 'Buffer.from("")';
-} else {
- throw new Error("No UTF-8 codec found");
-}
-if (!(encodeUTF8("") instanceof Uint8Array))
- throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
-
-This indicates that your JavaScript environment is broken. You cannot use
-esbuild in this environment because esbuild relies on this invariant. This
-is not a problem with esbuild. You need to fix your environment instead.
-`);
-function readUInt32LE(buffer, offset) {
- return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
-}
-function writeUInt32LE(buffer, value, offset) {
- buffer[offset++] = value;
- buffer[offset++] = value >> 8;
- buffer[offset++] = value >> 16;
- buffer[offset++] = value >> 24;
-}
-
-// lib/shared/common.ts
-var quote = JSON.stringify;
-var buildLogLevelDefault = "warning";
-var transformLogLevelDefault = "silent";
-function validateAndJoinStringArray(values, what) {
- const toJoin = [];
- for (const value of values) {
- validateStringValue(value, what);
- if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
- toJoin.push(value);
- }
- return toJoin.join(",");
-}
-var canBeAnything = () => null;
-var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
-var mustBeString = (value) => typeof value === "string" ? null : "a string";
-var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
-var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
-var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
-var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
-var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
-var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
-var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
-var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
-var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
-var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
-var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
-var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
-var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
-var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
-var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
-function getFlag(object, keys, key, mustBeFn) {
- let value = object[key];
- keys[key + ""] = true;
- if (value === void 0) return void 0;
- let mustBe = mustBeFn(value);
- if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
- return value;
-}
-function checkForInvalidFlags(object, keys, where) {
- for (let key in object) {
- if (!(key in keys)) {
- throw new Error(`Invalid option ${where}: ${quote(key)}`);
- }
- }
-}
-function validateInitializeOptions(options) {
- let keys = /* @__PURE__ */ Object.create(null);
- let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
- let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
- let worker = getFlag(options, keys, "worker", mustBeBoolean);
- checkForInvalidFlags(options, keys, "in initialize() call");
- return {
- wasmURL,
- wasmModule,
- worker
- };
-}
-function validateMangleCache(mangleCache) {
- let validated;
- if (mangleCache !== void 0) {
- validated = /* @__PURE__ */ Object.create(null);
- for (let key in mangleCache) {
- let value = mangleCache[key];
- if (typeof value === "string" || value === false) {
- validated[key] = value;
- } else {
- throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
- }
- }
- }
- return validated;
-}
-function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
- let color = getFlag(options, keys, "color", mustBeBoolean);
- let logLevel = getFlag(options, keys, "logLevel", mustBeString);
- let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
- if (color !== void 0) flags.push(`--color=${color}`);
- else if (isTTY2) flags.push(`--color=true`);
- flags.push(`--log-level=${logLevel || logLevelDefault}`);
- flags.push(`--log-limit=${logLimit || 0}`);
-}
-function validateStringValue(value, what, key) {
- if (typeof value !== "string") {
- throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
- }
- return value;
-}
-function pushCommonFlags(flags, options, keys) {
- let legalComments = getFlag(options, keys, "legalComments", mustBeString);
- let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
- let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
- let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
- let format = getFlag(options, keys, "format", mustBeString);
- let globalName = getFlag(options, keys, "globalName", mustBeString);
- let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
- let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
- let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
- let minify = getFlag(options, keys, "minify", mustBeBoolean);
- let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
- let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
- let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
- let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
- let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
- let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
- let charset = getFlag(options, keys, "charset", mustBeString);
- let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
- let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
- let jsx = getFlag(options, keys, "jsx", mustBeString);
- let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
- let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
- let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
- let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
- let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
- let define = getFlag(options, keys, "define", mustBeObject);
- let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
- let supported = getFlag(options, keys, "supported", mustBeObject);
- let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
- let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
- let platform = getFlag(options, keys, "platform", mustBeString);
- let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
- let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
- if (legalComments) flags.push(`--legal-comments=${legalComments}`);
- if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
- if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
- if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
- if (format) flags.push(`--format=${format}`);
- if (globalName) flags.push(`--global-name=${globalName}`);
- if (platform) flags.push(`--platform=${platform}`);
- if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
- if (minify) flags.push("--minify");
- if (minifySyntax) flags.push("--minify-syntax");
- if (minifyWhitespace) flags.push("--minify-whitespace");
- if (minifyIdentifiers) flags.push("--minify-identifiers");
- if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
- if (charset) flags.push(`--charset=${charset}`);
- if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
- if (ignoreAnnotations) flags.push(`--ignore-annotations`);
- if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
- if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
- if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
- if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
- if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
- if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
- if (jsx) flags.push(`--jsx=${jsx}`);
- if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
- if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
- if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
- if (jsxDev) flags.push(`--jsx-dev`);
- if (jsxSideEffects) flags.push(`--jsx-side-effects`);
- if (define) {
- for (let key in define) {
- if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
- flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
- }
- }
- if (logOverride) {
- for (let key in logOverride) {
- if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
- flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
- }
- }
- if (supported) {
- for (let key in supported) {
- if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
- const value = supported[key];
- if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
- flags.push(`--supported:${key}=${value}`);
- }
- }
- if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
- if (keepNames) flags.push(`--keep-names`);
-}
-function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
- var _a2;
- let flags = [];
- let entries = [];
- let keys = /* @__PURE__ */ Object.create(null);
- let stdinContents = null;
- let stdinResolveDir = null;
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
- pushCommonFlags(flags, options, keys);
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
- let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
- let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
- let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
- let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
- let outfile = getFlag(options, keys, "outfile", mustBeString);
- let outdir = getFlag(options, keys, "outdir", mustBeString);
- let outbase = getFlag(options, keys, "outbase", mustBeString);
- let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
- let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
- let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
- let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
- let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
- let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
- let packages = getFlag(options, keys, "packages", mustBeString);
- let alias = getFlag(options, keys, "alias", mustBeObject);
- let loader = getFlag(options, keys, "loader", mustBeObject);
- let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
- let publicPath = getFlag(options, keys, "publicPath", mustBeString);
- let entryNames = getFlag(options, keys, "entryNames", mustBeString);
- let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
- let assetNames = getFlag(options, keys, "assetNames", mustBeString);
- let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
- let banner = getFlag(options, keys, "banner", mustBeObject);
- let footer = getFlag(options, keys, "footer", mustBeObject);
- let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
- let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
- let stdin = getFlag(options, keys, "stdin", mustBeObject);
- let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
- let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
- keys.plugins = true;
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
- if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
- if (bundle) flags.push("--bundle");
- if (allowOverwrite) flags.push("--allow-overwrite");
- if (splitting) flags.push("--splitting");
- if (preserveSymlinks) flags.push("--preserve-symlinks");
- if (metafile) flags.push(`--metafile`);
- if (outfile) flags.push(`--outfile=${outfile}`);
- if (outdir) flags.push(`--outdir=${outdir}`);
- if (outbase) flags.push(`--outbase=${outbase}`);
- if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
- if (packages) flags.push(`--packages=${packages}`);
- if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
- if (publicPath) flags.push(`--public-path=${publicPath}`);
- if (entryNames) flags.push(`--entry-names=${entryNames}`);
- if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
- if (assetNames) flags.push(`--asset-names=${assetNames}`);
- if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
- if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
- if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
- if (alias) {
- for (let old in alias) {
- if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
- flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
- }
- }
- if (banner) {
- for (let type in banner) {
- if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
- flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
- }
- }
- if (footer) {
- for (let type in footer) {
- if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
- flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
- }
- }
- if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
- if (loader) {
- for (let ext in loader) {
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
- flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
- }
- }
- if (outExtension) {
- for (let ext in outExtension) {
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
- flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
- }
- }
- if (entryPoints) {
- if (Array.isArray(entryPoints)) {
- for (let i = 0, n = entryPoints.length; i < n; i++) {
- let entryPoint = entryPoints[i];
- if (typeof entryPoint === "object" && entryPoint !== null) {
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
- if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
- if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
- entries.push([output, input]);
- } else {
- entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
- }
- }
- } else {
- for (let key in entryPoints) {
- entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
- }
- }
- }
- if (stdin) {
- let stdinKeys = /* @__PURE__ */ Object.create(null);
- let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
- let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
- let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
- let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
- checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
- if (loader2) flags.push(`--loader=${loader2}`);
- if (resolveDir) stdinResolveDir = resolveDir;
- if (typeof contents === "string") stdinContents = encodeUTF8(contents);
- else if (contents instanceof Uint8Array) stdinContents = contents;
- }
- let nodePaths = [];
- if (nodePathsInput) {
- for (let value of nodePathsInput) {
- value += "";
- nodePaths.push(value);
- }
- }
- return {
- entries,
- flags,
- write,
- stdinContents,
- stdinResolveDir,
- absWorkingDir,
- nodePaths,
- mangleCache: validateMangleCache(mangleCache)
- };
-}
-function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
- let flags = [];
- let keys = /* @__PURE__ */ Object.create(null);
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
- pushCommonFlags(flags, options, keys);
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
- let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
- let loader = getFlag(options, keys, "loader", mustBeString);
- let banner = getFlag(options, keys, "banner", mustBeString);
- let footer = getFlag(options, keys, "footer", mustBeString);
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
- if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
- if (loader) flags.push(`--loader=${loader}`);
- if (banner) flags.push(`--banner=${banner}`);
- if (footer) flags.push(`--footer=${footer}`);
- return {
- flags,
- mangleCache: validateMangleCache(mangleCache)
- };
-}
-function createChannel(streamIn) {
- const requestCallbacksByKey = {};
- const closeData = { didClose: false, reason: "" };
- let responseCallbacks = {};
- let nextRequestID = 0;
- let nextBuildKey = 0;
- let stdout = new Uint8Array(16 * 1024);
- let stdoutUsed = 0;
- let readFromStdout = (chunk) => {
- let limit = stdoutUsed + chunk.length;
- if (limit > stdout.length) {
- let swap = new Uint8Array(limit * 2);
- swap.set(stdout);
- stdout = swap;
- }
- stdout.set(chunk, stdoutUsed);
- stdoutUsed += chunk.length;
- let offset = 0;
- while (offset + 4 <= stdoutUsed) {
- let length = readUInt32LE(stdout, offset);
- if (offset + 4 + length > stdoutUsed) {
- break;
- }
- offset += 4;
- handleIncomingPacket(stdout.subarray(offset, offset + length));
- offset += length;
- }
- if (offset > 0) {
- stdout.copyWithin(0, offset, stdoutUsed);
- stdoutUsed -= offset;
- }
- };
- let afterClose = (error) => {
- closeData.didClose = true;
- if (error) closeData.reason = ": " + (error.message || error);
- const text = "The service was stopped" + closeData.reason;
- for (let id in responseCallbacks) {
- responseCallbacks[id](text, null);
- }
- responseCallbacks = {};
- };
- let sendRequest = (refs, value, callback) => {
- if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
- let id = nextRequestID++;
- responseCallbacks[id] = (error, response) => {
- try {
- callback(error, response);
- } finally {
- if (refs) refs.unref();
- }
- };
- if (refs) refs.ref();
- streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
- };
- let sendResponse = (id, value) => {
- if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
- streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
- };
- let handleRequest = async (id, request) => {
- try {
- if (request.command === "ping") {
- sendResponse(id, {});
- return;
- }
- if (typeof request.key === "number") {
- const requestCallbacks = requestCallbacksByKey[request.key];
- if (!requestCallbacks) {
- return;
- }
- const callback = requestCallbacks[request.command];
- if (callback) {
- await callback(id, request);
- return;
- }
- }
- throw new Error(`Invalid command: ` + request.command);
- } catch (e) {
- const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
- try {
- sendResponse(id, { errors });
- } catch {
- }
- }
- };
- let isFirstPacket = true;
- let handleIncomingPacket = (bytes) => {
- if (isFirstPacket) {
- isFirstPacket = false;
- let binaryVersion = String.fromCharCode(...bytes);
- if (binaryVersion !== "0.25.12") {
- throw new Error(`Cannot start service: Host version "${"0.25.12"}" does not match binary version ${quote(binaryVersion)}`);
- }
- return;
- }
- let packet = decodePacket(bytes);
- if (packet.isRequest) {
- handleRequest(packet.id, packet.value);
- } else {
- let callback = responseCallbacks[packet.id];
- delete responseCallbacks[packet.id];
- if (packet.value.error) callback(packet.value.error, {});
- else callback(null, packet.value);
- }
- };
- let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
- let refCount = 0;
- const buildKey = nextBuildKey++;
- const requestCallbacks = {};
- const buildRefs = {
- ref() {
- if (++refCount === 1) {
- if (refs) refs.ref();
- }
- },
- unref() {
- if (--refCount === 0) {
- delete requestCallbacksByKey[buildKey];
- if (refs) refs.unref();
- }
- }
- };
- requestCallbacksByKey[buildKey] = requestCallbacks;
- buildRefs.ref();
- buildOrContextImpl(
- callName,
- buildKey,
- sendRequest,
- sendResponse,
- buildRefs,
- streamIn,
- requestCallbacks,
- options,
- isTTY2,
- defaultWD2,
- (err, res) => {
- try {
- callback(err, res);
- } finally {
- buildRefs.unref();
- }
- }
- );
- };
- let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
- const details = createObjectStash();
- let start = (inputPath) => {
- try {
- if (typeof input !== "string" && !(input instanceof Uint8Array))
- throw new Error('The input to "transform" must be a string or a Uint8Array');
- let {
- flags,
- mangleCache
- } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
- let request = {
- command: "transform",
- flags,
- inputFS: inputPath !== null,
- input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
- };
- if (mangleCache) request.mangleCache = mangleCache;
- sendRequest(refs, request, (error, response) => {
- if (error) return callback(new Error(error), null);
- let errors = replaceDetailsInMessages(response.errors, details);
- let warnings = replaceDetailsInMessages(response.warnings, details);
- let outstanding = 1;
- let next = () => {
- if (--outstanding === 0) {
- let result = {
- warnings,
- code: response.code,
- map: response.map,
- mangleCache: void 0,
- legalComments: void 0
- };
- if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
- if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
- callback(null, result);
- }
- };
- if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
- if (response.codeFS) {
- outstanding++;
- fs3.readFile(response.code, (err, contents) => {
- if (err !== null) {
- callback(err, null);
- } else {
- response.code = contents;
- next();
- }
- });
- }
- if (response.mapFS) {
- outstanding++;
- fs3.readFile(response.map, (err, contents) => {
- if (err !== null) {
- callback(err, null);
- } else {
- response.map = contents;
- next();
- }
- });
- }
- next();
- });
- } catch (e) {
- let flags = [];
- try {
- pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
- } catch {
- }
- const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
- sendRequest(refs, { command: "error", flags, error }, () => {
- error.detail = details.load(error.detail);
- callback(failureErrorWithLog("Transform failed", [error], []), null);
- });
- }
- };
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
- let next = start;
- start = () => fs3.writeFile(input, next);
- }
- start(null);
- };
- let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
- if (!options) throw new Error(`Missing second argument in ${callName}() call`);
- let keys = {};
- let kind = getFlag(options, keys, "kind", mustBeString);
- let color = getFlag(options, keys, "color", mustBeBoolean);
- let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
- if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
- if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
- let request = {
- command: "format-msgs",
- messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
- isWarning: kind === "warning"
- };
- if (color !== void 0) request.color = color;
- if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
- sendRequest(refs, request, (error, response) => {
- if (error) return callback(new Error(error), null);
- callback(null, response.messages);
- });
- };
- let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
- if (options === void 0) options = {};
- let keys = {};
- let color = getFlag(options, keys, "color", mustBeBoolean);
- let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
- let request = {
- command: "analyze-metafile",
- metafile
- };
- if (color !== void 0) request.color = color;
- if (verbose !== void 0) request.verbose = verbose;
- sendRequest(refs, request, (error, response) => {
- if (error) return callback(new Error(error), null);
- callback(null, response.result);
- });
- };
- return {
- readFromStdout,
- afterClose,
- service: {
- buildOrContext,
- transform: transform2,
- formatMessages: formatMessages2,
- analyzeMetafile: analyzeMetafile2
- }
- };
-}
-function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
- const details = createObjectStash();
- const isContext = callName === "context";
- const handleError = (e, pluginName) => {
- const flags = [];
- try {
- pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
- } catch {
- }
- const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
- sendRequest(refs, { command: "error", flags, error: message }, () => {
- message.detail = details.load(message.detail);
- callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
- });
- };
- let plugins;
- if (typeof options === "object") {
- const value = options.plugins;
- if (value !== void 0) {
- if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
- plugins = value;
- }
- }
- if (plugins && plugins.length > 0) {
- if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
- handlePlugins(
- buildKey,
- sendRequest,
- sendResponse,
- refs,
- streamIn,
- requestCallbacks,
- options,
- plugins,
- details
- ).then(
- (result) => {
- if (!result.ok) return handleError(result.error, result.pluginName);
- try {
- buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
- } catch (e) {
- handleError(e, "");
- }
- },
- (e) => handleError(e, "")
- );
- return;
- }
- try {
- buildOrContextContinue(null, (result, done) => done([], []), () => {
- });
- } catch (e) {
- handleError(e, "");
- }
- function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
- const writeDefault = streamIn.hasFS;
- const {
- entries,
- flags,
- write,
- stdinContents,
- stdinResolveDir,
- absWorkingDir,
- nodePaths,
- mangleCache
- } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
- if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
- const request = {
- command: "build",
- key: buildKey,
- entries,
- flags,
- write,
- stdinContents,
- stdinResolveDir,
- absWorkingDir: absWorkingDir || defaultWD2,
- nodePaths,
- context: isContext
- };
- if (requestPlugins) request.plugins = requestPlugins;
- if (mangleCache) request.mangleCache = mangleCache;
- const buildResponseToResult = (response, callback2) => {
- const result = {
- errors: replaceDetailsInMessages(response.errors, details),
- warnings: replaceDetailsInMessages(response.warnings, details),
- outputFiles: void 0,
- metafile: void 0,
- mangleCache: void 0
- };
- const originalErrors = result.errors.slice();
- const originalWarnings = result.warnings.slice();
- if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
- if (response.metafile) result.metafile = JSON.parse(response.metafile);
- if (response.mangleCache) result.mangleCache = response.mangleCache;
- if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
- runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
- if (originalErrors.length > 0 || onEndErrors.length > 0) {
- const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
- return callback2(error, null, onEndErrors, onEndWarnings);
- }
- callback2(null, result, onEndErrors, onEndWarnings);
- });
- };
- let latestResultPromise;
- let provideLatestResult;
- if (isContext)
- requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
- buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
- const response = {
- errors: onEndErrors,
- warnings: onEndWarnings
- };
- if (provideLatestResult) provideLatestResult(err, result);
- latestResultPromise = void 0;
- provideLatestResult = void 0;
- sendResponse(id, response);
- resolve();
- });
- });
- sendRequest(refs, request, (error, response) => {
- if (error) return callback(new Error(error), null);
- if (!isContext) {
- return buildResponseToResult(response, (err, res) => {
- scheduleOnDisposeCallbacks();
- return callback(err, res);
- });
- }
- if (response.errors.length > 0) {
- return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
- }
- let didDispose = false;
- const result = {
- rebuild: () => {
- if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
- let settlePromise;
- provideLatestResult = (err, result2) => {
- if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
- };
- const triggerAnotherBuild = () => {
- const request2 = {
- command: "rebuild",
- key: buildKey
- };
- sendRequest(refs, request2, (error2, response2) => {
- if (error2) {
- reject(new Error(error2));
- } else if (settlePromise) {
- settlePromise();
- } else {
- triggerAnotherBuild();
- }
- });
- };
- triggerAnotherBuild();
- });
- return latestResultPromise;
- },
- watch: (options2 = {}) => new Promise((resolve, reject) => {
- if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
- const keys = {};
- const delay = getFlag(options2, keys, "delay", mustBeInteger);
- checkForInvalidFlags(options2, keys, `in watch() call`);
- const request2 = {
- command: "watch",
- key: buildKey
- };
- if (delay) request2.delay = delay;
- sendRequest(refs, request2, (error2) => {
- if (error2) reject(new Error(error2));
- else resolve(void 0);
- });
- }),
- serve: (options2 = {}) => new Promise((resolve, reject) => {
- if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
- const keys = {};
- const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
- const host = getFlag(options2, keys, "host", mustBeString);
- const servedir = getFlag(options2, keys, "servedir", mustBeString);
- const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
- const certfile = getFlag(options2, keys, "certfile", mustBeString);
- const fallback = getFlag(options2, keys, "fallback", mustBeString);
- const cors = getFlag(options2, keys, "cors", mustBeObject);
- const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
- checkForInvalidFlags(options2, keys, `in serve() call`);
- const request2 = {
- command: "serve",
- key: buildKey,
- onRequest: !!onRequest
- };
- if (port !== void 0) request2.port = port;
- if (host !== void 0) request2.host = host;
- if (servedir !== void 0) request2.servedir = servedir;
- if (keyfile !== void 0) request2.keyfile = keyfile;
- if (certfile !== void 0) request2.certfile = certfile;
- if (fallback !== void 0) request2.fallback = fallback;
- if (cors) {
- const corsKeys = {};
- const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
- checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
- if (Array.isArray(origin)) request2.corsOrigin = origin;
- else if (origin !== void 0) request2.corsOrigin = [origin];
- }
- sendRequest(refs, request2, (error2, response2) => {
- if (error2) return reject(new Error(error2));
- if (onRequest) {
- requestCallbacks["serve-request"] = (id, request3) => {
- onRequest(request3.args);
- sendResponse(id, {});
- };
- }
- resolve(response2);
- });
- }),
- cancel: () => new Promise((resolve) => {
- if (didDispose) return resolve();
- const request2 = {
- command: "cancel",
- key: buildKey
- };
- sendRequest(refs, request2, () => {
- resolve();
- });
- }),
- dispose: () => new Promise((resolve) => {
- if (didDispose) return resolve();
- didDispose = true;
- const request2 = {
- command: "dispose",
- key: buildKey
- };
- sendRequest(refs, request2, () => {
- resolve();
- scheduleOnDisposeCallbacks();
- refs.unref();
- });
- })
- };
- refs.ref();
- callback(null, result);
- });
- }
-}
-var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
- let onStartCallbacks = [];
- let onEndCallbacks = [];
- let onResolveCallbacks = {};
- let onLoadCallbacks = {};
- let onDisposeCallbacks = [];
- let nextCallbackID = 0;
- let i = 0;
- let requestPlugins = [];
- let isSetupDone = false;
- plugins = [...plugins];
- for (let item of plugins) {
- let keys = {};
- if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
- const name = getFlag(item, keys, "name", mustBeString);
- if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
- try {
- let setup = getFlag(item, keys, "setup", mustBeFunction);
- if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
- checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
- let plugin = {
- name,
- onStart: false,
- onEnd: false,
- onResolve: [],
- onLoad: []
- };
- i++;
- let resolve = (path3, options = {}) => {
- if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
- if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
- let keys2 = /* @__PURE__ */ Object.create(null);
- let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
- let importer = getFlag(options, keys2, "importer", mustBeString);
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
- let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
- let kind = getFlag(options, keys2, "kind", mustBeString);
- let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
- let importAttributes = getFlag(options, keys2, "with", mustBeObject);
- checkForInvalidFlags(options, keys2, "in resolve() call");
- return new Promise((resolve2, reject) => {
- const request = {
- command: "resolve",
- path: path3,
- key: buildKey,
- pluginName: name
- };
- if (pluginName != null) request.pluginName = pluginName;
- if (importer != null) request.importer = importer;
- if (namespace != null) request.namespace = namespace;
- if (resolveDir != null) request.resolveDir = resolveDir;
- if (kind != null) request.kind = kind;
- else throw new Error(`Must specify "kind" when calling "resolve"`);
- if (pluginData != null) request.pluginData = details.store(pluginData);
- if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
- sendRequest(refs, request, (error, response) => {
- if (error !== null) reject(new Error(error));
- else resolve2({
- errors: replaceDetailsInMessages(response.errors, details),
- warnings: replaceDetailsInMessages(response.warnings, details),
- path: response.path,
- external: response.external,
- sideEffects: response.sideEffects,
- namespace: response.namespace,
- suffix: response.suffix,
- pluginData: details.load(response.pluginData)
- });
- });
- });
- };
- let promise = setup({
- initialOptions,
- resolve,
- onStart(callback) {
- let registeredText = `This error came from the "onStart" callback registered here:`;
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
- onStartCallbacks.push({ name, callback, note: registeredNote });
- plugin.onStart = true;
- },
- onEnd(callback) {
- let registeredText = `This error came from the "onEnd" callback registered here:`;
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
- onEndCallbacks.push({ name, callback, note: registeredNote });
- plugin.onEnd = true;
- },
- onResolve(options, callback) {
- let registeredText = `This error came from the "onResolve" callback registered here:`;
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
- let keys2 = {};
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
- checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
- if (filter == null) throw new Error(`onResolve() call is missing a filter`);
- let id = nextCallbackID++;
- onResolveCallbacks[id] = { name, callback, note: registeredNote };
- plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
- },
- onLoad(options, callback) {
- let registeredText = `This error came from the "onLoad" callback registered here:`;
- let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
- let keys2 = {};
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
- checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
- if (filter == null) throw new Error(`onLoad() call is missing a filter`);
- let id = nextCallbackID++;
- onLoadCallbacks[id] = { name, callback, note: registeredNote };
- plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
- },
- onDispose(callback) {
- onDisposeCallbacks.push(callback);
- },
- esbuild: streamIn.esbuild
- });
- if (promise) await promise;
- requestPlugins.push(plugin);
- } catch (e) {
- return { ok: false, error: e, pluginName: name };
- }
- }
- requestCallbacks["on-start"] = async (id, request) => {
- details.clear();
- let response = { errors: [], warnings: [] };
- await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
- try {
- let result = await callback();
- if (result != null) {
- if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
- let keys = {};
- let errors = getFlag(result, keys, "errors", mustBeArray);
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
- checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
- if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
- if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
- }
- } catch (e) {
- response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
- }
- }));
- sendResponse(id, response);
- };
- requestCallbacks["on-resolve"] = async (id, request) => {
- let response = {}, name = "", callback, note;
- for (let id2 of request.ids) {
- try {
- ({ name, callback, note } = onResolveCallbacks[id2]);
- let result = await callback({
- path: request.path,
- importer: request.importer,
- namespace: request.namespace,
- resolveDir: request.resolveDir,
- kind: request.kind,
- pluginData: details.load(request.pluginData),
- with: request.with
- });
- if (result != null) {
- if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
- let keys = {};
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
- let path3 = getFlag(result, keys, "path", mustBeString);
- let namespace = getFlag(result, keys, "namespace", mustBeString);
- let suffix = getFlag(result, keys, "suffix", mustBeString);
- let external = getFlag(result, keys, "external", mustBeBoolean);
- let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
- let errors = getFlag(result, keys, "errors", mustBeArray);
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
- checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
- response.id = id2;
- if (pluginName != null) response.pluginName = pluginName;
- if (path3 != null) response.path = path3;
- if (namespace != null) response.namespace = namespace;
- if (suffix != null) response.suffix = suffix;
- if (external != null) response.external = external;
- if (sideEffects != null) response.sideEffects = sideEffects;
- if (pluginData != null) response.pluginData = details.store(pluginData);
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
- break;
- }
- } catch (e) {
- response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
- break;
- }
- }
- sendResponse(id, response);
- };
- requestCallbacks["on-load"] = async (id, request) => {
- let response = {}, name = "", callback, note;
- for (let id2 of request.ids) {
- try {
- ({ name, callback, note } = onLoadCallbacks[id2]);
- let result = await callback({
- path: request.path,
- namespace: request.namespace,
- suffix: request.suffix,
- pluginData: details.load(request.pluginData),
- with: request.with
- });
- if (result != null) {
- if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
- let keys = {};
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
- let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
- let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
- let loader = getFlag(result, keys, "loader", mustBeString);
- let errors = getFlag(result, keys, "errors", mustBeArray);
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
- checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
- response.id = id2;
- if (pluginName != null) response.pluginName = pluginName;
- if (contents instanceof Uint8Array) response.contents = contents;
- else if (contents != null) response.contents = encodeUTF8(contents);
- if (resolveDir != null) response.resolveDir = resolveDir;
- if (pluginData != null) response.pluginData = details.store(pluginData);
- if (loader != null) response.loader = loader;
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
- break;
- }
- } catch (e) {
- response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
- break;
- }
- }
- sendResponse(id, response);
- };
- let runOnEndCallbacks = (result, done) => done([], []);
- if (onEndCallbacks.length > 0) {
- runOnEndCallbacks = (result, done) => {
- (async () => {
- const onEndErrors = [];
- const onEndWarnings = [];
- for (const { name, callback, note } of onEndCallbacks) {
- let newErrors;
- let newWarnings;
- try {
- const value = await callback(result);
- if (value != null) {
- if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
- let keys = {};
- let errors = getFlag(value, keys, "errors", mustBeArray);
- let warnings = getFlag(value, keys, "warnings", mustBeArray);
- checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
- if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
- if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
- }
- } catch (e) {
- newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
- }
- if (newErrors) {
- onEndErrors.push(...newErrors);
- try {
- result.errors.push(...newErrors);
- } catch {
- }
- }
- if (newWarnings) {
- onEndWarnings.push(...newWarnings);
- try {
- result.warnings.push(...newWarnings);
- } catch {
- }
- }
- }
- done(onEndErrors, onEndWarnings);
- })();
- };
- }
- let scheduleOnDisposeCallbacks = () => {
- for (const cb of onDisposeCallbacks) {
- setTimeout(() => cb(), 0);
- }
- };
- isSetupDone = true;
- return {
- ok: true,
- requestPlugins,
- runOnEndCallbacks,
- scheduleOnDisposeCallbacks
- };
-};
-function createObjectStash() {
- const map = /* @__PURE__ */ new Map();
- let nextID = 0;
- return {
- clear() {
- map.clear();
- },
- load(id) {
- return map.get(id);
- },
- store(value) {
- if (value === void 0) return -1;
- const id = nextID++;
- map.set(id, value);
- return id;
- }
- };
-}
-function extractCallerV8(e, streamIn, ident) {
- let note;
- let tried = false;
- return () => {
- if (tried) return note;
- tried = true;
- try {
- let lines = (e.stack + "").split("\n");
- lines.splice(1, 1);
- let location = parseStackLinesV8(streamIn, lines, ident);
- if (location) {
- note = { text: e.message, location };
- return note;
- }
- } catch {
- }
- };
-}
-function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
- let text = "Internal error";
- let location = null;
- try {
- text = (e && e.message || e) + "";
- } catch {
- }
- try {
- location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
- } catch {
- }
- return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
-}
-function parseStackLinesV8(streamIn, lines, ident) {
- let at = " at ";
- if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
- for (let i = 1; i < lines.length; i++) {
- let line = lines[i];
- if (!line.startsWith(at)) continue;
- line = line.slice(at.length);
- while (true) {
- let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
- if (match) {
- line = match[1];
- continue;
- }
- match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
- if (match) {
- line = match[1];
- continue;
- }
- match = /^(\S+):(\d+):(\d+)$/.exec(line);
- if (match) {
- let contents;
- try {
- contents = streamIn.readFileSync(match[1], "utf8");
- } catch {
- break;
- }
- let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
- let column = +match[3] - 1;
- let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
- return {
- file: match[1],
- namespace: "file",
- line: +match[2],
- column: encodeUTF8(lineText.slice(0, column)).length,
- length: encodeUTF8(lineText.slice(column, column + length)).length,
- lineText: lineText + "\n" + lines.slice(1).join("\n"),
- suggestion: ""
- };
- }
- break;
- }
- }
- }
- return null;
-}
-function failureErrorWithLog(text, errors, warnings) {
- let limit = 5;
- text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
- if (i === limit) return "\n...";
- if (!e.location) return `
-error: ${e.text}`;
- let { file, line, column } = e.location;
- let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
- return `
-${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
- }).join("");
- let error = new Error(text);
- for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
- Object.defineProperty(error, key, {
- configurable: true,
- enumerable: true,
- get: () => value,
- set: (value2) => Object.defineProperty(error, key, {
- configurable: true,
- enumerable: true,
- value: value2
- })
- });
- }
- return error;
-}
-function replaceDetailsInMessages(messages, stash) {
- for (const message of messages) {
- message.detail = stash.load(message.detail);
- }
- return messages;
-}
-function sanitizeLocation(location, where, terminalWidth) {
- if (location == null) return null;
- let keys = {};
- let file = getFlag(location, keys, "file", mustBeString);
- let namespace = getFlag(location, keys, "namespace", mustBeString);
- let line = getFlag(location, keys, "line", mustBeInteger);
- let column = getFlag(location, keys, "column", mustBeInteger);
- let length = getFlag(location, keys, "length", mustBeInteger);
- let lineText = getFlag(location, keys, "lineText", mustBeString);
- let suggestion = getFlag(location, keys, "suggestion", mustBeString);
- checkForInvalidFlags(location, keys, where);
- if (lineText) {
- const relevantASCII = lineText.slice(
- 0,
- (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
- );
- if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
- lineText = relevantASCII;
- }
- }
- return {
- file: file || "",
- namespace: namespace || "",
- line: line || 0,
- column: column || 0,
- length: length || 0,
- lineText: lineText || "",
- suggestion: suggestion || ""
- };
-}
-function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
- let messagesClone = [];
- let index = 0;
- for (const message of messages) {
- let keys = {};
- let id = getFlag(message, keys, "id", mustBeString);
- let pluginName = getFlag(message, keys, "pluginName", mustBeString);
- let text = getFlag(message, keys, "text", mustBeString);
- let location = getFlag(message, keys, "location", mustBeObjectOrNull);
- let notes = getFlag(message, keys, "notes", mustBeArray);
- let detail = getFlag(message, keys, "detail", canBeAnything);
- let where = `in element ${index} of "${property}"`;
- checkForInvalidFlags(message, keys, where);
- let notesClone = [];
- if (notes) {
- for (const note of notes) {
- let noteKeys = {};
- let noteText = getFlag(note, noteKeys, "text", mustBeString);
- let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
- checkForInvalidFlags(note, noteKeys, where);
- notesClone.push({
- text: noteText || "",
- location: sanitizeLocation(noteLocation, where, terminalWidth)
- });
- }
- }
- messagesClone.push({
- id: id || "",
- pluginName: pluginName || fallbackPluginName,
- text: text || "",
- location: sanitizeLocation(location, where, terminalWidth),
- notes: notesClone,
- detail: stash ? stash.store(detail) : -1
- });
- index++;
- }
- return messagesClone;
-}
-function sanitizeStringArray(values, property) {
- const result = [];
- for (const value of values) {
- if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
- result.push(value);
- }
- return result;
-}
-function sanitizeStringMap(map, property) {
- const result = /* @__PURE__ */ Object.create(null);
- for (const key in map) {
- const value = map[key];
- if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
- result[key] = value;
- }
- return result;
-}
-function convertOutputFiles({ path: path3, contents, hash }) {
- let text = null;
- return {
- path: path3,
- contents,
- hash,
- get text() {
- const binary = this.contents;
- if (text === null || binary !== contents) {
- contents = binary;
- text = decodeUTF8(binary);
- }
- return text;
- }
- };
-}
-function jsRegExpToGoRegExp(regexp) {
- let result = regexp.source;
- if (regexp.flags) result = `(?${regexp.flags})${result}`;
- return result;
-}
-
-// lib/npm/node-platform.ts
-var fs = require("fs");
-var os = require("os");
-var path = require("path");
-var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
-var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
-var packageDarwin_arm64 = "@esbuild/darwin-arm64";
-var packageDarwin_x64 = "@esbuild/darwin-x64";
-var knownWindowsPackages = {
- "win32 arm64 LE": "@esbuild/win32-arm64",
- "win32 ia32 LE": "@esbuild/win32-ia32",
- "win32 x64 LE": "@esbuild/win32-x64"
-};
-var knownUnixlikePackages = {
- "aix ppc64 BE": "@esbuild/aix-ppc64",
- "android arm64 LE": "@esbuild/android-arm64",
- "darwin arm64 LE": "@esbuild/darwin-arm64",
- "darwin x64 LE": "@esbuild/darwin-x64",
- "freebsd arm64 LE": "@esbuild/freebsd-arm64",
- "freebsd x64 LE": "@esbuild/freebsd-x64",
- "linux arm LE": "@esbuild/linux-arm",
- "linux arm64 LE": "@esbuild/linux-arm64",
- "linux ia32 LE": "@esbuild/linux-ia32",
- "linux mips64el LE": "@esbuild/linux-mips64el",
- "linux ppc64 LE": "@esbuild/linux-ppc64",
- "linux riscv64 LE": "@esbuild/linux-riscv64",
- "linux s390x BE": "@esbuild/linux-s390x",
- "linux x64 LE": "@esbuild/linux-x64",
- "linux loong64 LE": "@esbuild/linux-loong64",
- "netbsd arm64 LE": "@esbuild/netbsd-arm64",
- "netbsd x64 LE": "@esbuild/netbsd-x64",
- "openbsd arm64 LE": "@esbuild/openbsd-arm64",
- "openbsd x64 LE": "@esbuild/openbsd-x64",
- "sunos x64 LE": "@esbuild/sunos-x64"
-};
-var knownWebAssemblyFallbackPackages = {
- "android arm LE": "@esbuild/android-arm",
- "android x64 LE": "@esbuild/android-x64",
- "openharmony arm64 LE": "@esbuild/openharmony-arm64"
-};
-function pkgAndSubpathForCurrentPlatform() {
- let pkg;
- let subpath;
- let isWASM = false;
- let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
- if (platformKey in knownWindowsPackages) {
- pkg = knownWindowsPackages[platformKey];
- subpath = "esbuild.exe";
- } else if (platformKey in knownUnixlikePackages) {
- pkg = knownUnixlikePackages[platformKey];
- subpath = "bin/esbuild";
- } else if (platformKey in knownWebAssemblyFallbackPackages) {
- pkg = knownWebAssemblyFallbackPackages[platformKey];
- subpath = "bin/esbuild";
- isWASM = true;
- } else {
- throw new Error(`Unsupported platform: ${platformKey}`);
- }
- return { pkg, subpath, isWASM };
-}
-function pkgForSomeOtherPlatform() {
- const libMainJS = require.resolve("esbuild");
- const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
- if (path.basename(nodeModulesDirectory) === "node_modules") {
- for (const unixKey in knownUnixlikePackages) {
- try {
- const pkg = knownUnixlikePackages[unixKey];
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
- } catch {
- }
- }
- for (const windowsKey in knownWindowsPackages) {
- try {
- const pkg = knownWindowsPackages[windowsKey];
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
- } catch {
- }
- }
- }
- return null;
-}
-function downloadedBinPath(pkg, subpath) {
- const esbuildLibDir = path.dirname(require.resolve("esbuild"));
- return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
-}
-function generateBinPath() {
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
- if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
- console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
- } else {
- return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
- }
- }
- const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
- let binPath;
- try {
- binPath = require.resolve(`${pkg}/${subpath}`);
- } catch (e) {
- binPath = downloadedBinPath(pkg, subpath);
- if (!fs.existsSync(binPath)) {
- try {
- require.resolve(pkg);
- } catch {
- const otherPkg = pkgForSomeOtherPlatform();
- if (otherPkg) {
- let suggestions = `
-Specifically the "${otherPkg}" package is present but this platform
-needs the "${pkg}" package instead. People often get into this
-situation by installing esbuild on Windows or macOS and copying "node_modules"
-into a Docker image that runs Linux, or by copying "node_modules" between
-Windows and WSL environments.
-
-If you are installing with npm, you can try not copying the "node_modules"
-directory when you copy the files over, and running "npm ci" or "npm install"
-on the destination platform after the copy. Or you could consider using yarn
-instead of npm which has built-in support for installing a package on multiple
-platforms simultaneously.
-
-If you are installing with yarn, you can try listing both this platform and the
-other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
-feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
-Keep in mind that this means multiple copies of esbuild will be present.
-`;
- if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
- suggestions = `
-Specifically the "${otherPkg}" package is present but this platform
-needs the "${pkg}" package instead. People often get into this
-situation by installing esbuild with npm running inside of Rosetta 2 and then
-trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
-2 is Apple's on-the-fly x86_64-to-arm64 translation service).
-
-If you are installing with npm, you can try ensuring that both npm and node are
-not running under Rosetta 2 and then reinstalling esbuild. This likely involves
-changing how you installed npm and/or node. For example, installing node with
-the universal installer here should work: https://nodejs.org/en/download/. Or
-you could consider using yarn instead of npm which has built-in support for
-installing a package on multiple platforms simultaneously.
-
-If you are installing with yarn, you can try listing both "arm64" and "x64"
-in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
-https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
-Keep in mind that this means multiple copies of esbuild will be present.
-`;
- }
- throw new Error(`
-You installed esbuild for another platform than the one you're currently using.
-This won't work because esbuild is written with native code and needs to
-install a platform-specific binary executable.
-${suggestions}
-Another alternative is to use the "esbuild-wasm" package instead, which works
-the same way on all platforms. But it comes with a heavy performance cost and
-can sometimes be 10x slower than the "esbuild" package, so you may also not
-want to do that.
-`);
- }
- throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
-
-If you are installing esbuild with npm, make sure that you don't specify the
-"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
-of "package.json" is used by esbuild to install the correct binary executable
-for your current platform.`);
- }
- throw e;
- }
- }
- if (/\.zip\//.test(binPath)) {
- let pnpapi;
- try {
- pnpapi = require("pnpapi");
- } catch (e) {
- }
- if (pnpapi) {
- const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
- const binTargetPath = path.join(
- root,
- "node_modules",
- ".cache",
- "esbuild",
- `pnpapi-${pkg.replace("/", "-")}-${"0.25.12"}-${path.basename(subpath)}`
- );
- if (!fs.existsSync(binTargetPath)) {
- fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
- fs.copyFileSync(binPath, binTargetPath);
- fs.chmodSync(binTargetPath, 493);
- }
- return { binPath: binTargetPath, isWASM };
- }
- }
- return { binPath, isWASM };
-}
-
-// lib/npm/node.ts
-var child_process = require("child_process");
-var crypto = require("crypto");
-var path2 = require("path");
-var fs2 = require("fs");
-var os2 = require("os");
-var tty = require("tty");
-var worker_threads;
-if (process.env.ESBUILD_WORKER_THREADS !== "0") {
- try {
- worker_threads = require("worker_threads");
- } catch {
- }
- let [major, minor] = process.versions.node.split(".");
- if (
- // {
- if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
- throw new Error(
- `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
-
-More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`
- );
- }
- if (false) {
- return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]];
- } else {
- const { binPath, isWASM } = generateBinPath();
- if (isWASM) {
- return ["node", [binPath]];
- } else {
- return [binPath, []];
- }
- }
-};
-var isTTY = () => tty.isatty(2);
-var fsSync = {
- readFile(tempFile, callback) {
- try {
- let contents = fs2.readFileSync(tempFile, "utf8");
- try {
- fs2.unlinkSync(tempFile);
- } catch {
- }
- callback(null, contents);
- } catch (err) {
- callback(err, null);
- }
- },
- writeFile(contents, callback) {
- try {
- let tempFile = randomFileName();
- fs2.writeFileSync(tempFile, contents);
- callback(tempFile);
- } catch {
- callback(null);
- }
- }
-};
-var fsAsync = {
- readFile(tempFile, callback) {
- try {
- fs2.readFile(tempFile, "utf8", (err, contents) => {
- try {
- fs2.unlink(tempFile, () => callback(err, contents));
- } catch {
- callback(err, contents);
- }
- });
- } catch (err) {
- callback(err, null);
- }
- },
- writeFile(contents, callback) {
- try {
- let tempFile = randomFileName();
- fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
- } catch {
- callback(null);
- }
- }
-};
-var version = "0.25.12";
-var build = (options) => ensureServiceIsRunning().build(options);
-var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
-var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
-var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
-var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
-var buildSync = (options) => {
- if (worker_threads && !isInternalWorkerThread) {
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
- return workerThreadService.buildSync(options);
- }
- let result;
- runServiceSync((service) => service.buildOrContext({
- callName: "buildSync",
- refs: null,
- options,
- isTTY: isTTY(),
- defaultWD,
- callback: (err, res) => {
- if (err) throw err;
- result = res;
- }
- }));
- return result;
-};
-var transformSync = (input, options) => {
- if (worker_threads && !isInternalWorkerThread) {
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
- return workerThreadService.transformSync(input, options);
- }
- let result;
- runServiceSync((service) => service.transform({
- callName: "transformSync",
- refs: null,
- input,
- options: options || {},
- isTTY: isTTY(),
- fs: fsSync,
- callback: (err, res) => {
- if (err) throw err;
- result = res;
- }
- }));
- return result;
-};
-var formatMessagesSync = (messages, options) => {
- if (worker_threads && !isInternalWorkerThread) {
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
- return workerThreadService.formatMessagesSync(messages, options);
- }
- let result;
- runServiceSync((service) => service.formatMessages({
- callName: "formatMessagesSync",
- refs: null,
- messages,
- options,
- callback: (err, res) => {
- if (err) throw err;
- result = res;
- }
- }));
- return result;
-};
-var analyzeMetafileSync = (metafile, options) => {
- if (worker_threads && !isInternalWorkerThread) {
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
- return workerThreadService.analyzeMetafileSync(metafile, options);
- }
- let result;
- runServiceSync((service) => service.analyzeMetafile({
- callName: "analyzeMetafileSync",
- refs: null,
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
- options,
- callback: (err, res) => {
- if (err) throw err;
- result = res;
- }
- }));
- return result;
-};
-var stop = () => {
- if (stopService) stopService();
- if (workerThreadService) workerThreadService.stop();
- return Promise.resolve();
-};
-var initializeWasCalled = false;
-var initialize = (options) => {
- options = validateInitializeOptions(options || {});
- if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
- if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
- if (options.worker) throw new Error(`The "worker" option only works in the browser`);
- if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
- ensureServiceIsRunning();
- initializeWasCalled = true;
- return Promise.resolve();
-};
-var defaultWD = process.cwd();
-var longLivedService;
-var stopService;
-var ensureServiceIsRunning = () => {
- if (longLivedService) return longLivedService;
- let [command, args] = esbuildCommandAndArgs();
- let child = child_process.spawn(command, args.concat(`--service=${"0.25.12"}`, "--ping"), {
- windowsHide: true,
- stdio: ["pipe", "pipe", "inherit"],
- cwd: defaultWD
- });
- let { readFromStdout, afterClose, service } = createChannel({
- writeToStdin(bytes) {
- child.stdin.write(bytes, (err) => {
- if (err) afterClose(err);
- });
- },
- readFileSync: fs2.readFileSync,
- isSync: false,
- hasFS: true,
- esbuild: node_exports
- });
- child.stdin.on("error", afterClose);
- child.on("error", afterClose);
- const stdin = child.stdin;
- const stdout = child.stdout;
- stdout.on("data", readFromStdout);
- stdout.on("end", afterClose);
- stopService = () => {
- stdin.destroy();
- stdout.destroy();
- child.kill();
- initializeWasCalled = false;
- longLivedService = void 0;
- stopService = void 0;
- };
- let refCount = 0;
- child.unref();
- if (stdin.unref) {
- stdin.unref();
- }
- if (stdout.unref) {
- stdout.unref();
- }
- const refs = {
- ref() {
- if (++refCount === 1) child.ref();
- },
- unref() {
- if (--refCount === 0) child.unref();
- }
- };
- longLivedService = {
- build: (options) => new Promise((resolve, reject) => {
- service.buildOrContext({
- callName: "build",
- refs,
- options,
- isTTY: isTTY(),
- defaultWD,
- callback: (err, res) => err ? reject(err) : resolve(res)
- });
- }),
- context: (options) => new Promise((resolve, reject) => service.buildOrContext({
- callName: "context",
- refs,
- options,
- isTTY: isTTY(),
- defaultWD,
- callback: (err, res) => err ? reject(err) : resolve(res)
- })),
- transform: (input, options) => new Promise((resolve, reject) => service.transform({
- callName: "transform",
- refs,
- input,
- options: options || {},
- isTTY: isTTY(),
- fs: fsAsync,
- callback: (err, res) => err ? reject(err) : resolve(res)
- })),
- formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
- callName: "formatMessages",
- refs,
- messages,
- options,
- callback: (err, res) => err ? reject(err) : resolve(res)
- })),
- analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
- callName: "analyzeMetafile",
- refs,
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
- options,
- callback: (err, res) => err ? reject(err) : resolve(res)
- }))
- };
- return longLivedService;
-};
-var runServiceSync = (callback) => {
- let [command, args] = esbuildCommandAndArgs();
- let stdin = new Uint8Array();
- let { readFromStdout, afterClose, service } = createChannel({
- writeToStdin(bytes) {
- if (stdin.length !== 0) throw new Error("Must run at most one command");
- stdin = bytes;
- },
- isSync: true,
- hasFS: true,
- esbuild: node_exports
- });
- callback(service);
- let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.25.12"}`), {
- cwd: defaultWD,
- windowsHide: true,
- input: stdin,
- // We don't know how large the output could be. If it's too large, the
- // command will fail with ENOBUFS. Reserve 16mb for now since that feels
- // like it should be enough. Also allow overriding this with an environment
- // variable.
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
- });
- readFromStdout(stdout);
- afterClose(null);
-};
-var randomFileName = () => {
- return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
-};
-var workerThreadService = null;
-var startWorkerThreadService = (worker_threads2) => {
- let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
- let worker = new worker_threads2.Worker(__filename, {
- workerData: { workerPort, defaultWD, esbuildVersion: "0.25.12" },
- transferList: [workerPort],
- // From node's documentation: https://nodejs.org/api/worker_threads.html
- //
- // Take care when launching worker threads from preload scripts (scripts loaded
- // and run using the `-r` command line flag). Unless the `execArgv` option is
- // explicitly set, new Worker threads automatically inherit the command line flags
- // from the running process and will preload the same preload scripts as the main
- // thread. If the preload script unconditionally launches a worker thread, every
- // thread spawned will spawn another until the application crashes.
- //
- execArgv: []
- });
- let nextID = 0;
- let fakeBuildError = (text) => {
- let error = new Error(`Build failed with 1 error:
-error: ${text}`);
- let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
- error.errors = errors;
- error.warnings = [];
- return error;
- };
- let validateBuildSyncOptions = (options) => {
- if (!options) return;
- let plugins = options.plugins;
- if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
- };
- let applyProperties = (object, properties) => {
- for (let key in properties) {
- object[key] = properties[key];
- }
- };
- let runCallSync = (command, args) => {
- let id = nextID++;
- let sharedBuffer = new SharedArrayBuffer(8);
- let sharedBufferView = new Int32Array(sharedBuffer);
- let msg = { sharedBuffer, id, command, args };
- worker.postMessage(msg);
- let status = Atomics.wait(sharedBufferView, 0, 0);
- if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
- let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
- if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
- if (reject) {
- applyProperties(reject, properties);
- throw reject;
- }
- return resolve;
- };
- worker.unref();
- return {
- buildSync(options) {
- validateBuildSyncOptions(options);
- return runCallSync("build", [options]);
- },
- transformSync(input, options) {
- return runCallSync("transform", [input, options]);
- },
- formatMessagesSync(messages, options) {
- return runCallSync("formatMessages", [messages, options]);
- },
- analyzeMetafileSync(metafile, options) {
- return runCallSync("analyzeMetafile", [metafile, options]);
- },
- stop() {
- worker.terminate();
- workerThreadService = null;
- }
- };
-};
-var startSyncServiceWorker = () => {
- let workerPort = worker_threads.workerData.workerPort;
- let parentPort = worker_threads.parentPort;
- let extractProperties = (object) => {
- let properties = {};
- if (object && typeof object === "object") {
- for (let key in object) {
- properties[key] = object[key];
- }
- }
- return properties;
- };
- try {
- let service = ensureServiceIsRunning();
- defaultWD = worker_threads.workerData.defaultWD;
- parentPort.on("message", (msg) => {
- (async () => {
- let { sharedBuffer, id, command, args } = msg;
- let sharedBufferView = new Int32Array(sharedBuffer);
- try {
- switch (command) {
- case "build":
- workerPort.postMessage({ id, resolve: await service.build(args[0]) });
- break;
- case "transform":
- workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
- break;
- case "formatMessages":
- workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
- break;
- case "analyzeMetafile":
- workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
- break;
- default:
- throw new Error(`Invalid command: ${command}`);
- }
- } catch (reject) {
- workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
- }
- Atomics.add(sharedBufferView, 0, 1);
- Atomics.notify(sharedBufferView, 0, Infinity);
- })();
- });
- } catch (reject) {
- parentPort.on("message", (msg) => {
- let { sharedBuffer, id } = msg;
- let sharedBufferView = new Int32Array(sharedBuffer);
- workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
- Atomics.add(sharedBufferView, 0, 1);
- Atomics.notify(sharedBufferView, 0, Infinity);
- });
- }
-};
-if (isInternalWorkerThread) {
- startSyncServiceWorker();
-}
-var node_default = node_exports;
-// Annotate the CommonJS export names for ESM import in node:
-0 && (module.exports = {
- analyzeMetafile,
- analyzeMetafileSync,
- build,
- buildSync,
- context,
- formatMessages,
- formatMessagesSync,
- initialize,
- stop,
- transform,
- transformSync,
- version
-});
diff --git a/backend/dev-console/node_modules/esbuild/package.json b/backend/dev-console/node_modules/esbuild/package.json
deleted file mode 100644
index afe58fd..0000000
--- a/backend/dev-console/node_modules/esbuild/package.json
+++ /dev/null
@@ -1,49 +0,0 @@
-{
- "name": "esbuild",
- "version": "0.25.12",
- "description": "An extremely fast JavaScript and CSS bundler and minifier.",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/evanw/esbuild.git"
- },
- "scripts": {
- "postinstall": "node install.js"
- },
- "main": "lib/main.js",
- "types": "lib/main.d.ts",
- "engines": {
- "node": ">=18"
- },
- "bin": {
- "esbuild": "bin/esbuild"
- },
- "optionalDependencies": {
- "@esbuild/aix-ppc64": "0.25.12",
- "@esbuild/android-arm": "0.25.12",
- "@esbuild/android-arm64": "0.25.12",
- "@esbuild/android-x64": "0.25.12",
- "@esbuild/darwin-arm64": "0.25.12",
- "@esbuild/darwin-x64": "0.25.12",
- "@esbuild/freebsd-arm64": "0.25.12",
- "@esbuild/freebsd-x64": "0.25.12",
- "@esbuild/linux-arm": "0.25.12",
- "@esbuild/linux-arm64": "0.25.12",
- "@esbuild/linux-ia32": "0.25.12",
- "@esbuild/linux-loong64": "0.25.12",
- "@esbuild/linux-mips64el": "0.25.12",
- "@esbuild/linux-ppc64": "0.25.12",
- "@esbuild/linux-riscv64": "0.25.12",
- "@esbuild/linux-s390x": "0.25.12",
- "@esbuild/linux-x64": "0.25.12",
- "@esbuild/netbsd-arm64": "0.25.12",
- "@esbuild/netbsd-x64": "0.25.12",
- "@esbuild/openbsd-arm64": "0.25.12",
- "@esbuild/openbsd-x64": "0.25.12",
- "@esbuild/openharmony-arm64": "0.25.12",
- "@esbuild/sunos-x64": "0.25.12",
- "@esbuild/win32-arm64": "0.25.12",
- "@esbuild/win32-ia32": "0.25.12",
- "@esbuild/win32-x64": "0.25.12"
- },
- "license": "MIT"
-}
diff --git a/backend/dev-console/node_modules/fdir/LICENSE b/backend/dev-console/node_modules/fdir/LICENSE
deleted file mode 100644
index bb7fdee..0000000
--- a/backend/dev-console/node_modules/fdir/LICENSE
+++ /dev/null
@@ -1,7 +0,0 @@
-Copyright 2023 Abdullah Atta
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/backend/dev-console/node_modules/fdir/README.md b/backend/dev-console/node_modules/fdir/README.md
deleted file mode 100644
index 5c70530..0000000
--- a/backend/dev-console/node_modules/fdir/README.md
+++ /dev/null
@@ -1,91 +0,0 @@
-
-
-
-
The Fastest Directory Crawler & Globber for NodeJS
-
-
-
-
-
-
-
-
-
-
-
-
-⚡ **The Fastest:** Nothing similar (in the NodeJS world) beats `fdir` in speed. It can easily crawl a directory containing **1 million files in < 1 second.**
-
-💡 **Stupidly Easy:** `fdir` uses expressive Builder pattern to build the crawler increasing code readability.
-
-🤖 **Zero Dependencies\*:** `fdir` only uses NodeJS `fs` & `path` modules.
-
-🕺 **Astonishingly Small:** < 2KB in size gzipped & minified.
-
-🖮 **Hackable:** Extending `fdir` is extremely simple now that the new Builder API is here. Feel free to experiment around.
-
-_\* `picomatch` must be installed manually by the user to support globbing._
-
-## 🚄 Quickstart
-
-### Installation
-
-You can install using `npm`:
-
-```sh
-$ npm i fdir
-```
-
-or Yarn:
-
-```sh
-$ yarn add fdir
-```
-
-### Usage
-
-```ts
-import { fdir } from "fdir";
-
-// create the builder
-const api = new fdir().withFullPaths().crawl("path/to/dir");
-
-// get all files in a directory synchronously
-const files = api.sync();
-
-// or asynchronously
-api.withPromise().then((files) => {
- // do something with the result here.
-});
-```
-
-## Documentation:
-
-Documentation for all methods is available [here](/documentation.md).
-
-## 📊 Benchmarks:
-
-Please check the benchmark against the latest version [here](/BENCHMARKS.md).
-
-## 🙏Used by:
-
-`fdir` is downloaded over 200k+ times a week by projects around the world. Here's a list of some notable projects using `fdir` in production:
-
-> Note: if you think your project should be here, feel free to open an issue. Notable is anything with a considerable amount of GitHub stars.
-
-1. [rollup/plugins](https://github.com/rollup/plugins)
-2. [SuperchupuDev/tinyglobby](https://github.com/SuperchupuDev/tinyglobby)
-3. [pulumi/pulumi](https://github.com/pulumi/pulumi)
-4. [dotenvx/dotenvx](https://github.com/dotenvx/dotenvx)
-5. [mdn/yari](https://github.com/mdn/yari)
-6. [streetwriters/notesnook](https://github.com/streetwriters/notesnook)
-7. [imba/imba](https://github.com/imba/imba)
-8. [moroshko/react-scanner](https://github.com/moroshko/react-scanner)
-9. [netlify/build](https://github.com/netlify/build)
-10. [yassinedoghri/astro-i18next](https://github.com/yassinedoghri/astro-i18next)
-11. [selfrefactor/rambda](https://github.com/selfrefactor/rambda)
-12. [whyboris/Video-Hub-App](https://github.com/whyboris/Video-Hub-App)
-
-## 🦮 LICENSE
-
-Copyright © 2024 Abdullah Atta under MIT. [Read full text here.](https://github.com/thecodrr/fdir/raw/master/LICENSE)
diff --git a/backend/dev-console/node_modules/fdir/dist/index.cjs b/backend/dev-console/node_modules/fdir/dist/index.cjs
deleted file mode 100644
index 4868ffb..0000000
--- a/backend/dev-console/node_modules/fdir/dist/index.cjs
+++ /dev/null
@@ -1,588 +0,0 @@
-//#region rolldown:runtime
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
- key = keys[i];
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
- get: ((k) => from[k]).bind(null, key),
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
- });
- }
- return to;
-};
-var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
- value: mod,
- enumerable: true
-}) : target, mod));
-
-//#endregion
-const path = __toESM(require("path"));
-const fs = __toESM(require("fs"));
-
-//#region src/utils.ts
-function cleanPath(path$1) {
- let normalized = (0, path.normalize)(path$1);
- if (normalized.length > 1 && normalized[normalized.length - 1] === path.sep) normalized = normalized.substring(0, normalized.length - 1);
- return normalized;
-}
-const SLASHES_REGEX = /[\\/]/g;
-function convertSlashes(path$1, separator) {
- return path$1.replace(SLASHES_REGEX, separator);
-}
-const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
-function isRootDirectory(path$1) {
- return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
-}
-function normalizePath(path$1, options) {
- const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
- const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
- if (resolvePaths) path$1 = (0, path.resolve)(path$1);
- if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
- if (path$1 === ".") return "";
- const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
- return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
-}
-
-//#endregion
-//#region src/api/functions/join-path.ts
-function joinPathWithBasePath(filename, directoryPath) {
- return directoryPath + filename;
-}
-function joinPathWithRelativePath(root, options) {
- return function(filename, directoryPath) {
- const sameRoot = directoryPath.startsWith(root);
- if (sameRoot) return directoryPath.slice(root.length) + filename;
- else return convertSlashes((0, path.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
- };
-}
-function joinPath(filename) {
- return filename;
-}
-function joinDirectoryPath(filename, directoryPath, separator) {
- return directoryPath + filename + separator;
-}
-function build$7(root, options) {
- const { relativePaths, includeBasePath } = options;
- return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
-}
-
-//#endregion
-//#region src/api/functions/push-directory.ts
-function pushDirectoryWithRelativePath(root) {
- return function(directoryPath, paths) {
- paths.push(directoryPath.substring(root.length) || ".");
- };
-}
-function pushDirectoryFilterWithRelativePath(root) {
- return function(directoryPath, paths, filters) {
- const relativePath = directoryPath.substring(root.length) || ".";
- if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
- };
-}
-const pushDirectory = (directoryPath, paths) => {
- paths.push(directoryPath || ".");
-};
-const pushDirectoryFilter = (directoryPath, paths, filters) => {
- const path$1 = directoryPath || ".";
- if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
-};
-const empty$2 = () => {};
-function build$6(root, options) {
- const { includeDirs, filters, relativePaths } = options;
- if (!includeDirs) return empty$2;
- if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
- return filters && filters.length ? pushDirectoryFilter : pushDirectory;
-}
-
-//#endregion
-//#region src/api/functions/push-file.ts
-const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
- if (filters.every((filter) => filter(filename, false))) counts.files++;
-};
-const pushFileFilter = (filename, paths, _counts, filters) => {
- if (filters.every((filter) => filter(filename, false))) paths.push(filename);
-};
-const pushFileCount = (_filename, _paths, counts, _filters) => {
- counts.files++;
-};
-const pushFile = (filename, paths) => {
- paths.push(filename);
-};
-const empty$1 = () => {};
-function build$5(options) {
- const { excludeFiles, filters, onlyCounts } = options;
- if (excludeFiles) return empty$1;
- if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
- else if (onlyCounts) return pushFileCount;
- else return pushFile;
-}
-
-//#endregion
-//#region src/api/functions/get-array.ts
-const getArray = (paths) => {
- return paths;
-};
-const getArrayGroup = () => {
- return [""].slice(0, 0);
-};
-function build$4(options) {
- return options.group ? getArrayGroup : getArray;
-}
-
-//#endregion
-//#region src/api/functions/group-files.ts
-const groupFiles = (groups, directory, files) => {
- groups.push({
- directory,
- files,
- dir: directory
- });
-};
-const empty = () => {};
-function build$3(options) {
- return options.group ? groupFiles : empty;
-}
-
-//#endregion
-//#region src/api/functions/resolve-symlink.ts
-const resolveSymlinksAsync = function(path$1, state, callback$1) {
- const { queue, fs: fs$1, options: { suppressErrors } } = state;
- queue.enqueue();
- fs$1.realpath(path$1, (error, resolvedPath) => {
- if (error) return queue.dequeue(suppressErrors ? null : error, state);
- fs$1.stat(resolvedPath, (error$1, stat) => {
- if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
- if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
- callback$1(stat, resolvedPath);
- queue.dequeue(null, state);
- });
- });
-};
-const resolveSymlinks = function(path$1, state, callback$1) {
- const { queue, fs: fs$1, options: { suppressErrors } } = state;
- queue.enqueue();
- try {
- const resolvedPath = fs$1.realpathSync(path$1);
- const stat = fs$1.statSync(resolvedPath);
- if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
- callback$1(stat, resolvedPath);
- } catch (e) {
- if (!suppressErrors) throw e;
- }
-};
-function build$2(options, isSynchronous) {
- if (!options.resolveSymlinks || options.excludeSymlinks) return null;
- return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
-}
-function isRecursive(path$1, resolved, state) {
- if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
- let parent = (0, path.dirname)(path$1);
- let depth = 1;
- while (parent !== state.root && depth < 2) {
- const resolvedPath = state.symlinks.get(parent);
- const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
- if (isSameRoot) depth++;
- else parent = (0, path.dirname)(parent);
- }
- state.symlinks.set(path$1, resolved);
- return depth > 1;
-}
-function isRecursiveUsingRealPaths(resolved, state) {
- return state.visited.includes(resolved + state.options.pathSeparator);
-}
-
-//#endregion
-//#region src/api/functions/invoke-callback.ts
-const onlyCountsSync = (state) => {
- return state.counts;
-};
-const groupsSync = (state) => {
- return state.groups;
-};
-const defaultSync = (state) => {
- return state.paths;
-};
-const limitFilesSync = (state) => {
- return state.paths.slice(0, state.options.maxFiles);
-};
-const onlyCountsAsync = (state, error, callback$1) => {
- report(error, callback$1, state.counts, state.options.suppressErrors);
- return null;
-};
-const defaultAsync = (state, error, callback$1) => {
- report(error, callback$1, state.paths, state.options.suppressErrors);
- return null;
-};
-const limitFilesAsync = (state, error, callback$1) => {
- report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
- return null;
-};
-const groupsAsync = (state, error, callback$1) => {
- report(error, callback$1, state.groups, state.options.suppressErrors);
- return null;
-};
-function report(error, callback$1, output, suppressErrors) {
- if (error && !suppressErrors) callback$1(error, output);
- else callback$1(null, output);
-}
-function build$1(options, isSynchronous) {
- const { onlyCounts, group, maxFiles } = options;
- if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
- else if (group) return isSynchronous ? groupsSync : groupsAsync;
- else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
- else return isSynchronous ? defaultSync : defaultAsync;
-}
-
-//#endregion
-//#region src/api/functions/walk-directory.ts
-const readdirOpts = { withFileTypes: true };
-const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
- state.queue.enqueue();
- if (currentDepth < 0) return state.queue.dequeue(null, state);
- const { fs: fs$1 } = state;
- state.visited.push(crawlPath);
- state.counts.directories++;
- fs$1.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
- callback$1(entries, directoryPath, currentDepth);
- state.queue.dequeue(state.options.suppressErrors ? null : error, state);
- });
-};
-const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
- const { fs: fs$1 } = state;
- if (currentDepth < 0) return;
- state.visited.push(crawlPath);
- state.counts.directories++;
- let entries = [];
- try {
- entries = fs$1.readdirSync(crawlPath || ".", readdirOpts);
- } catch (e) {
- if (!state.options.suppressErrors) throw e;
- }
- callback$1(entries, directoryPath, currentDepth);
-};
-function build(isSynchronous) {
- return isSynchronous ? walkSync : walkAsync;
-}
-
-//#endregion
-//#region src/api/queue.ts
-/**
-* This is a custom stateless queue to track concurrent async fs calls.
-* It increments a counter whenever a call is queued and decrements it
-* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
-*/
-var Queue = class {
- count = 0;
- constructor(onQueueEmpty) {
- this.onQueueEmpty = onQueueEmpty;
- }
- enqueue() {
- this.count++;
- return this.count;
- }
- dequeue(error, output) {
- if (this.onQueueEmpty && (--this.count <= 0 || error)) {
- this.onQueueEmpty(error, output);
- if (error) {
- output.controller.abort();
- this.onQueueEmpty = void 0;
- }
- }
- }
-};
-
-//#endregion
-//#region src/api/counter.ts
-var Counter = class {
- _files = 0;
- _directories = 0;
- set files(num) {
- this._files = num;
- }
- get files() {
- return this._files;
- }
- set directories(num) {
- this._directories = num;
- }
- get directories() {
- return this._directories;
- }
- /**
- * @deprecated use `directories` instead
- */
- /* c8 ignore next 3 */
- get dirs() {
- return this._directories;
- }
-};
-
-//#endregion
-//#region src/api/aborter.ts
-/**
-* AbortController is not supported on Node 14 so we use this until we can drop
-* support for Node 14.
-*/
-var Aborter = class {
- aborted = false;
- abort() {
- this.aborted = true;
- }
-};
-
-//#endregion
-//#region src/api/walker.ts
-var Walker = class {
- root;
- isSynchronous;
- state;
- joinPath;
- pushDirectory;
- pushFile;
- getArray;
- groupFiles;
- resolveSymlink;
- walkDirectory;
- callbackInvoker;
- constructor(root, options, callback$1) {
- this.isSynchronous = !callback$1;
- this.callbackInvoker = build$1(options, this.isSynchronous);
- this.root = normalizePath(root, options);
- this.state = {
- root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
- paths: [""].slice(0, 0),
- groups: [],
- counts: new Counter(),
- options,
- queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
- symlinks: /* @__PURE__ */ new Map(),
- visited: [""].slice(0, 0),
- controller: new Aborter(),
- fs: options.fs || fs
- };
- this.joinPath = build$7(this.root, options);
- this.pushDirectory = build$6(this.root, options);
- this.pushFile = build$5(options);
- this.getArray = build$4(options);
- this.groupFiles = build$3(options);
- this.resolveSymlink = build$2(options, this.isSynchronous);
- this.walkDirectory = build(this.isSynchronous);
- }
- start() {
- this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
- this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
- return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
- }
- walk = (entries, directoryPath, depth) => {
- const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
- if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
- const files = this.getArray(this.state.paths);
- for (let i = 0; i < entries.length; ++i) {
- const entry = entries[i];
- if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
- const filename = this.joinPath(entry.name, directoryPath);
- this.pushFile(filename, files, this.state.counts, filters);
- } else if (entry.isDirectory()) {
- let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
- if (exclude && exclude(entry.name, path$1)) continue;
- this.pushDirectory(path$1, paths, filters);
- this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk);
- } else if (this.resolveSymlink && entry.isSymbolicLink()) {
- let path$1 = joinPathWithBasePath(entry.name, directoryPath);
- this.resolveSymlink(path$1, this.state, (stat, resolvedPath) => {
- if (stat.isDirectory()) {
- resolvedPath = normalizePath(resolvedPath, this.state.options);
- if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
- this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk);
- } else {
- resolvedPath = useRealPaths ? resolvedPath : path$1;
- const filename = (0, path.basename)(resolvedPath);
- const directoryPath$1 = normalizePath((0, path.dirname)(resolvedPath), this.state.options);
- resolvedPath = this.joinPath(filename, directoryPath$1);
- this.pushFile(resolvedPath, files, this.state.counts, filters);
- }
- });
- }
- }
- this.groupFiles(this.state.groups, directoryPath, files);
- };
-};
-
-//#endregion
-//#region src/api/async.ts
-function promise(root, options) {
- return new Promise((resolve$1, reject) => {
- callback(root, options, (err, output) => {
- if (err) return reject(err);
- resolve$1(output);
- });
- });
-}
-function callback(root, options, callback$1) {
- let walker = new Walker(root, options, callback$1);
- walker.start();
-}
-
-//#endregion
-//#region src/api/sync.ts
-function sync(root, options) {
- const walker = new Walker(root, options);
- return walker.start();
-}
-
-//#endregion
-//#region src/builder/api-builder.ts
-var APIBuilder = class {
- constructor(root, options) {
- this.root = root;
- this.options = options;
- }
- withPromise() {
- return promise(this.root, this.options);
- }
- withCallback(cb) {
- callback(this.root, this.options, cb);
- }
- sync() {
- return sync(this.root, this.options);
- }
-};
-
-//#endregion
-//#region src/builder/index.ts
-let pm = null;
-/* c8 ignore next 6 */
-try {
- require.resolve("picomatch");
- pm = require("picomatch");
-} catch {}
-var Builder = class {
- globCache = {};
- options = {
- maxDepth: Infinity,
- suppressErrors: true,
- pathSeparator: path.sep,
- filters: []
- };
- globFunction;
- constructor(options) {
- this.options = {
- ...this.options,
- ...options
- };
- this.globFunction = this.options.globFunction;
- }
- group() {
- this.options.group = true;
- return this;
- }
- withPathSeparator(separator) {
- this.options.pathSeparator = separator;
- return this;
- }
- withBasePath() {
- this.options.includeBasePath = true;
- return this;
- }
- withRelativePaths() {
- this.options.relativePaths = true;
- return this;
- }
- withDirs() {
- this.options.includeDirs = true;
- return this;
- }
- withMaxDepth(depth) {
- this.options.maxDepth = depth;
- return this;
- }
- withMaxFiles(limit) {
- this.options.maxFiles = limit;
- return this;
- }
- withFullPaths() {
- this.options.resolvePaths = true;
- this.options.includeBasePath = true;
- return this;
- }
- withErrors() {
- this.options.suppressErrors = false;
- return this;
- }
- withSymlinks({ resolvePaths = true } = {}) {
- this.options.resolveSymlinks = true;
- this.options.useRealPaths = resolvePaths;
- return this.withFullPaths();
- }
- withAbortSignal(signal) {
- this.options.signal = signal;
- return this;
- }
- normalize() {
- this.options.normalizePath = true;
- return this;
- }
- filter(predicate) {
- this.options.filters.push(predicate);
- return this;
- }
- onlyDirs() {
- this.options.excludeFiles = true;
- this.options.includeDirs = true;
- return this;
- }
- exclude(predicate) {
- this.options.exclude = predicate;
- return this;
- }
- onlyCounts() {
- this.options.onlyCounts = true;
- return this;
- }
- crawl(root) {
- return new APIBuilder(root || ".", this.options);
- }
- withGlobFunction(fn) {
- this.globFunction = fn;
- return this;
- }
- /**
- * @deprecated Pass options using the constructor instead:
- * ```ts
- * new fdir(options).crawl("/path/to/root");
- * ```
- * This method will be removed in v7.0
- */
- /* c8 ignore next 4 */
- crawlWithOptions(root, options) {
- this.options = {
- ...this.options,
- ...options
- };
- return new APIBuilder(root || ".", this.options);
- }
- glob(...patterns) {
- if (this.globFunction) return this.globWithOptions(patterns);
- return this.globWithOptions(patterns, ...[{ dot: true }]);
- }
- globWithOptions(patterns, ...options) {
- const globFn = this.globFunction || pm;
- /* c8 ignore next 5 */
- if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
- var isMatch = this.globCache[patterns.join("\0")];
- if (!isMatch) {
- isMatch = globFn(patterns, ...options);
- this.globCache[patterns.join("\0")] = isMatch;
- }
- this.options.filters.push((path$1) => isMatch(path$1));
- return this;
- }
-};
-
-//#endregion
-exports.fdir = Builder;
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/fdir/dist/index.d.cts b/backend/dev-console/node_modules/fdir/dist/index.d.cts
deleted file mode 100644
index f448ef5..0000000
--- a/backend/dev-console/node_modules/fdir/dist/index.d.cts
+++ /dev/null
@@ -1,155 +0,0 @@
-///
-import * as nativeFs from "fs";
-import picomatch from "picomatch";
-
-//#region src/api/aborter.d.ts
-/**
- * AbortController is not supported on Node 14 so we use this until we can drop
- * support for Node 14.
- */
-declare class Aborter {
- aborted: boolean;
- abort(): void;
-}
-//#endregion
-//#region src/api/queue.d.ts
-type OnQueueEmptyCallback = (error: Error | null, output: WalkerState) => void;
-/**
- * This is a custom stateless queue to track concurrent async fs calls.
- * It increments a counter whenever a call is queued and decrements it
- * as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
- */
-declare class Queue {
- private onQueueEmpty?;
- count: number;
- constructor(onQueueEmpty?: OnQueueEmptyCallback | undefined);
- enqueue(): number;
- dequeue(error: Error | null, output: WalkerState): void;
-}
-//#endregion
-//#region src/types.d.ts
-type Counts = {
- files: number;
- directories: number;
- /**
- * @deprecated use `directories` instead. Will be removed in v7.0.
- */
- dirs: number;
-};
-type Group = {
- directory: string;
- files: string[];
- /**
- * @deprecated use `directory` instead. Will be removed in v7.0.
- */
- dir: string;
-};
-type GroupOutput = Group[];
-type OnlyCountsOutput = Counts;
-type PathsOutput = string[];
-type Output = OnlyCountsOutput | PathsOutput | GroupOutput;
-type FSLike = {
- readdir: typeof nativeFs.readdir;
- readdirSync: typeof nativeFs.readdirSync;
- realpath: typeof nativeFs.realpath;
- realpathSync: typeof nativeFs.realpathSync;
- stat: typeof nativeFs.stat;
- statSync: typeof nativeFs.statSync;
-};
-type WalkerState = {
- root: string;
- paths: string[];
- groups: Group[];
- counts: Counts;
- options: Options;
- queue: Queue;
- controller: Aborter;
- fs: FSLike;
- symlinks: Map;
- visited: string[];
-};
-type ResultCallback = (error: Error | null, output: TOutput) => void;
-type FilterPredicate = (path: string, isDirectory: boolean) => boolean;
-type ExcludePredicate = (dirName: string, dirPath: string) => boolean;
-type PathSeparator = "/" | "\\";
-type Options = {
- includeBasePath?: boolean;
- includeDirs?: boolean;
- normalizePath?: boolean;
- maxDepth: number;
- maxFiles?: number;
- resolvePaths?: boolean;
- suppressErrors: boolean;
- group?: boolean;
- onlyCounts?: boolean;
- filters: FilterPredicate[];
- resolveSymlinks?: boolean;
- useRealPaths?: boolean;
- excludeFiles?: boolean;
- excludeSymlinks?: boolean;
- exclude?: ExcludePredicate;
- relativePaths?: boolean;
- pathSeparator: PathSeparator;
- signal?: AbortSignal;
- globFunction?: TGlobFunction;
- fs?: FSLike;
-};
-type GlobMatcher = (test: string) => boolean;
-type GlobFunction = (glob: string | string[], ...params: unknown[]) => GlobMatcher;
-type GlobParams = T extends ((globs: string | string[], ...params: infer TParams extends unknown[]) => GlobMatcher) ? TParams : [];
-//#endregion
-//#region src/builder/api-builder.d.ts
-declare class APIBuilder {
- private readonly root;
- private readonly options;
- constructor(root: string, options: Options);
- withPromise(): Promise;
- withCallback(cb: ResultCallback): void;
- sync(): TReturnType;
-}
-//#endregion
-//#region src/builder/index.d.ts
-declare class Builder {
- private readonly globCache;
- private options;
- private globFunction?;
- constructor(options?: Partial>);
- group(): Builder;
- withPathSeparator(separator: "/" | "\\"): this;
- withBasePath(): this;
- withRelativePaths(): this;
- withDirs(): this;
- withMaxDepth(depth: number): this;
- withMaxFiles(limit: number): this;
- withFullPaths(): this;
- withErrors(): this;
- withSymlinks({
- resolvePaths
- }?: {
- resolvePaths?: boolean | undefined;
- }): this;
- withAbortSignal(signal: AbortSignal): this;
- normalize(): this;
- filter(predicate: FilterPredicate): this;
- onlyDirs(): this;
- exclude(predicate: ExcludePredicate): this;
- onlyCounts(): Builder;
- crawl(root?: string): APIBuilder;
- withGlobFunction(fn: TFunc): Builder;
- /**
- * @deprecated Pass options using the constructor instead:
- * ```ts
- * new fdir(options).crawl("/path/to/root");
- * ```
- * This method will be removed in v7.0
- */
- crawlWithOptions(root: string, options: Partial>): APIBuilder;
- glob(...patterns: string[]): Builder;
- globWithOptions(patterns: string[]): Builder;
- globWithOptions(patterns: string[], ...options: GlobParams): Builder;
-}
-//#endregion
-//#region src/index.d.ts
-type Fdir = typeof Builder;
-//#endregion
-export { Counts, ExcludePredicate, FSLike, Fdir, FilterPredicate, GlobFunction, GlobMatcher, GlobParams, Group, GroupOutput, OnlyCountsOutput, Options, Output, PathSeparator, PathsOutput, ResultCallback, WalkerState, Builder as fdir };
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/fdir/dist/index.d.mts b/backend/dev-console/node_modules/fdir/dist/index.d.mts
deleted file mode 100644
index f448ef5..0000000
--- a/backend/dev-console/node_modules/fdir/dist/index.d.mts
+++ /dev/null
@@ -1,155 +0,0 @@
-///
-import * as nativeFs from "fs";
-import picomatch from "picomatch";
-
-//#region src/api/aborter.d.ts
-/**
- * AbortController is not supported on Node 14 so we use this until we can drop
- * support for Node 14.
- */
-declare class Aborter {
- aborted: boolean;
- abort(): void;
-}
-//#endregion
-//#region src/api/queue.d.ts
-type OnQueueEmptyCallback = (error: Error | null, output: WalkerState) => void;
-/**
- * This is a custom stateless queue to track concurrent async fs calls.
- * It increments a counter whenever a call is queued and decrements it
- * as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
- */
-declare class Queue {
- private onQueueEmpty?;
- count: number;
- constructor(onQueueEmpty?: OnQueueEmptyCallback | undefined);
- enqueue(): number;
- dequeue(error: Error | null, output: WalkerState): void;
-}
-//#endregion
-//#region src/types.d.ts
-type Counts = {
- files: number;
- directories: number;
- /**
- * @deprecated use `directories` instead. Will be removed in v7.0.
- */
- dirs: number;
-};
-type Group = {
- directory: string;
- files: string[];
- /**
- * @deprecated use `directory` instead. Will be removed in v7.0.
- */
- dir: string;
-};
-type GroupOutput = Group[];
-type OnlyCountsOutput = Counts;
-type PathsOutput = string[];
-type Output = OnlyCountsOutput | PathsOutput | GroupOutput;
-type FSLike = {
- readdir: typeof nativeFs.readdir;
- readdirSync: typeof nativeFs.readdirSync;
- realpath: typeof nativeFs.realpath;
- realpathSync: typeof nativeFs.realpathSync;
- stat: typeof nativeFs.stat;
- statSync: typeof nativeFs.statSync;
-};
-type WalkerState = {
- root: string;
- paths: string[];
- groups: Group[];
- counts: Counts;
- options: Options;
- queue: Queue;
- controller: Aborter;
- fs: FSLike;
- symlinks: Map;
- visited: string[];
-};
-type ResultCallback = (error: Error | null, output: TOutput) => void;
-type FilterPredicate = (path: string, isDirectory: boolean) => boolean;
-type ExcludePredicate = (dirName: string, dirPath: string) => boolean;
-type PathSeparator = "/" | "\\";
-type Options = {
- includeBasePath?: boolean;
- includeDirs?: boolean;
- normalizePath?: boolean;
- maxDepth: number;
- maxFiles?: number;
- resolvePaths?: boolean;
- suppressErrors: boolean;
- group?: boolean;
- onlyCounts?: boolean;
- filters: FilterPredicate[];
- resolveSymlinks?: boolean;
- useRealPaths?: boolean;
- excludeFiles?: boolean;
- excludeSymlinks?: boolean;
- exclude?: ExcludePredicate;
- relativePaths?: boolean;
- pathSeparator: PathSeparator;
- signal?: AbortSignal;
- globFunction?: TGlobFunction;
- fs?: FSLike;
-};
-type GlobMatcher = (test: string) => boolean;
-type GlobFunction = (glob: string | string[], ...params: unknown[]) => GlobMatcher;
-type GlobParams = T extends ((globs: string | string[], ...params: infer TParams extends unknown[]) => GlobMatcher) ? TParams : [];
-//#endregion
-//#region src/builder/api-builder.d.ts
-declare class APIBuilder {
- private readonly root;
- private readonly options;
- constructor(root: string, options: Options);
- withPromise(): Promise;
- withCallback(cb: ResultCallback): void;
- sync(): TReturnType;
-}
-//#endregion
-//#region src/builder/index.d.ts
-declare class Builder {
- private readonly globCache;
- private options;
- private globFunction?;
- constructor(options?: Partial>);
- group(): Builder;
- withPathSeparator(separator: "/" | "\\"): this;
- withBasePath(): this;
- withRelativePaths(): this;
- withDirs(): this;
- withMaxDepth(depth: number): this;
- withMaxFiles(limit: number): this;
- withFullPaths(): this;
- withErrors(): this;
- withSymlinks({
- resolvePaths
- }?: {
- resolvePaths?: boolean | undefined;
- }): this;
- withAbortSignal(signal: AbortSignal): this;
- normalize(): this;
- filter(predicate: FilterPredicate): this;
- onlyDirs(): this;
- exclude(predicate: ExcludePredicate): this;
- onlyCounts(): Builder;
- crawl(root?: string): APIBuilder;
- withGlobFunction(fn: TFunc): Builder;
- /**
- * @deprecated Pass options using the constructor instead:
- * ```ts
- * new fdir(options).crawl("/path/to/root");
- * ```
- * This method will be removed in v7.0
- */
- crawlWithOptions(root: string, options: Partial>): APIBuilder;
- glob(...patterns: string[]): Builder;
- globWithOptions(patterns: string[]): Builder;
- globWithOptions(patterns: string[], ...options: GlobParams): Builder;
-}
-//#endregion
-//#region src/index.d.ts
-type Fdir = typeof Builder;
-//#endregion
-export { Counts, ExcludePredicate, FSLike, Fdir, FilterPredicate, GlobFunction, GlobMatcher, GlobParams, Group, GroupOutput, OnlyCountsOutput, Options, Output, PathSeparator, PathsOutput, ResultCallback, WalkerState, Builder as fdir };
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/fdir/dist/index.mjs b/backend/dev-console/node_modules/fdir/dist/index.mjs
deleted file mode 100644
index 5c37e09..0000000
--- a/backend/dev-console/node_modules/fdir/dist/index.mjs
+++ /dev/null
@@ -1,570 +0,0 @@
-import { createRequire } from "module";
-import { basename, dirname, normalize, relative, resolve, sep } from "path";
-import * as nativeFs from "fs";
-
-//#region rolldown:runtime
-var __require = /* @__PURE__ */ createRequire(import.meta.url);
-
-//#endregion
-//#region src/utils.ts
-function cleanPath(path) {
- let normalized = normalize(path);
- if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1);
- return normalized;
-}
-const SLASHES_REGEX = /[\\/]/g;
-function convertSlashes(path, separator) {
- return path.replace(SLASHES_REGEX, separator);
-}
-const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
-function isRootDirectory(path) {
- return path === "/" || WINDOWS_ROOT_DIR_REGEX.test(path);
-}
-function normalizePath(path, options) {
- const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
- const pathNeedsCleaning = process.platform === "win32" && path.includes("/") || path.startsWith(".");
- if (resolvePaths) path = resolve(path);
- if (normalizePath$1 || pathNeedsCleaning) path = cleanPath(path);
- if (path === ".") return "";
- const needsSeperator = path[path.length - 1] !== pathSeparator;
- return convertSlashes(needsSeperator ? path + pathSeparator : path, pathSeparator);
-}
-
-//#endregion
-//#region src/api/functions/join-path.ts
-function joinPathWithBasePath(filename, directoryPath) {
- return directoryPath + filename;
-}
-function joinPathWithRelativePath(root, options) {
- return function(filename, directoryPath) {
- const sameRoot = directoryPath.startsWith(root);
- if (sameRoot) return directoryPath.slice(root.length) + filename;
- else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
- };
-}
-function joinPath(filename) {
- return filename;
-}
-function joinDirectoryPath(filename, directoryPath, separator) {
- return directoryPath + filename + separator;
-}
-function build$7(root, options) {
- const { relativePaths, includeBasePath } = options;
- return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
-}
-
-//#endregion
-//#region src/api/functions/push-directory.ts
-function pushDirectoryWithRelativePath(root) {
- return function(directoryPath, paths) {
- paths.push(directoryPath.substring(root.length) || ".");
- };
-}
-function pushDirectoryFilterWithRelativePath(root) {
- return function(directoryPath, paths, filters) {
- const relativePath = directoryPath.substring(root.length) || ".";
- if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
- };
-}
-const pushDirectory = (directoryPath, paths) => {
- paths.push(directoryPath || ".");
-};
-const pushDirectoryFilter = (directoryPath, paths, filters) => {
- const path = directoryPath || ".";
- if (filters.every((filter) => filter(path, true))) paths.push(path);
-};
-const empty$2 = () => {};
-function build$6(root, options) {
- const { includeDirs, filters, relativePaths } = options;
- if (!includeDirs) return empty$2;
- if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
- return filters && filters.length ? pushDirectoryFilter : pushDirectory;
-}
-
-//#endregion
-//#region src/api/functions/push-file.ts
-const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
- if (filters.every((filter) => filter(filename, false))) counts.files++;
-};
-const pushFileFilter = (filename, paths, _counts, filters) => {
- if (filters.every((filter) => filter(filename, false))) paths.push(filename);
-};
-const pushFileCount = (_filename, _paths, counts, _filters) => {
- counts.files++;
-};
-const pushFile = (filename, paths) => {
- paths.push(filename);
-};
-const empty$1 = () => {};
-function build$5(options) {
- const { excludeFiles, filters, onlyCounts } = options;
- if (excludeFiles) return empty$1;
- if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
- else if (onlyCounts) return pushFileCount;
- else return pushFile;
-}
-
-//#endregion
-//#region src/api/functions/get-array.ts
-const getArray = (paths) => {
- return paths;
-};
-const getArrayGroup = () => {
- return [""].slice(0, 0);
-};
-function build$4(options) {
- return options.group ? getArrayGroup : getArray;
-}
-
-//#endregion
-//#region src/api/functions/group-files.ts
-const groupFiles = (groups, directory, files) => {
- groups.push({
- directory,
- files,
- dir: directory
- });
-};
-const empty = () => {};
-function build$3(options) {
- return options.group ? groupFiles : empty;
-}
-
-//#endregion
-//#region src/api/functions/resolve-symlink.ts
-const resolveSymlinksAsync = function(path, state, callback$1) {
- const { queue, fs, options: { suppressErrors } } = state;
- queue.enqueue();
- fs.realpath(path, (error, resolvedPath) => {
- if (error) return queue.dequeue(suppressErrors ? null : error, state);
- fs.stat(resolvedPath, (error$1, stat) => {
- if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
- if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return queue.dequeue(null, state);
- callback$1(stat, resolvedPath);
- queue.dequeue(null, state);
- });
- });
-};
-const resolveSymlinks = function(path, state, callback$1) {
- const { queue, fs, options: { suppressErrors } } = state;
- queue.enqueue();
- try {
- const resolvedPath = fs.realpathSync(path);
- const stat = fs.statSync(resolvedPath);
- if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return;
- callback$1(stat, resolvedPath);
- } catch (e) {
- if (!suppressErrors) throw e;
- }
-};
-function build$2(options, isSynchronous) {
- if (!options.resolveSymlinks || options.excludeSymlinks) return null;
- return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
-}
-function isRecursive(path, resolved, state) {
- if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
- let parent = dirname(path);
- let depth = 1;
- while (parent !== state.root && depth < 2) {
- const resolvedPath = state.symlinks.get(parent);
- const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
- if (isSameRoot) depth++;
- else parent = dirname(parent);
- }
- state.symlinks.set(path, resolved);
- return depth > 1;
-}
-function isRecursiveUsingRealPaths(resolved, state) {
- return state.visited.includes(resolved + state.options.pathSeparator);
-}
-
-//#endregion
-//#region src/api/functions/invoke-callback.ts
-const onlyCountsSync = (state) => {
- return state.counts;
-};
-const groupsSync = (state) => {
- return state.groups;
-};
-const defaultSync = (state) => {
- return state.paths;
-};
-const limitFilesSync = (state) => {
- return state.paths.slice(0, state.options.maxFiles);
-};
-const onlyCountsAsync = (state, error, callback$1) => {
- report(error, callback$1, state.counts, state.options.suppressErrors);
- return null;
-};
-const defaultAsync = (state, error, callback$1) => {
- report(error, callback$1, state.paths, state.options.suppressErrors);
- return null;
-};
-const limitFilesAsync = (state, error, callback$1) => {
- report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
- return null;
-};
-const groupsAsync = (state, error, callback$1) => {
- report(error, callback$1, state.groups, state.options.suppressErrors);
- return null;
-};
-function report(error, callback$1, output, suppressErrors) {
- if (error && !suppressErrors) callback$1(error, output);
- else callback$1(null, output);
-}
-function build$1(options, isSynchronous) {
- const { onlyCounts, group, maxFiles } = options;
- if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
- else if (group) return isSynchronous ? groupsSync : groupsAsync;
- else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
- else return isSynchronous ? defaultSync : defaultAsync;
-}
-
-//#endregion
-//#region src/api/functions/walk-directory.ts
-const readdirOpts = { withFileTypes: true };
-const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
- state.queue.enqueue();
- if (currentDepth < 0) return state.queue.dequeue(null, state);
- const { fs } = state;
- state.visited.push(crawlPath);
- state.counts.directories++;
- fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
- callback$1(entries, directoryPath, currentDepth);
- state.queue.dequeue(state.options.suppressErrors ? null : error, state);
- });
-};
-const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
- const { fs } = state;
- if (currentDepth < 0) return;
- state.visited.push(crawlPath);
- state.counts.directories++;
- let entries = [];
- try {
- entries = fs.readdirSync(crawlPath || ".", readdirOpts);
- } catch (e) {
- if (!state.options.suppressErrors) throw e;
- }
- callback$1(entries, directoryPath, currentDepth);
-};
-function build(isSynchronous) {
- return isSynchronous ? walkSync : walkAsync;
-}
-
-//#endregion
-//#region src/api/queue.ts
-/**
-* This is a custom stateless queue to track concurrent async fs calls.
-* It increments a counter whenever a call is queued and decrements it
-* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
-*/
-var Queue = class {
- count = 0;
- constructor(onQueueEmpty) {
- this.onQueueEmpty = onQueueEmpty;
- }
- enqueue() {
- this.count++;
- return this.count;
- }
- dequeue(error, output) {
- if (this.onQueueEmpty && (--this.count <= 0 || error)) {
- this.onQueueEmpty(error, output);
- if (error) {
- output.controller.abort();
- this.onQueueEmpty = void 0;
- }
- }
- }
-};
-
-//#endregion
-//#region src/api/counter.ts
-var Counter = class {
- _files = 0;
- _directories = 0;
- set files(num) {
- this._files = num;
- }
- get files() {
- return this._files;
- }
- set directories(num) {
- this._directories = num;
- }
- get directories() {
- return this._directories;
- }
- /**
- * @deprecated use `directories` instead
- */
- /* c8 ignore next 3 */
- get dirs() {
- return this._directories;
- }
-};
-
-//#endregion
-//#region src/api/aborter.ts
-/**
-* AbortController is not supported on Node 14 so we use this until we can drop
-* support for Node 14.
-*/
-var Aborter = class {
- aborted = false;
- abort() {
- this.aborted = true;
- }
-};
-
-//#endregion
-//#region src/api/walker.ts
-var Walker = class {
- root;
- isSynchronous;
- state;
- joinPath;
- pushDirectory;
- pushFile;
- getArray;
- groupFiles;
- resolveSymlink;
- walkDirectory;
- callbackInvoker;
- constructor(root, options, callback$1) {
- this.isSynchronous = !callback$1;
- this.callbackInvoker = build$1(options, this.isSynchronous);
- this.root = normalizePath(root, options);
- this.state = {
- root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
- paths: [""].slice(0, 0),
- groups: [],
- counts: new Counter(),
- options,
- queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
- symlinks: /* @__PURE__ */ new Map(),
- visited: [""].slice(0, 0),
- controller: new Aborter(),
- fs: options.fs || nativeFs
- };
- this.joinPath = build$7(this.root, options);
- this.pushDirectory = build$6(this.root, options);
- this.pushFile = build$5(options);
- this.getArray = build$4(options);
- this.groupFiles = build$3(options);
- this.resolveSymlink = build$2(options, this.isSynchronous);
- this.walkDirectory = build(this.isSynchronous);
- }
- start() {
- this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
- this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
- return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
- }
- walk = (entries, directoryPath, depth) => {
- const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
- if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
- const files = this.getArray(this.state.paths);
- for (let i = 0; i < entries.length; ++i) {
- const entry = entries[i];
- if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
- const filename = this.joinPath(entry.name, directoryPath);
- this.pushFile(filename, files, this.state.counts, filters);
- } else if (entry.isDirectory()) {
- let path = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
- if (exclude && exclude(entry.name, path)) continue;
- this.pushDirectory(path, paths, filters);
- this.walkDirectory(this.state, path, path, depth - 1, this.walk);
- } else if (this.resolveSymlink && entry.isSymbolicLink()) {
- let path = joinPathWithBasePath(entry.name, directoryPath);
- this.resolveSymlink(path, this.state, (stat, resolvedPath) => {
- if (stat.isDirectory()) {
- resolvedPath = normalizePath(resolvedPath, this.state.options);
- if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path + pathSeparator)) return;
- this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk);
- } else {
- resolvedPath = useRealPaths ? resolvedPath : path;
- const filename = basename(resolvedPath);
- const directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options);
- resolvedPath = this.joinPath(filename, directoryPath$1);
- this.pushFile(resolvedPath, files, this.state.counts, filters);
- }
- });
- }
- }
- this.groupFiles(this.state.groups, directoryPath, files);
- };
-};
-
-//#endregion
-//#region src/api/async.ts
-function promise(root, options) {
- return new Promise((resolve$1, reject) => {
- callback(root, options, (err, output) => {
- if (err) return reject(err);
- resolve$1(output);
- });
- });
-}
-function callback(root, options, callback$1) {
- let walker = new Walker(root, options, callback$1);
- walker.start();
-}
-
-//#endregion
-//#region src/api/sync.ts
-function sync(root, options) {
- const walker = new Walker(root, options);
- return walker.start();
-}
-
-//#endregion
-//#region src/builder/api-builder.ts
-var APIBuilder = class {
- constructor(root, options) {
- this.root = root;
- this.options = options;
- }
- withPromise() {
- return promise(this.root, this.options);
- }
- withCallback(cb) {
- callback(this.root, this.options, cb);
- }
- sync() {
- return sync(this.root, this.options);
- }
-};
-
-//#endregion
-//#region src/builder/index.ts
-let pm = null;
-/* c8 ignore next 6 */
-try {
- __require.resolve("picomatch");
- pm = __require("picomatch");
-} catch {}
-var Builder = class {
- globCache = {};
- options = {
- maxDepth: Infinity,
- suppressErrors: true,
- pathSeparator: sep,
- filters: []
- };
- globFunction;
- constructor(options) {
- this.options = {
- ...this.options,
- ...options
- };
- this.globFunction = this.options.globFunction;
- }
- group() {
- this.options.group = true;
- return this;
- }
- withPathSeparator(separator) {
- this.options.pathSeparator = separator;
- return this;
- }
- withBasePath() {
- this.options.includeBasePath = true;
- return this;
- }
- withRelativePaths() {
- this.options.relativePaths = true;
- return this;
- }
- withDirs() {
- this.options.includeDirs = true;
- return this;
- }
- withMaxDepth(depth) {
- this.options.maxDepth = depth;
- return this;
- }
- withMaxFiles(limit) {
- this.options.maxFiles = limit;
- return this;
- }
- withFullPaths() {
- this.options.resolvePaths = true;
- this.options.includeBasePath = true;
- return this;
- }
- withErrors() {
- this.options.suppressErrors = false;
- return this;
- }
- withSymlinks({ resolvePaths = true } = {}) {
- this.options.resolveSymlinks = true;
- this.options.useRealPaths = resolvePaths;
- return this.withFullPaths();
- }
- withAbortSignal(signal) {
- this.options.signal = signal;
- return this;
- }
- normalize() {
- this.options.normalizePath = true;
- return this;
- }
- filter(predicate) {
- this.options.filters.push(predicate);
- return this;
- }
- onlyDirs() {
- this.options.excludeFiles = true;
- this.options.includeDirs = true;
- return this;
- }
- exclude(predicate) {
- this.options.exclude = predicate;
- return this;
- }
- onlyCounts() {
- this.options.onlyCounts = true;
- return this;
- }
- crawl(root) {
- return new APIBuilder(root || ".", this.options);
- }
- withGlobFunction(fn) {
- this.globFunction = fn;
- return this;
- }
- /**
- * @deprecated Pass options using the constructor instead:
- * ```ts
- * new fdir(options).crawl("/path/to/root");
- * ```
- * This method will be removed in v7.0
- */
- /* c8 ignore next 4 */
- crawlWithOptions(root, options) {
- this.options = {
- ...this.options,
- ...options
- };
- return new APIBuilder(root || ".", this.options);
- }
- glob(...patterns) {
- if (this.globFunction) return this.globWithOptions(patterns);
- return this.globWithOptions(patterns, ...[{ dot: true }]);
- }
- globWithOptions(patterns, ...options) {
- const globFn = this.globFunction || pm;
- /* c8 ignore next 5 */
- if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
- var isMatch = this.globCache[patterns.join("\0")];
- if (!isMatch) {
- isMatch = globFn(patterns, ...options);
- this.globCache[patterns.join("\0")] = isMatch;
- }
- this.options.filters.push((path) => isMatch(path));
- return this;
- }
-};
-
-//#endregion
-export { Builder as fdir };
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/fdir/package.json b/backend/dev-console/node_modules/fdir/package.json
deleted file mode 100644
index e229dff..0000000
--- a/backend/dev-console/node_modules/fdir/package.json
+++ /dev/null
@@ -1,103 +0,0 @@
-{
- "name": "fdir",
- "version": "6.5.0",
- "description": "The fastest directory crawler & globbing alternative to glob, fast-glob, & tiny-glob. Crawls 1m files in < 1s",
- "main": "./dist/index.cjs",
- "types": "./dist/index.d.cts",
- "type": "module",
- "scripts": {
- "prepublishOnly": "npm run test && npm run build",
- "build": "tsdown",
- "format": "prettier --write src __tests__ benchmarks",
- "test": "vitest run __tests__/",
- "test:coverage": "vitest run --coverage __tests__/",
- "test:watch": "vitest __tests__/",
- "bench": "ts-node benchmarks/benchmark.js",
- "bench:glob": "ts-node benchmarks/glob-benchmark.ts",
- "bench:fdir": "ts-node benchmarks/fdir-benchmark.ts",
- "release": "./scripts/release.sh"
- },
- "engines": {
- "node": ">=12.0.0"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/thecodrr/fdir.git"
- },
- "keywords": [
- "util",
- "os",
- "sys",
- "fs",
- "walk",
- "crawler",
- "directory",
- "files",
- "io",
- "tiny-glob",
- "glob",
- "fast-glob",
- "speed",
- "javascript",
- "nodejs"
- ],
- "author": "thecodrr ",
- "license": "MIT",
- "bugs": {
- "url": "https://github.com/thecodrr/fdir/issues"
- },
- "homepage": "https://github.com/thecodrr/fdir#readme",
- "devDependencies": {
- "@types/glob": "^8.1.0",
- "@types/mock-fs": "^4.13.4",
- "@types/node": "^20.9.4",
- "@types/picomatch": "^4.0.0",
- "@types/tap": "^15.0.11",
- "@vitest/coverage-v8": "^0.34.6",
- "all-files-in-tree": "^1.1.2",
- "benny": "^3.7.1",
- "csv-to-markdown-table": "^1.3.1",
- "expect": "^29.7.0",
- "fast-glob": "^3.3.2",
- "fdir1": "npm:fdir@1.2.0",
- "fdir2": "npm:fdir@2.1.0",
- "fdir3": "npm:fdir@3.4.2",
- "fdir4": "npm:fdir@4.1.0",
- "fdir5": "npm:fdir@5.0.0",
- "fs-readdir-recursive": "^1.1.0",
- "get-all-files": "^4.1.0",
- "glob": "^10.3.10",
- "klaw-sync": "^6.0.0",
- "mock-fs": "^5.2.0",
- "picomatch": "^4.0.2",
- "prettier": "^3.5.3",
- "recur-readdir": "0.0.1",
- "recursive-files": "^1.0.2",
- "recursive-fs": "^2.1.0",
- "recursive-readdir": "^2.2.3",
- "rrdir": "^12.1.0",
- "systeminformation": "^5.21.17",
- "tiny-glob": "^0.2.9",
- "ts-node": "^10.9.1",
- "tsdown": "^0.12.5",
- "typescript": "^5.3.2",
- "vitest": "^0.34.6",
- "walk-sync": "^3.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- },
- "module": "./dist/index.mjs",
- "exports": {
- ".": {
- "import": "./dist/index.mjs",
- "require": "./dist/index.cjs"
- },
- "./package.json": "./package.json"
- }
-}
diff --git a/backend/dev-console/node_modules/nanoid/LICENSE b/backend/dev-console/node_modules/nanoid/LICENSE
deleted file mode 100644
index 37f56aa..0000000
--- a/backend/dev-console/node_modules/nanoid/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright 2017 Andrey Sitnik
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/backend/dev-console/node_modules/nanoid/README.md b/backend/dev-console/node_modules/nanoid/README.md
deleted file mode 100644
index 5124349..0000000
--- a/backend/dev-console/node_modules/nanoid/README.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Nano ID
-
-
-
-**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
-
-A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
-
-> “An amazing level of senseless perfectionism,
-> which is simply impossible not to respect.”
-
-* **Small.** 130 bytes (minified and gzipped). No dependencies.
- [Size Limit] controls the size.
-* **Fast.** It is 2 times faster than UUID.
-* **Safe.** It uses hardware random generator. Can be used in clusters.
-* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
- So ID size was reduced from 36 to 21 symbols.
-* **Portable.** Nano ID was ported
- to [20 programming languages](#other-programming-languages).
-
-```js
-import { nanoid } from 'nanoid'
-model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
-```
-
-Supports modern browsers, IE [with Babel], Node.js and React Native.
-
-[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/
-[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
-[Size Limit]: https://github.com/ai/size-limit
-
-
-
-
diff --git a/backend/dev-console/node_modules/nanoid/async/index.browser.cjs b/backend/dev-console/node_modules/nanoid/async/index.browser.cjs
deleted file mode 100644
index 9f8c3a3..0000000
--- a/backend/dev-console/node_modules/nanoid/async/index.browser.cjs
+++ /dev/null
@@ -1,42 +0,0 @@
-let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
-
-
-
- let step = -~((1.6 * mask * defaultSize) / alphabet.length)
-
- return async (size = defaultSize) => {
- let id = ''
- while (true) {
- let bytes = crypto.getRandomValues(new Uint8Array(step))
- let i = step | 0
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
-}
-
-let nanoid = async (size = 21) => {
- let id = ''
- let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
-
- while (size--) {
- let byte = bytes[size] & 63
- if (byte < 36) {
- id += byte.toString(36)
- } else if (byte < 62) {
- id += (byte - 26).toString(36).toUpperCase()
- } else if (byte < 63) {
- id += '_'
- } else {
- id += '-'
- }
- }
- return id
-}
-
-module.exports = { nanoid, customAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/async/index.browser.js b/backend/dev-console/node_modules/nanoid/async/index.browser.js
deleted file mode 100644
index 9e5da48..0000000
--- a/backend/dev-console/node_modules/nanoid/async/index.browser.js
+++ /dev/null
@@ -1,42 +0,0 @@
-let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
-
-
-
- let step = -~((1.6 * mask * defaultSize) / alphabet.length)
-
- return async (size = defaultSize) => {
- let id = ''
- while (true) {
- let bytes = crypto.getRandomValues(new Uint8Array(step))
- let i = step | 0
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
-}
-
-let nanoid = async (size = 21) => {
- let id = ''
- let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
-
- while (size--) {
- let byte = bytes[size] & 63
- if (byte < 36) {
- id += byte.toString(36)
- } else if (byte < 62) {
- id += (byte - 26).toString(36).toUpperCase()
- } else if (byte < 63) {
- id += '_'
- } else {
- id += '-'
- }
- }
- return id
-}
-
-export { nanoid, customAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/async/index.cjs b/backend/dev-console/node_modules/nanoid/async/index.cjs
deleted file mode 100644
index d6db856..0000000
--- a/backend/dev-console/node_modules/nanoid/async/index.cjs
+++ /dev/null
@@ -1,44 +0,0 @@
-let crypto = require('crypto')
-
-let { urlAlphabet } = require('../url-alphabet/index.cjs')
-
-let random = bytes =>
- new Promise((resolve, reject) => {
- crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
- if (err) {
- reject(err)
- } else {
- resolve(buf)
- }
- })
- })
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
-
-
- let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
-
- let tick = (id, size = defaultSize) =>
- random(step).then(bytes => {
- let i = step
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length >= size) return id
- }
- return tick(id, size)
- })
-
- return size => tick('', size)
-}
-
-let nanoid = (size = 21) =>
- random((size |= 0)).then(bytes => {
- let id = ''
- while (size--) {
- id += urlAlphabet[bytes[size] & 63]
- }
- return id
- })
-
-module.exports = { nanoid, customAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/async/index.d.ts b/backend/dev-console/node_modules/nanoid/async/index.d.ts
deleted file mode 100644
index 9e91965..0000000
--- a/backend/dev-console/node_modules/nanoid/async/index.d.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Generate secure URL-friendly unique ID. The non-blocking version.
- *
- * By default, the ID will have 21 symbols to have a collision probability
- * similar to UUID v4.
- *
- * ```js
- * import { nanoid } from 'nanoid/async'
- * nanoid().then(id => {
- * model.id = id
- * })
- * ```
- *
- * @param size Size of the ID. The default size is 21.
- * @returns A promise with a random string.
- */
-export function nanoid(size?: number): Promise
-
-/**
- * A low-level function.
- * Generate secure unique ID with custom alphabet. The non-blocking version.
- *
- * Alphabet must contain 256 symbols or less. Otherwise, the generator
- * will not be secure.
- *
- * @param alphabet Alphabet used to generate the ID.
- * @param defaultSize Size of the ID. The default size is 21.
- * @returns A function that returns a promise with a random string.
- *
- * ```js
- * import { customAlphabet } from 'nanoid/async'
- * const nanoid = customAlphabet('0123456789абвгдеё', 5)
- * nanoid().then(id => {
- * model.id = id //=> "8ё56а"
- * })
- * ```
- */
-export function customAlphabet(
- alphabet: string,
- defaultSize?: number
-): (size?: number) => Promise
-
-/**
- * Generate an array of random bytes collected from hardware noise.
- *
- * ```js
- * import { random } from 'nanoid/async'
- * random(5).then(bytes => {
- * bytes //=> [10, 67, 212, 67, 89]
- * })
- * ```
- *
- * @param bytes Size of the array.
- * @returns A promise with a random bytes array.
- */
-export function random(bytes: number): Promise
diff --git a/backend/dev-console/node_modules/nanoid/async/index.js b/backend/dev-console/node_modules/nanoid/async/index.js
deleted file mode 100644
index 4df5919..0000000
--- a/backend/dev-console/node_modules/nanoid/async/index.js
+++ /dev/null
@@ -1,44 +0,0 @@
-import crypto from 'crypto'
-
-import { urlAlphabet } from '../url-alphabet/index.js'
-
-let random = bytes =>
- new Promise((resolve, reject) => {
- crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
- if (err) {
- reject(err)
- } else {
- resolve(buf)
- }
- })
- })
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
-
-
- let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
-
- let tick = (id, size = defaultSize) =>
- random(step).then(bytes => {
- let i = step
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length >= size) return id
- }
- return tick(id, size)
- })
-
- return size => tick('', size)
-}
-
-let nanoid = (size = 21) =>
- random((size |= 0)).then(bytes => {
- let id = ''
- while (size--) {
- id += urlAlphabet[bytes[size] & 63]
- }
- return id
- })
-
-export { nanoid, customAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/async/index.native.js b/backend/dev-console/node_modules/nanoid/async/index.native.js
deleted file mode 100644
index 9579c12..0000000
--- a/backend/dev-console/node_modules/nanoid/async/index.native.js
+++ /dev/null
@@ -1,35 +0,0 @@
-import { getRandomBytesAsync } from 'expo-random'
-
-import { urlAlphabet } from '../url-alphabet/index.js'
-
-let random = getRandomBytesAsync
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
-
-
- let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
-
- let tick = (id, size = defaultSize) =>
- random(step).then(bytes => {
- let i = step
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length >= size) return id
- }
- return tick(id, size)
- })
-
- return size => tick('', size)
-}
-
-let nanoid = (size = 21) =>
- random((size |= 0)).then(bytes => {
- let id = ''
- while (size--) {
- id += urlAlphabet[bytes[size] & 63]
- }
- return id
- })
-
-export { nanoid, customAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/async/package.json b/backend/dev-console/node_modules/nanoid/async/package.json
deleted file mode 100644
index 578cdb4..0000000
--- a/backend/dev-console/node_modules/nanoid/async/package.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "type": "module",
- "main": "index.cjs",
- "module": "index.js",
- "react-native": {
- "./index.js": "./index.native.js"
- },
- "browser": {
- "./index.js": "./index.browser.js",
- "./index.cjs": "./index.browser.cjs"
- }
-}
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/nanoid/bin/nanoid.cjs b/backend/dev-console/node_modules/nanoid/bin/nanoid.cjs
deleted file mode 100755
index c76db0f..0000000
--- a/backend/dev-console/node_modules/nanoid/bin/nanoid.cjs
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env node
-
-let { nanoid, customAlphabet } = require('..')
-
-function print(msg) {
- process.stdout.write(msg + '\n')
-}
-
-function error(msg) {
- process.stderr.write(msg + '\n')
- process.exit(1)
-}
-
-if (process.argv.includes('--help') || process.argv.includes('-h')) {
- print(`
- Usage
- $ nanoid [options]
-
- Options
- -s, --size Generated ID size
- -a, --alphabet Alphabet to use
- -h, --help Show this help
-
- Examples
- $ nanoid --s 15
- S9sBF77U6sDB8Yg
-
- $ nanoid --size 10 --alphabet abc
- bcabababca`)
- process.exit()
-}
-
-let alphabet, size
-for (let i = 2; i < process.argv.length; i++) {
- let arg = process.argv[i]
- if (arg === '--size' || arg === '-s') {
- size = Number(process.argv[i + 1])
- i += 1
- if (Number.isNaN(size) || size <= 0) {
- error('Size must be positive integer')
- }
- } else if (arg === '--alphabet' || arg === '-a') {
- alphabet = process.argv[i + 1]
- i += 1
- } else {
- error('Unknown argument ' + arg)
- }
-}
-
-if (alphabet) {
- let customNanoid = customAlphabet(alphabet, size)
- print(customNanoid())
-} else {
- print(nanoid(size))
-}
diff --git a/backend/dev-console/node_modules/nanoid/index.browser.cjs b/backend/dev-console/node_modules/nanoid/index.browser.cjs
deleted file mode 100644
index 2b4b7b6..0000000
--- a/backend/dev-console/node_modules/nanoid/index.browser.cjs
+++ /dev/null
@@ -1,44 +0,0 @@
-
-let { urlAlphabet } = require('./url-alphabet/index.cjs')
-
-let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
-
-let customRandom = (alphabet, defaultSize, getRandom) => {
- let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
-
-
-
- let step = -~((1.6 * mask * defaultSize) / alphabet.length)
-
- return (size = defaultSize) => {
- let id = ''
- while (true) {
- let bytes = getRandom(step)
- let j = step | 0
- while (j--) {
- id += alphabet[bytes[j] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
-}
-
-let customAlphabet = (alphabet, size = 21) =>
- customRandom(alphabet, size, random)
-
-let nanoid = (size = 21) =>
- crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
- byte &= 63
- if (byte < 36) {
- id += byte.toString(36)
- } else if (byte < 62) {
- id += (byte - 26).toString(36).toUpperCase()
- } else if (byte > 62) {
- id += '-'
- } else {
- id += '_'
- }
- return id
- }, '')
-
-module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/index.browser.js b/backend/dev-console/node_modules/nanoid/index.browser.js
deleted file mode 100644
index db69b3a..0000000
--- a/backend/dev-console/node_modules/nanoid/index.browser.js
+++ /dev/null
@@ -1,44 +0,0 @@
-
-import { urlAlphabet } from './url-alphabet/index.js'
-
-let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
-
-let customRandom = (alphabet, defaultSize, getRandom) => {
- let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
-
-
-
- let step = -~((1.6 * mask * defaultSize) / alphabet.length)
-
- return (size = defaultSize) => {
- let id = ''
- while (true) {
- let bytes = getRandom(step)
- let j = step | 0
- while (j--) {
- id += alphabet[bytes[j] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
-}
-
-let customAlphabet = (alphabet, size = 21) =>
- customRandom(alphabet, size, random)
-
-let nanoid = (size = 21) =>
- crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
- byte &= 63
- if (byte < 36) {
- id += byte.toString(36)
- } else if (byte < 62) {
- id += (byte - 26).toString(36).toUpperCase()
- } else if (byte > 62) {
- id += '-'
- } else {
- id += '_'
- }
- return id
- }, '')
-
-export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/index.cjs b/backend/dev-console/node_modules/nanoid/index.cjs
deleted file mode 100644
index 9d50c52..0000000
--- a/backend/dev-console/node_modules/nanoid/index.cjs
+++ /dev/null
@@ -1,57 +0,0 @@
-let crypto = require('crypto')
-
-let { urlAlphabet } = require('./url-alphabet/index.cjs')
-
-const POOL_SIZE_MULTIPLIER = 128
-let pool, poolOffset
-
-let fillPool = bytes => {
- if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size')
- if (!pool || pool.length < bytes) {
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
- crypto.randomFillSync(pool)
- poolOffset = 0
- } else if (poolOffset + bytes > pool.length) {
- crypto.randomFillSync(pool)
- poolOffset = 0
- }
- poolOffset += bytes
-}
-
-let random = bytes => {
- fillPool((bytes |= 0))
- return pool.subarray(poolOffset - bytes, poolOffset)
-}
-
-let customRandom = (alphabet, defaultSize, getRandom) => {
- let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
-
-
- let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
-
- return (size = defaultSize) => {
- let id = ''
- while (true) {
- let bytes = getRandom(step)
- let i = step
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
-}
-
-let customAlphabet = (alphabet, size = 21) =>
- customRandom(alphabet, size, random)
-
-let nanoid = (size = 21) => {
- fillPool((size |= 0))
- let id = ''
- for (let i = poolOffset - size; i < poolOffset; i++) {
- id += urlAlphabet[pool[i] & 63]
- }
- return id
-}
-
-module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/index.d.cts b/backend/dev-console/node_modules/nanoid/index.d.cts
deleted file mode 100644
index 3e111a3..0000000
--- a/backend/dev-console/node_modules/nanoid/index.d.cts
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Generate secure URL-friendly unique ID.
- *
- * By default, the ID will have 21 symbols to have a collision probability
- * similar to UUID v4.
- *
- * ```js
- * import { nanoid } from 'nanoid'
- * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
- * ```
- *
- * @param size Size of the ID. The default size is 21.
- * @returns A random string.
- */
-export function nanoid(size?: number): string
-
-/**
- * Generate secure unique ID with custom alphabet.
- *
- * Alphabet must contain 256 symbols or less. Otherwise, the generator
- * will not be secure.
- *
- * @param alphabet Alphabet used to generate the ID.
- * @param defaultSize Size of the ID. The default size is 21.
- * @returns A random string generator.
- *
- * ```js
- * const { customAlphabet } = require('nanoid')
- * const nanoid = customAlphabet('0123456789абвгдеё', 5)
- * nanoid() //=> "8ё56а"
- * ```
- */
-export function customAlphabet(
- alphabet: string,
- defaultSize?: number
-): (size?: number) => string
-
-/**
- * Generate unique ID with custom random generator and alphabet.
- *
- * Alphabet must contain 256 symbols or less. Otherwise, the generator
- * will not be secure.
- *
- * ```js
- * import { customRandom } from 'nanoid/format'
- *
- * const nanoid = customRandom('abcdef', 5, size => {
- * const random = []
- * for (let i = 0; i < size; i++) {
- * random.push(randomByte())
- * }
- * return random
- * })
- *
- * nanoid() //=> "fbaef"
- * ```
- *
- * @param alphabet Alphabet used to generate a random string.
- * @param size Size of the random string.
- * @param random A random bytes generator.
- * @returns A random string generator.
- */
-export function customRandom(
- alphabet: string,
- size: number,
- random: (bytes: number) => Uint8Array
-): () => string
-
-/**
- * URL safe symbols.
- *
- * ```js
- * import { urlAlphabet } from 'nanoid'
- * const nanoid = customAlphabet(urlAlphabet, 10)
- * nanoid() //=> "Uakgb_J5m9"
- * ```
- */
-export const urlAlphabet: string
-
-/**
- * Generate an array of random bytes collected from hardware noise.
- *
- * ```js
- * import { customRandom, random } from 'nanoid'
- * const nanoid = customRandom("abcdef", 5, random)
- * ```
- *
- * @param bytes Size of the array.
- * @returns An array of random bytes.
- */
-export function random(bytes: number): Uint8Array
diff --git a/backend/dev-console/node_modules/nanoid/index.d.ts b/backend/dev-console/node_modules/nanoid/index.d.ts
deleted file mode 100644
index 3e111a3..0000000
--- a/backend/dev-console/node_modules/nanoid/index.d.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Generate secure URL-friendly unique ID.
- *
- * By default, the ID will have 21 symbols to have a collision probability
- * similar to UUID v4.
- *
- * ```js
- * import { nanoid } from 'nanoid'
- * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
- * ```
- *
- * @param size Size of the ID. The default size is 21.
- * @returns A random string.
- */
-export function nanoid(size?: number): string
-
-/**
- * Generate secure unique ID with custom alphabet.
- *
- * Alphabet must contain 256 symbols or less. Otherwise, the generator
- * will not be secure.
- *
- * @param alphabet Alphabet used to generate the ID.
- * @param defaultSize Size of the ID. The default size is 21.
- * @returns A random string generator.
- *
- * ```js
- * const { customAlphabet } = require('nanoid')
- * const nanoid = customAlphabet('0123456789абвгдеё', 5)
- * nanoid() //=> "8ё56а"
- * ```
- */
-export function customAlphabet(
- alphabet: string,
- defaultSize?: number
-): (size?: number) => string
-
-/**
- * Generate unique ID with custom random generator and alphabet.
- *
- * Alphabet must contain 256 symbols or less. Otherwise, the generator
- * will not be secure.
- *
- * ```js
- * import { customRandom } from 'nanoid/format'
- *
- * const nanoid = customRandom('abcdef', 5, size => {
- * const random = []
- * for (let i = 0; i < size; i++) {
- * random.push(randomByte())
- * }
- * return random
- * })
- *
- * nanoid() //=> "fbaef"
- * ```
- *
- * @param alphabet Alphabet used to generate a random string.
- * @param size Size of the random string.
- * @param random A random bytes generator.
- * @returns A random string generator.
- */
-export function customRandom(
- alphabet: string,
- size: number,
- random: (bytes: number) => Uint8Array
-): () => string
-
-/**
- * URL safe symbols.
- *
- * ```js
- * import { urlAlphabet } from 'nanoid'
- * const nanoid = customAlphabet(urlAlphabet, 10)
- * nanoid() //=> "Uakgb_J5m9"
- * ```
- */
-export const urlAlphabet: string
-
-/**
- * Generate an array of random bytes collected from hardware noise.
- *
- * ```js
- * import { customRandom, random } from 'nanoid'
- * const nanoid = customRandom("abcdef", 5, random)
- * ```
- *
- * @param bytes Size of the array.
- * @returns An array of random bytes.
- */
-export function random(bytes: number): Uint8Array
diff --git a/backend/dev-console/node_modules/nanoid/index.js b/backend/dev-console/node_modules/nanoid/index.js
deleted file mode 100644
index c5d67b7..0000000
--- a/backend/dev-console/node_modules/nanoid/index.js
+++ /dev/null
@@ -1,62 +0,0 @@
-import crypto from 'crypto'
-
-import { urlAlphabet } from './url-alphabet/index.js'
-
-const POOL_SIZE_MULTIPLIER = 128
-let pool, poolOffset
-
-let fillPool = bytes => {
- if (bytes < 0) throw new RangeError('Wrong ID size')
- try {
- if (!pool || pool.length < bytes) {
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
- crypto.randomFillSync(pool)
- poolOffset = 0
- } else if (poolOffset + bytes > pool.length) {
- crypto.randomFillSync(pool)
- poolOffset = 0
- }
- } catch (e) {
- pool = undefined
- throw e
- }
- poolOffset += bytes
-}
-
-let random = bytes => {
- fillPool((bytes |= 0))
- return pool.subarray(poolOffset - bytes, poolOffset)
-}
-
-let customRandom = (alphabet, defaultSize, getRandom) => {
- let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
-
-
- let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
-
- return (size = defaultSize) => {
- let id = ''
- while (true) {
- let bytes = getRandom(step)
- let i = step
- while (i--) {
- id += alphabet[bytes[i] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
-}
-
-let customAlphabet = (alphabet, size = 21) =>
- customRandom(alphabet, size, random)
-
-let nanoid = (size = 21) => {
- fillPool((size |= 0))
- let id = ''
- for (let i = poolOffset - size; i < poolOffset; i++) {
- id += urlAlphabet[pool[i] & 63]
- }
- return id
-}
-
-export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/backend/dev-console/node_modules/nanoid/nanoid.js b/backend/dev-console/node_modules/nanoid/nanoid.js
deleted file mode 100644
index ec242ea..0000000
--- a/backend/dev-console/node_modules/nanoid/nanoid.js
+++ /dev/null
@@ -1 +0,0 @@
-export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),"");
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/nanoid/non-secure/index.cjs b/backend/dev-console/node_modules/nanoid/non-secure/index.cjs
deleted file mode 100644
index b32f42b..0000000
--- a/backend/dev-console/node_modules/nanoid/non-secure/index.cjs
+++ /dev/null
@@ -1,24 +0,0 @@
-let urlAlphabet =
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- return (size = defaultSize) => {
- let id = ''
- let i = size | 0
- while (i--) {
- id += alphabet[(Math.random() * alphabet.length) | 0]
- }
- return id
- }
-}
-
-let nanoid = (size = 21) => {
- let id = ''
- let i = size | 0
- while (i--) {
- id += urlAlphabet[(Math.random() * 64) | 0]
- }
- return id
-}
-
-module.exports = { nanoid, customAlphabet }
diff --git a/backend/dev-console/node_modules/nanoid/non-secure/index.d.ts b/backend/dev-console/node_modules/nanoid/non-secure/index.d.ts
deleted file mode 100644
index 4965322..0000000
--- a/backend/dev-console/node_modules/nanoid/non-secure/index.d.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Generate URL-friendly unique ID. This method uses the non-secure
- * predictable random generator with bigger collision probability.
- *
- * ```js
- * import { nanoid } from 'nanoid/non-secure'
- * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
- * ```
- *
- * @param size Size of the ID. The default size is 21.
- * @returns A random string.
- */
-export function nanoid(size?: number): string
-
-/**
- * Generate a unique ID based on a custom alphabet.
- * This method uses the non-secure predictable random generator
- * with bigger collision probability.
- *
- * @param alphabet Alphabet used to generate the ID.
- * @param defaultSize Size of the ID. The default size is 21.
- * @returns A random string generator.
- *
- * ```js
- * import { customAlphabet } from 'nanoid/non-secure'
- * const nanoid = customAlphabet('0123456789абвгдеё', 5)
- * model.id = //=> "8ё56а"
- * ```
- */
-export function customAlphabet(
- alphabet: string,
- defaultSize?: number
-): (size?: number) => string
diff --git a/backend/dev-console/node_modules/nanoid/non-secure/index.js b/backend/dev-console/node_modules/nanoid/non-secure/index.js
deleted file mode 100644
index 49b12c8..0000000
--- a/backend/dev-console/node_modules/nanoid/non-secure/index.js
+++ /dev/null
@@ -1,24 +0,0 @@
-let urlAlphabet =
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
-
-let customAlphabet = (alphabet, defaultSize = 21) => {
- return (size = defaultSize) => {
- let id = ''
- let i = size | 0
- while (i--) {
- id += alphabet[(Math.random() * alphabet.length) | 0]
- }
- return id
- }
-}
-
-let nanoid = (size = 21) => {
- let id = ''
- let i = size | 0
- while (i--) {
- id += urlAlphabet[(Math.random() * 64) | 0]
- }
- return id
-}
-
-export { nanoid, customAlphabet }
diff --git a/backend/dev-console/node_modules/nanoid/non-secure/package.json b/backend/dev-console/node_modules/nanoid/non-secure/package.json
deleted file mode 100644
index 9930d6a..0000000
--- a/backend/dev-console/node_modules/nanoid/non-secure/package.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "type": "module",
- "main": "index.cjs",
- "module": "index.js",
- "react-native": "index.js"
-}
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/nanoid/package.json b/backend/dev-console/node_modules/nanoid/package.json
deleted file mode 100644
index b76bde9..0000000
--- a/backend/dev-console/node_modules/nanoid/package.json
+++ /dev/null
@@ -1,89 +0,0 @@
-{
- "name": "nanoid",
- "version": "3.3.15",
- "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
- "keywords": [
- "uuid",
- "random",
- "id",
- "url"
- ],
- "engines": {
- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
- },
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "author": "Andrey Sitnik ",
- "license": "MIT",
- "repository": "ai/nanoid",
- "browser": {
- "./index.js": "./index.browser.js",
- "./async/index.js": "./async/index.browser.js",
- "./async/index.cjs": "./async/index.browser.cjs",
- "./index.cjs": "./index.browser.cjs"
- },
- "react-native": "index.js",
- "bin": "./bin/nanoid.cjs",
- "sideEffects": false,
- "types": "./index.d.ts",
- "type": "module",
- "main": "index.cjs",
- "module": "index.js",
- "exports": {
- ".": {
- "react-native": "./index.browser.js",
- "browser": "./index.browser.js",
- "require": {
- "types": "./index.d.cts",
- "default": "./index.cjs"
- },
- "import": {
- "types": "./index.d.ts",
- "default": "./index.js"
- },
- "default": "./index.js"
- },
- "./package.json": "./package.json",
- "./async/package.json": "./async/package.json",
- "./async": {
- "browser": "./async/index.browser.js",
- "require": {
- "types": "./index.d.cts",
- "default": "./async/index.cjs"
- },
- "import": {
- "types": "./index.d.ts",
- "default": "./async/index.js"
- },
- "default": "./async/index.js"
- },
- "./non-secure/package.json": "./non-secure/package.json",
- "./non-secure": {
- "require": {
- "types": "./index.d.cts",
- "default": "./non-secure/index.cjs"
- },
- "import": {
- "types": "./index.d.ts",
- "default": "./non-secure/index.js"
- },
- "default": "./non-secure/index.js"
- },
- "./url-alphabet/package.json": "./url-alphabet/package.json",
- "./url-alphabet": {
- "require": {
- "types": "./index.d.cts",
- "default": "./url-alphabet/index.cjs"
- },
- "import": {
- "types": "./index.d.ts",
- "default": "./url-alphabet/index.js"
- },
- "default": "./url-alphabet/index.js"
- }
- }
-}
diff --git a/backend/dev-console/node_modules/nanoid/url-alphabet/index.cjs b/backend/dev-console/node_modules/nanoid/url-alphabet/index.cjs
deleted file mode 100644
index 9021f0b..0000000
--- a/backend/dev-console/node_modules/nanoid/url-alphabet/index.cjs
+++ /dev/null
@@ -1,4 +0,0 @@
-let urlAlphabet =
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
-
-module.exports = { urlAlphabet }
diff --git a/backend/dev-console/node_modules/nanoid/url-alphabet/index.js b/backend/dev-console/node_modules/nanoid/url-alphabet/index.js
deleted file mode 100644
index f995c4f..0000000
--- a/backend/dev-console/node_modules/nanoid/url-alphabet/index.js
+++ /dev/null
@@ -1,4 +0,0 @@
-let urlAlphabet =
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
-
-export { urlAlphabet }
diff --git a/backend/dev-console/node_modules/nanoid/url-alphabet/package.json b/backend/dev-console/node_modules/nanoid/url-alphabet/package.json
deleted file mode 100644
index 9930d6a..0000000
--- a/backend/dev-console/node_modules/nanoid/url-alphabet/package.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "type": "module",
- "main": "index.cjs",
- "module": "index.js",
- "react-native": "index.js"
-}
\ No newline at end of file
diff --git a/backend/dev-console/node_modules/picocolors/LICENSE b/backend/dev-console/node_modules/picocolors/LICENSE
deleted file mode 100644
index 46c9b95..0000000
--- a/backend/dev-console/node_modules/picocolors/LICENSE
+++ /dev/null
@@ -1,15 +0,0 @@
-ISC License
-
-Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted, provided that the above
-copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/backend/dev-console/node_modules/picocolors/README.md b/backend/dev-console/node_modules/picocolors/README.md
deleted file mode 100644
index 8e47aa8..0000000
--- a/backend/dev-console/node_modules/picocolors/README.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# picocolors
-
-The tiniest and the fastest library for terminal output formatting with ANSI colors.
-
-```javascript
-import pc from "picocolors"
-
-console.log(
- pc.green(`How are ${pc.italic(`you`)} doing?`)
-)
-```
-
-- **No dependencies.**
-- **14 times** smaller and **2 times** faster than chalk.
-- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist.
-- Node.js v6+ & browsers support. Support for both CJS and ESM projects.
-- TypeScript type declarations included.
-- [`NO_COLOR`](https://no-color.org/) friendly.
-
-## Docs
-Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub.
diff --git a/backend/dev-console/node_modules/picocolors/package.json b/backend/dev-console/node_modules/picocolors/package.json
deleted file mode 100644
index 372d4b6..0000000
--- a/backend/dev-console/node_modules/picocolors/package.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "name": "picocolors",
- "version": "1.1.1",
- "main": "./picocolors.js",
- "types": "./picocolors.d.ts",
- "browser": {
- "./picocolors.js": "./picocolors.browser.js"
- },
- "sideEffects": false,
- "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors",
- "files": [
- "picocolors.*",
- "types.d.ts"
- ],
- "keywords": [
- "terminal",
- "colors",
- "formatting",
- "cli",
- "console"
- ],
- "author": "Alexey Raspopov",
- "repository": "alexeyraspopov/picocolors",
- "license": "ISC"
-}
diff --git a/backend/dev-console/node_modules/picocolors/picocolors.browser.js b/backend/dev-console/node_modules/picocolors/picocolors.browser.js
deleted file mode 100644
index 9dcf637..0000000
--- a/backend/dev-console/node_modules/picocolors/picocolors.browser.js
+++ /dev/null
@@ -1,4 +0,0 @@
-var x=String;
-var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};
-module.exports=create();
-module.exports.createColors = create;
diff --git a/backend/dev-console/node_modules/picocolors/picocolors.d.ts b/backend/dev-console/node_modules/picocolors/picocolors.d.ts
deleted file mode 100644
index 94e146a..0000000
--- a/backend/dev-console/node_modules/picocolors/picocolors.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { Colors } from "./types"
-
-declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors }
-
-export = picocolors
diff --git a/backend/dev-console/node_modules/picocolors/picocolors.js b/backend/dev-console/node_modules/picocolors/picocolors.js
deleted file mode 100644
index e32df85..0000000
--- a/backend/dev-console/node_modules/picocolors/picocolors.js
+++ /dev/null
@@ -1,75 +0,0 @@
-let p = process || {}, argv = p.argv || [], env = p.env || {}
-let isColorSupported =
- !(!!env.NO_COLOR || argv.includes("--no-color")) &&
- (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI)
-
-let formatter = (open, close, replace = open) =>
- input => {
- let string = "" + input, index = string.indexOf(close, open.length)
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
- }
-
-let replaceClose = (string, close, replace, index) => {
- let result = "", cursor = 0
- do {
- result += string.substring(cursor, index) + replace
- cursor = index + close.length
- index = string.indexOf(close, cursor)
- } while (~index)
- return result + string.substring(cursor)
-}
-
-let createColors = (enabled = isColorSupported) => {
- let f = enabled ? formatter : () => String
- return {
- isColorSupported: enabled,
- reset: f("\x1b[0m", "\x1b[0m"),
- bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
- dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
- italic: f("\x1b[3m", "\x1b[23m"),
- underline: f("\x1b[4m", "\x1b[24m"),
- inverse: f("\x1b[7m", "\x1b[27m"),
- hidden: f("\x1b[8m", "\x1b[28m"),
- strikethrough: f("\x1b[9m", "\x1b[29m"),
-
- black: f("\x1b[30m", "\x1b[39m"),
- red: f("\x1b[31m", "\x1b[39m"),
- green: f("\x1b[32m", "\x1b[39m"),
- yellow: f("\x1b[33m", "\x1b[39m"),
- blue: f("\x1b[34m", "\x1b[39m"),
- magenta: f("\x1b[35m", "\x1b[39m"),
- cyan: f("\x1b[36m", "\x1b[39m"),
- white: f("\x1b[37m", "\x1b[39m"),
- gray: f("\x1b[90m", "\x1b[39m"),
-
- bgBlack: f("\x1b[40m", "\x1b[49m"),
- bgRed: f("\x1b[41m", "\x1b[49m"),
- bgGreen: f("\x1b[42m", "\x1b[49m"),
- bgYellow: f("\x1b[43m", "\x1b[49m"),
- bgBlue: f("\x1b[44m", "\x1b[49m"),
- bgMagenta: f("\x1b[45m", "\x1b[49m"),
- bgCyan: f("\x1b[46m", "\x1b[49m"),
- bgWhite: f("\x1b[47m", "\x1b[49m"),
-
- blackBright: f("\x1b[90m", "\x1b[39m"),
- redBright: f("\x1b[91m", "\x1b[39m"),
- greenBright: f("\x1b[92m", "\x1b[39m"),
- yellowBright: f("\x1b[93m", "\x1b[39m"),
- blueBright: f("\x1b[94m", "\x1b[39m"),
- magentaBright: f("\x1b[95m", "\x1b[39m"),
- cyanBright: f("\x1b[96m", "\x1b[39m"),
- whiteBright: f("\x1b[97m", "\x1b[39m"),
-
- bgBlackBright: f("\x1b[100m", "\x1b[49m"),
- bgRedBright: f("\x1b[101m", "\x1b[49m"),
- bgGreenBright: f("\x1b[102m", "\x1b[49m"),
- bgYellowBright: f("\x1b[103m", "\x1b[49m"),
- bgBlueBright: f("\x1b[104m", "\x1b[49m"),
- bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
- bgCyanBright: f("\x1b[106m", "\x1b[49m"),
- bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
- }
-}
-
-module.exports = createColors()
-module.exports.createColors = createColors
diff --git a/backend/dev-console/node_modules/picocolors/types.d.ts b/backend/dev-console/node_modules/picocolors/types.d.ts
deleted file mode 100644
index cd1aec4..0000000
--- a/backend/dev-console/node_modules/picocolors/types.d.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-export type Formatter = (input: string | number | null | undefined) => string
-
-export interface Colors {
- isColorSupported: boolean
-
- reset: Formatter
- bold: Formatter
- dim: Formatter
- italic: Formatter
- underline: Formatter
- inverse: Formatter
- hidden: Formatter
- strikethrough: Formatter
-
- black: Formatter
- red: Formatter
- green: Formatter
- yellow: Formatter
- blue: Formatter
- magenta: Formatter
- cyan: Formatter
- white: Formatter
- gray: Formatter
-
- bgBlack: Formatter
- bgRed: Formatter
- bgGreen: Formatter
- bgYellow: Formatter
- bgBlue: Formatter
- bgMagenta: Formatter
- bgCyan: Formatter
- bgWhite: Formatter
-
- blackBright: Formatter
- redBright: Formatter
- greenBright: Formatter
- yellowBright: Formatter
- blueBright: Formatter
- magentaBright: Formatter
- cyanBright: Formatter
- whiteBright: Formatter
-
- bgBlackBright: Formatter
- bgRedBright: Formatter
- bgGreenBright: Formatter
- bgYellowBright: Formatter
- bgBlueBright: Formatter
- bgMagentaBright: Formatter
- bgCyanBright: Formatter
- bgWhiteBright: Formatter
-}
diff --git a/backend/dev-console/node_modules/picomatch/LICENSE b/backend/dev-console/node_modules/picomatch/LICENSE
deleted file mode 100644
index 3608dca..0000000
--- a/backend/dev-console/node_modules/picomatch/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2017-present, Jon Schlinkert.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/backend/dev-console/node_modules/picomatch/README.md b/backend/dev-console/node_modules/picomatch/README.md
deleted file mode 100644
index 14805d6..0000000
--- a/backend/dev-console/node_modules/picomatch/README.md
+++ /dev/null
@@ -1,749 +0,0 @@
-Picomatch
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Blazing fast and accurate glob matcher written in JavaScript.
-No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.
-
-
-
-
-
-## Why picomatch?
-
-* **Lightweight** - No dependencies
-* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
-* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps)
-* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files)
-* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes.
-* **Well tested** - Thousands of unit tests
-
-See the [library comparison](#library-comparisons) to other libraries.
-
-
-
-
-## Table of Contents
-
- Click to expand
-
-- [Install](#install)
-- [Usage](#usage)
-- [API](#api)
- * [picomatch](#picomatch)
- * [.test](#test)
- * [.matchBase](#matchbase)
- * [.isMatch](#ismatch)
- * [.parse](#parse)
- * [.scan](#scan)
- * [.compileRe](#compilere)
- * [.makeRe](#makere)
- * [.toRegex](#toregex)
-- [Options](#options)
- * [Picomatch options](#picomatch-options)
- * [Scan Options](#scan-options)
- * [Options Examples](#options-examples)
-- [Globbing features](#globbing-features)
- * [Basic globbing](#basic-globbing)
- * [Advanced globbing](#advanced-globbing)
- * [Braces](#braces)
- * [Matching special characters as literals](#matching-special-characters-as-literals)
-- [Library Comparisons](#library-comparisons)
-- [Benchmarks](#benchmarks)
-- [Philosophies](#philosophies)
-- [About](#about)
- * [Author](#author)
- * [License](#license)
-
-_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
-
-
-
-
-
-
-## Install
-
-Install with [npm](https://www.npmjs.com/):
-
-```sh
-npm install --save picomatch
-```
-
-
-
-## Usage
-
-The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
-
-```js
-const pm = require('picomatch');
-const isMatch = pm('*.js');
-
-console.log(isMatch('abcd')); //=> false
-console.log(isMatch('a.js')); //=> true
-console.log(isMatch('a.md')); //=> false
-console.log(isMatch('a/b.js')); //=> false
-```
-
-
-
-## API
-
-### [picomatch](lib/picomatch.js#L31)
-
-Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information.
-
-**Params**
-
-* `globs` **{String|Array}**: One or more glob patterns.
-* `options` **{Object=}**
-* `returns` **{Function=}**: Returns a matcher function.
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch(glob[, options]);
-
-const isMatch = picomatch('*.!(*a)');
-console.log(isMatch('a.a')); //=> false
-console.log(isMatch('a.b')); //=> true
-```
-
-**Example without node.js**
-
-For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection.
-
-```js
-const picomatch = require('picomatch/posix');
-// the same API, defaulting to posix paths
-const isMatch = picomatch('a/*');
-console.log(isMatch('a\\b')); //=> false
-console.log(isMatch('a/b')); //=> true
-
-// you can still configure the matcher function to accept windows paths
-const isMatch = picomatch('a/*', { options: windows });
-console.log(isMatch('a\\b')); //=> true
-console.log(isMatch('a/b')); //=> true
-```
-
-### [.test](lib/picomatch.js#L116)
-
-Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string.
-
-**Params**
-
-* `input` **{String}**: String to test.
-* `regex` **{RegExp}**
-* `returns` **{Object}**: Returns an object with matching info.
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch.test(input, regex[, options]);
-
-console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
-// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
-```
-
-### [.matchBase](lib/picomatch.js#L160)
-
-Match the basename of a filepath.
-
-**Params**
-
-* `input` **{String}**: String to test.
-* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe).
-* `returns` **{Boolean}**
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch.matchBase(input, glob[, options]);
-console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
-```
-
-### [.isMatch](lib/picomatch.js#L182)
-
-Returns true if **any** of the given glob `patterns` match the specified `string`.
-
-**Params**
-
-* **{String|Array}**: str The string to test.
-* **{String|Array}**: patterns One or more glob patterns to use for matching.
-* **{Object}**: See available [options](#options).
-* `returns` **{Boolean}**: Returns true if any patterns match `str`
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch.isMatch(string, patterns[, options]);
-
-console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
-console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
-```
-
-### [.parse](lib/picomatch.js#L198)
-
-Parse a glob pattern to create the source string for a regular expression.
-
-**Params**
-
-* `pattern` **{String}**
-* `options` **{Object}**
-* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string.
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-const result = picomatch.parse(pattern[, options]);
-```
-
-### [.scan](lib/picomatch.js#L230)
-
-Scan a glob pattern to separate the pattern into segments.
-
-**Params**
-
-* `input` **{String}**: Glob pattern to scan.
-* `options` **{Object}**
-* `returns` **{Object}**: Returns an object with
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch.scan(input[, options]);
-
-const result = picomatch.scan('!./foo/*.js');
-console.log(result);
-{ prefix: '!./',
- input: '!./foo/*.js',
- start: 3,
- base: 'foo',
- glob: '*.js',
- isBrace: false,
- isBracket: false,
- isGlob: true,
- isExtglob: false,
- isGlobstar: false,
- negated: true }
-```
-
-### [.compileRe](lib/picomatch.js#L244)
-
-Compile a regular expression from the `state` object returned by the
-[parse()](#parse) method.
-
-**Params**
-
-* `state` **{Object}**
-* `options` **{Object}**
-* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser.
-* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
-* `returns` **{RegExp}**
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-const state = picomatch.parse('*.js');
-// picomatch.compileRe(state[, options]);
-
-console.log(picomatch.compileRe(state));
-//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
-```
-
-### [.makeRe](lib/picomatch.js#L285)
-
-Create a regular expression from a parsed glob pattern.
-
-**Params**
-
-* `state` **{String}**: The object returned from the `.parse` method.
-* `options` **{Object}**
-* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
-* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
-* `returns` **{RegExp}**: Returns a regex created from the given pattern.
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch.makeRe(state[, options]);
-
-const result = picomatch.makeRe('*.js');
-console.log(result);
-//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
-```
-
-### [.toRegex](lib/picomatch.js#L320)
-
-Create a regular expression from the given regex source string.
-
-**Params**
-
-* `source` **{String}**: Regular expression source string.
-* `options` **{Object}**
-* `returns` **{RegExp}**
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-// picomatch.toRegex(source[, options]);
-
-const { output } = picomatch.parse('*.js');
-console.log(picomatch.toRegex(output));
-//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
-```
-
-
-
-## Options
-
-### Picomatch options
-
-The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API.
-
-| **Option** | **Type** | **Default value** | **Description** |
-| --- | --- | --- | --- |
-| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. |
-| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
-| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
-| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
-| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
-| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true |
-| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. |
-| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
-| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
-| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
-| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
-| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
-| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
-| `matchBase` | `boolean` | `false` | Alias for `basename` |
-| `maxLength` | `number` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
-| `maxExtglobRecursion` | `number\|boolean` | `0` | Limit nested quantified extglobs and other risky repeated extglob forms. When the limit is exceeded, the extglob is treated as a literal string instead of being compiled to regex. Set to `false` to disable this safeguard. |
-| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
-| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
-| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. |
-| `noext` | `boolean` | `false` | Alias for `noextglob` |
-| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) |
-| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
-| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
-| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
-| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
-| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
-| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). |
-| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. |
-| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
-| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
-| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
-| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
-| `windows` | `boolean` | `false` | Also accept backslashes as the path separator. |
-
-### Scan Options
-
-In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method.
-
-| **Option** | **Type** | **Default value** | **Description** |
-| --- | --- | --- | --- |
-| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
-| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true |
-
-**Example**
-
-```js
-const picomatch = require('picomatch');
-const result = picomatch.scan('!./foo/*.js', { tokens: true });
-console.log(result);
-// {
-// prefix: '!./',
-// input: '!./foo/*.js',
-// start: 3,
-// base: 'foo',
-// glob: '*.js',
-// isBrace: false,
-// isBracket: false,
-// isGlob: true,
-// isExtglob: false,
-// isGlobstar: false,
-// negated: true,
-// maxDepth: 2,
-// tokens: [
-// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
-// { value: 'foo', depth: 1, isGlob: false },
-// { value: '*.js', depth: 1, isGlob: true }
-// ],
-// slashes: [ 2, 6 ],
-// parts: [ 'foo', '*.js' ]
-// }
-```
-
-
-
-### Options Examples
-
-#### options.expandRange
-
-**Type**: `function`
-
-**Default**: `undefined`
-
-Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
-
-**Example**
-
-The following example shows how to create a glob that matches a folder
-
-```js
-const fill = require('fill-range');
-const regex = pm.makeRe('foo/{01..25}/bar', {
- expandRange(a, b) {
- return `(${fill(a, b, { toRegex: true })})`;
- }
-});
-
-console.log(regex);
-//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
-
-console.log(regex.test('foo/00/bar')) // false
-console.log(regex.test('foo/01/bar')) // true
-console.log(regex.test('foo/10/bar')) // true
-console.log(regex.test('foo/22/bar')) // true
-console.log(regex.test('foo/25/bar')) // true
-console.log(regex.test('foo/26/bar')) // false
-```
-
-#### options.format
-
-**Type**: `function`
-
-**Default**: `undefined`
-
-Custom function for formatting strings before they're matched.
-
-**Example**
-
-```js
-// strip leading './' from strings
-const format = str => str.replace(/^\.\//, '');
-const isMatch = picomatch('foo/*.js', { format });
-console.log(isMatch('./foo/bar.js')); //=> true
-```
-
-#### options.onMatch
-
-```js
-const onMatch = ({ glob, regex, input, output }) => {
- console.log({ glob, regex, input, output });
-};
-
-const isMatch = picomatch('*', { onMatch });
-isMatch('foo');
-isMatch('bar');
-isMatch('baz');
-```
-
-#### options.onIgnore
-
-```js
-const onIgnore = ({ glob, regex, input, output }) => {
- console.log({ glob, regex, input, output });
-};
-
-const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
-isMatch('foo');
-isMatch('bar');
-isMatch('baz');
-```
-
-#### options.onResult
-
-```js
-const onResult = ({ glob, regex, input, output }) => {
- console.log({ glob, regex, input, output });
-};
-
-const isMatch = picomatch('*', { onResult, ignore: 'f*' });
-isMatch('foo');
-isMatch('bar');
-isMatch('baz');
-```
-
-
-
-
-## Globbing features
-
-* [Basic globbing](#basic-globbing) (Wildcard matching)
-* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching)
-
-### Basic globbing
-
-| **Character** | **Description** |
-| --- | --- |
-| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. |
-| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` with the `windows` option) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. |
-| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. |
-| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. |
-
-#### Matching behavior vs. Bash
-
-Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
-
-* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`.
-* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`.
-
-
-
-### Advanced globbing
-
-* [extglobs](#extglobs)
-* [POSIX brackets](#posix-brackets)
-* [Braces](#brace-expansion)
-
-#### Extglobs
-
-| **Pattern** | **Description** |
-| --- | --- |
-| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` |
-| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` |
-| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` |
-| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` |
-| `!(pattern)` | Match _anything but_ `pattern` |
-
-**Examples**
-
-```js
-const pm = require('picomatch');
-
-// *(pattern) matches ZERO or more of "pattern"
-console.log(pm.isMatch('a', 'a*(z)')); // true
-console.log(pm.isMatch('az', 'a*(z)')); // true
-console.log(pm.isMatch('azzz', 'a*(z)')); // true
-
-// +(pattern) matches ONE or more of "pattern"
-console.log(pm.isMatch('a', 'a+(z)')); // false
-console.log(pm.isMatch('az', 'a+(z)')); // true
-console.log(pm.isMatch('azzz', 'a+(z)')); // true
-
-// supports multiple extglobs
-console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
-
-// supports nested extglobs
-console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
-
-// risky quantified extglobs are treated literally by default
-console.log(pm.makeRe('+(a|aa)'));
-//=> /^(?:\+\(a\|aa\))$/
-
-// increase the limit to allow a small amount of nested quantified extglobs
-console.log(pm.isMatch('aaa', '+(+(a))', { maxExtglobRecursion: 1 })); // true
-```
-
-#### POSIX brackets
-
-POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true.
-
-**Enable POSIX bracket support**
-
-```js
-console.log(pm.makeRe('[[:word:]]+', { posix: true }));
-//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
-```
-
-**Supported POSIX classes**
-
-The following named POSIX bracket expressions are supported:
-
-* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]`
-* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`.
-* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`.
-* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`.
-* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`.
-* `[:digit:]` - Numerical digits, equivalent to `[0-9]`.
-* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`.
-* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`.
-* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`.
-* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
-* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`.
-* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`.
-* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`.
-* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`.
-
-See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information.
-
-### Braces
-
-Picomatch only does [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) of comma-delimited lists (e.g. `a/{b,c}/d`). For advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch), which supports advanced syntax such as ranges (e.g. `{01..03}`) and increments (e.g. `{2..10..2}`).
-
-### Matching special characters as literals
-
-If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
-
-**Special Characters**
-
-Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
-
-To match any of the following characters as literals: `$^*+?()[]
-
-Examples:
-
-```js
-console.log(pm.makeRe('foo/bar \\(1\\)'));
-console.log(pm.makeRe('foo/bar \\(1\\)'));
-```
-
-
-
-
-## Library Comparisons
-
-The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets).
-
-| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` |
-| --- | --- | --- | --- | --- | --- | --- | --- |
-| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - |
-| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
-| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - |
-| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - |
-| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
-| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
-| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
-| File system operations | - | - | - | - | - | - | - |
-
-
-
-
-## Benchmarks
-
-Performance comparison of picomatch and minimatch.
-
-```
-# .makeRe star (*)
- picomatch x 3,251,247 ops/sec ±0.25% (95 runs sampled)
- minimatch x 497,224 ops/sec ±0.11% (100 runs sampled)
-
-# .makeRe star; dot=true (*)
- picomatch x 2,624,035 ops/sec ±0.16% (98 runs sampled)
- minimatch x 446,244 ops/sec ±0.63% (99 runs sampled)
-
-# .makeRe globstar (**)
- picomatch x 2,524,465 ops/sec ±0.13% (99 runs sampled)
- minimatch x 1,396,257 ops/sec ±0.58% (96 runs sampled)
-
-# .makeRe globstars (**/**/**)
- picomatch x 2,545,674 ops/sec ±0.10% (99 runs sampled)
- minimatch x 1,196,835 ops/sec ±0.63% (98 runs sampled)
-
-# .makeRe with leading star (*.txt)
- picomatch x 2,537,708 ops/sec ±0.11% (100 runs sampled)
- minimatch x 345,284 ops/sec ±0.64% (96 runs sampled)
-
-# .makeRe - basic braces ({a,b,c}*.txt)
- picomatch x 505,430 ops/sec ±1.04% (94 runs sampled)
- minimatch x 107,991 ops/sec ±0.54% (99 runs sampled)
-
-# .makeRe - short ranges ({a..z}*.txt)
- picomatch x 371,179 ops/sec ±2.91% (77 runs sampled)
- minimatch x 14,104 ops/sec ±0.61% (99 runs sampled)
-
-# .makeRe - medium ranges ({1..100000}*.txt)
- picomatch x 384,958 ops/sec ±1.70% (82 runs sampled)
- minimatch x 2.55 ops/sec ±3.22% (11 runs sampled)
-
-# .makeRe - long ranges ({1..10000000}*.txt)
- picomatch x 382,552 ops/sec ±1.52% (71 runs sampled)
- minimatch x 0.83 ops/sec ±5.67% (7 runs sampled))
-```
-
-
-
-
-## Philosophies
-
-The goal of this library is to be blazing fast, without compromising on accuracy.
-
-**Accuracy**
-
-The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`.
-
-Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
-
-**Performance**
-
-Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
-
-
-
-
-## About
-
-
-Contributing
-
-Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
-
-Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
-
-
-
-
-Running Tests
-
-Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
-
-```sh
-npm install && npm test
-```
-
-
-
-
-Building docs
-
-_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
-
-To generate the readme, run the following command:
-
-```sh
-npm install -g verbose/verb#dev verb-generate-readme && verb
-```
-
-
-
-### Author
-
-**Jon Schlinkert**
-
-* [GitHub Profile](https://github.com/jonschlinkert)
-* [Twitter Profile](https://twitter.com/jonschlinkert)
-* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
-
-### License
-
-Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert).
-Released under the [MIT License](LICENSE).
diff --git a/backend/dev-console/node_modules/picomatch/index.js b/backend/dev-console/node_modules/picomatch/index.js
deleted file mode 100644
index a753b1d..0000000
--- a/backend/dev-console/node_modules/picomatch/index.js
+++ /dev/null
@@ -1,17 +0,0 @@
-'use strict';
-
-const pico = require('./lib/picomatch');
-const utils = require('./lib/utils');
-
-function picomatch(glob, options, returnState = false) {
- // default to os.platform()
- if (options && (options.windows === null || options.windows === undefined)) {
- // don't mutate the original options object
- options = { ...options, windows: utils.isWindows() };
- }
-
- return pico(glob, options, returnState);
-}
-
-Object.assign(picomatch, pico);
-module.exports = picomatch;
diff --git a/backend/dev-console/node_modules/picomatch/lib/constants.js b/backend/dev-console/node_modules/picomatch/lib/constants.js
deleted file mode 100644
index f0aeda7..0000000
--- a/backend/dev-console/node_modules/picomatch/lib/constants.js
+++ /dev/null
@@ -1,184 +0,0 @@
-'use strict';
-
-const WIN_SLASH = '\\\\/';
-const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
-
-const DEFAULT_MAX_EXTGLOB_RECURSION = 0;
-
-/**
- * Posix glob regex
- */
-
-const DOT_LITERAL = '\\.';
-const PLUS_LITERAL = '\\+';
-const QMARK_LITERAL = '\\?';
-const SLASH_LITERAL = '\\/';
-const ONE_CHAR = '(?=.)';
-const QMARK = '[^/]';
-const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
-const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
-const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
-const NO_DOT = `(?!${DOT_LITERAL})`;
-const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
-const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
-const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
-const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
-const STAR = `${QMARK}*?`;
-const SEP = '/';
-
-const POSIX_CHARS = {
- DOT_LITERAL,
- PLUS_LITERAL,
- QMARK_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- QMARK,
- END_ANCHOR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR,
- SEP
-};
-
-/**
- * Windows glob regex
- */
-
-const WINDOWS_CHARS = {
- ...POSIX_CHARS,
-
- SLASH_LITERAL: `[${WIN_SLASH}]`,
- QMARK: WIN_NO_SLASH,
- STAR: `${WIN_NO_SLASH}*?`,
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
- NO_DOT: `(?!${DOT_LITERAL})`,
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
- SEP: '\\'
-};
-
-/**
- * POSIX Bracket Regex
- */
-
-const POSIX_REGEX_SOURCE = {
- __proto__: null,
- alnum: 'a-zA-Z0-9',
- alpha: 'a-zA-Z',
- ascii: '\\x00-\\x7F',
- blank: ' \\t',
- cntrl: '\\x00-\\x1F\\x7F',
- digit: '0-9',
- graph: '\\x21-\\x7E',
- lower: 'a-z',
- print: '\\x20-\\x7E ',
- punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
- space: ' \\t\\r\\n\\v\\f',
- upper: 'A-Z',
- word: 'A-Za-z0-9_',
- xdigit: 'A-Fa-f0-9'
-};
-
-module.exports = {
- DEFAULT_MAX_EXTGLOB_RECURSION,
- MAX_LENGTH: 1024 * 64,
- POSIX_REGEX_SOURCE,
-
- // regular expressions
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
-
- // Replace globs with equivalent patterns to reduce parsing time.
- REPLACEMENTS: {
- __proto__: null,
- '***': '*',
- '**/**': '**',
- '**/**/**': '**'
- },
-
- // Digits
- CHAR_0: 48, /* 0 */
- CHAR_9: 57, /* 9 */
-
- // Alphabet chars.
- CHAR_UPPERCASE_A: 65, /* A */
- CHAR_LOWERCASE_A: 97, /* a */
- CHAR_UPPERCASE_Z: 90, /* Z */
- CHAR_LOWERCASE_Z: 122, /* z */
-
- CHAR_LEFT_PARENTHESES: 40, /* ( */
- CHAR_RIGHT_PARENTHESES: 41, /* ) */
-
- CHAR_ASTERISK: 42, /* * */
-
- // Non-alphabetic chars.
- CHAR_AMPERSAND: 38, /* & */
- CHAR_AT: 64, /* @ */
- CHAR_BACKWARD_SLASH: 92, /* \ */
- CHAR_CARRIAGE_RETURN: 13, /* \r */
- CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
- CHAR_COLON: 58, /* : */
- CHAR_COMMA: 44, /* , */
- CHAR_DOT: 46, /* . */
- CHAR_DOUBLE_QUOTE: 34, /* " */
- CHAR_EQUAL: 61, /* = */
- CHAR_EXCLAMATION_MARK: 33, /* ! */
- CHAR_FORM_FEED: 12, /* \f */
- CHAR_FORWARD_SLASH: 47, /* / */
- CHAR_GRAVE_ACCENT: 96, /* ` */
- CHAR_HASH: 35, /* # */
- CHAR_HYPHEN_MINUS: 45, /* - */
- CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
- CHAR_LEFT_CURLY_BRACE: 123, /* { */
- CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
- CHAR_LINE_FEED: 10, /* \n */
- CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
- CHAR_PERCENT: 37, /* % */
- CHAR_PLUS: 43, /* + */
- CHAR_QUESTION_MARK: 63, /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
- CHAR_RIGHT_CURLY_BRACE: 125, /* } */
- CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
- CHAR_SEMICOLON: 59, /* ; */
- CHAR_SINGLE_QUOTE: 39, /* ' */
- CHAR_SPACE: 32, /* */
- CHAR_TAB: 9, /* \t */
- CHAR_UNDERSCORE: 95, /* _ */
- CHAR_VERTICAL_LINE: 124, /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
-
- /**
- * Create EXTGLOB_CHARS
- */
-
- extglobChars(chars) {
- return {
- '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
- '?': { type: 'qmark', open: '(?:', close: ')?' },
- '+': { type: 'plus', open: '(?:', close: ')+' },
- '*': { type: 'star', open: '(?:', close: ')*' },
- '@': { type: 'at', open: '(?:', close: ')' }
- };
- },
-
- /**
- * Create GLOB_CHARS
- */
-
- globChars(win32) {
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
- }
-};
diff --git a/backend/dev-console/node_modules/picomatch/lib/parse.js b/backend/dev-console/node_modules/picomatch/lib/parse.js
deleted file mode 100644
index 57d994a..0000000
--- a/backend/dev-console/node_modules/picomatch/lib/parse.js
+++ /dev/null
@@ -1,1386 +0,0 @@
-'use strict';
-
-const constants = require('./constants');
-const utils = require('./utils');
-
-/**
- * Constants
- */
-
-const {
- MAX_LENGTH,
- POSIX_REGEX_SOURCE,
- REGEX_NON_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_BACKREF,
- REPLACEMENTS
-} = constants;
-
-/**
- * Helpers
- */
-
-const expandRange = (args, options) => {
- if (typeof options.expandRange === 'function') {
- return options.expandRange(...args, options);
- }
-
- args.sort();
- const value = `[${args.join('-')}]`;
-
- try {
- /* eslint-disable-next-line no-new */
- new RegExp(value);
- } catch (ex) {
- return args.map(v => utils.escapeRegex(v)).join('..');
- }
-
- return value;
-};
-
-/**
- * Create the message for a syntax error
- */
-
-const syntaxError = (type, char) => {
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
-};
-
-const splitTopLevel = input => {
- const parts = [];
- let bracket = 0;
- let paren = 0;
- let quote = 0;
- let value = '';
- let escaped = false;
-
- for (const ch of input) {
- if (escaped === true) {
- value += ch;
- escaped = false;
- continue;
- }
-
- if (ch === '\\') {
- value += ch;
- escaped = true;
- continue;
- }
-
- if (ch === '"') {
- quote = quote === 1 ? 0 : 1;
- value += ch;
- continue;
- }
-
- if (quote === 0) {
- if (ch === '[') {
- bracket++;
- } else if (ch === ']' && bracket > 0) {
- bracket--;
- } else if (bracket === 0) {
- if (ch === '(') {
- paren++;
- } else if (ch === ')' && paren > 0) {
- paren--;
- } else if (ch === '|' && paren === 0) {
- parts.push(value);
- value = '';
- continue;
- }
- }
- }
-
- value += ch;
- }
-
- parts.push(value);
- return parts;
-};
-
-const isPlainBranch = branch => {
- let escaped = false;
-
- for (const ch of branch) {
- if (escaped === true) {
- escaped = false;
- continue;
- }
-
- if (ch === '\\') {
- escaped = true;
- continue;
- }
-
- if (/[?*+@!()[\]{}]/.test(ch)) {
- return false;
- }
- }
-
- return true;
-};
-
-const normalizeSimpleBranch = branch => {
- let value = branch.trim();
- let changed = true;
-
- while (changed === true) {
- changed = false;
-
- if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
- value = value.slice(2, -1);
- changed = true;
- }
- }
-
- if (!isPlainBranch(value)) {
- return;
- }
-
- return value.replace(/\\(.)/g, '$1');
-};
-
-const hasRepeatedCharPrefixOverlap = branches => {
- const values = branches.map(normalizeSimpleBranch).filter(Boolean);
-
- for (let i = 0; i < values.length; i++) {
- for (let j = i + 1; j < values.length; j++) {
- const a = values[i];
- const b = values[j];
- const char = a[0];
-
- if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
- continue;
- }
-
- if (a === b || a.startsWith(b) || b.startsWith(a)) {
- return true;
- }
- }
- }
-
- return false;
-};
-
-const parseRepeatedExtglob = (pattern, requireEnd = true) => {
- if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') {
- return;
- }
-
- let bracket = 0;
- let paren = 0;
- let quote = 0;
- let escaped = false;
-
- for (let i = 1; i < pattern.length; i++) {
- const ch = pattern[i];
-
- if (escaped === true) {
- escaped = false;
- continue;
- }
-
- if (ch === '\\') {
- escaped = true;
- continue;
- }
-
- if (ch === '"') {
- quote = quote === 1 ? 0 : 1;
- continue;
- }
-
- if (quote === 1) {
- continue;
- }
-
- if (ch === '[') {
- bracket++;
- continue;
- }
-
- if (ch === ']' && bracket > 0) {
- bracket--;
- continue;
- }
-
- if (bracket > 0) {
- continue;
- }
-
- if (ch === '(') {
- paren++;
- continue;
- }
-
- if (ch === ')') {
- paren--;
-
- if (paren === 0) {
- if (requireEnd === true && i !== pattern.length - 1) {
- return;
- }
-
- return {
- type: pattern[0],
- body: pattern.slice(2, i),
- end: i
- };
- }
- }
- }
-};
-
-const getStarExtglobSequenceOutput = pattern => {
- let index = 0;
- const chars = [];
-
- while (index < pattern.length) {
- const match = parseRepeatedExtglob(pattern.slice(index), false);
-
- if (!match || match.type !== '*') {
- return;
- }
-
- const branches = splitTopLevel(match.body).map(branch => branch.trim());
- if (branches.length !== 1) {
- return;
- }
-
- const branch = normalizeSimpleBranch(branches[0]);
- if (!branch || branch.length !== 1) {
- return;
- }
-
- chars.push(branch);
- index += match.end + 1;
- }
-
- if (chars.length < 1) {
- return;
- }
-
- const source = chars.length === 1
- ? utils.escapeRegex(chars[0])
- : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`;
-
- return `${source}*`;
-};
-
-const repeatedExtglobRecursion = pattern => {
- let depth = 0;
- let value = pattern.trim();
- let match = parseRepeatedExtglob(value);
-
- while (match) {
- depth++;
- value = match.body.trim();
- match = parseRepeatedExtglob(value);
- }
-
- return depth;
-};
-
-const analyzeRepeatedExtglob = (body, options) => {
- if (options.maxExtglobRecursion === false) {
- return { risky: false };
- }
-
- const max =
- typeof options.maxExtglobRecursion === 'number'
- ? options.maxExtglobRecursion
- : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
-
- const branches = splitTopLevel(body).map(branch => branch.trim());
-
- if (branches.length > 1) {
- if (
- branches.some(branch => branch === '') ||
- branches.some(branch => /^[*?]+$/.test(branch)) ||
- hasRepeatedCharPrefixOverlap(branches)
- ) {
- return { risky: true };
- }
- }
-
- for (const branch of branches) {
- const safeOutput = getStarExtglobSequenceOutput(branch);
- if (safeOutput) {
- return { risky: true, safeOutput };
- }
-
- if (repeatedExtglobRecursion(branch) > max) {
- return { risky: true };
- }
- }
-
- return { risky: false };
-};
-
-/**
- * Parse the given input string.
- * @param {String} input
- * @param {Object} options
- * @return {Object}
- */
-
-const parse = (input, options) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
-
- input = REPLACEMENTS[input] || input;
-
- const opts = { ...options };
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
-
- let len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
-
- const bos = { type: 'bos', value: '', output: opts.prepend || '' };
- const tokens = [bos];
-
- const capture = opts.capture ? '' : '?:';
-
- // create constants based on platform, for windows or posix
- const PLATFORM_CHARS = constants.globChars(opts.windows);
- const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
-
- const {
- DOT_LITERAL,
- PLUS_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
- } = PLATFORM_CHARS;
-
- const globstar = opts => {
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
-
- const nodot = opts.dot ? '' : NO_DOT;
- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
- let star = opts.bash === true ? globstar(opts) : STAR;
-
- if (opts.capture) {
- star = `(${star})`;
- }
-
- // minimatch options support
- if (typeof opts.noext === 'boolean') {
- opts.noextglob = opts.noext;
- }
-
- const state = {
- input,
- index: -1,
- start: 0,
- dot: opts.dot === true,
- consumed: '',
- output: '',
- prefix: '',
- backtrack: false,
- negated: false,
- brackets: 0,
- braces: 0,
- parens: 0,
- quotes: 0,
- globstar: false,
- tokens
- };
-
- input = utils.removePrefix(input, state);
- len = input.length;
-
- const extglobs = [];
- const braces = [];
- const stack = [];
- let prev = bos;
- let value;
-
- /**
- * Tokenizing helpers
- */
-
- const eos = () => state.index === len - 1;
- const peek = state.peek = (n = 1) => input[state.index + n];
- const advance = state.advance = () => input[++state.index] || '';
- const remaining = () => input.slice(state.index + 1);
- const consume = (value = '', num = 0) => {
- state.consumed += value;
- state.index += num;
- };
-
- const append = token => {
- state.output += token.output != null ? token.output : token.value;
- consume(token.value);
- };
-
- const negate = () => {
- let count = 1;
-
- while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
- advance();
- state.start++;
- count++;
- }
-
- if (count % 2 === 0) {
- return false;
- }
-
- state.negated = true;
- state.start++;
- return true;
- };
-
- const increment = type => {
- state[type]++;
- stack.push(type);
- };
-
- const decrement = type => {
- state[type]--;
- stack.pop();
- };
-
- /**
- * Push tokens onto the tokens array. This helper speeds up
- * tokenizing by 1) helping us avoid backtracking as much as possible,
- * and 2) helping us avoid creating extra tokens when consecutive
- * characters are plain text. This improves performance and simplifies
- * lookbehinds.
- */
-
- const push = tok => {
- if (prev.type === 'globstar') {
- const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
- const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
-
- if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
- state.output = state.output.slice(0, -prev.output.length);
- prev.type = 'star';
- prev.value = '*';
- prev.output = star;
- state.output += prev.output;
- }
- }
-
- if (extglobs.length && tok.type !== 'paren') {
- extglobs[extglobs.length - 1].inner += tok.value;
- }
-
- if (tok.value || tok.output) append(tok);
- if (prev && prev.type === 'text' && tok.type === 'text') {
- prev.output = (prev.output || prev.value) + tok.value;
- prev.value += tok.value;
- return;
- }
-
- tok.prev = prev;
- tokens.push(tok);
- prev = tok;
- };
-
- const extglobOpen = (type, value) => {
- const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
-
- token.prev = prev;
- token.parens = state.parens;
- token.output = state.output;
- token.startIndex = state.index;
- token.tokensIndex = tokens.length;
- const output = (opts.capture ? '(' : '') + token.open;
-
- increment('parens');
- push({ type, value, output: state.output ? '' : ONE_CHAR });
- push({ type: 'paren', extglob: true, value: advance(), output });
- extglobs.push(token);
- };
-
- const extglobClose = token => {
- const literal = input.slice(token.startIndex, state.index + 1);
- const body = input.slice(token.startIndex + 2, state.index);
- const analysis = analyzeRepeatedExtglob(body, opts);
-
- if ((token.type === 'plus' || token.type === 'star') && analysis.risky) {
- const safeOutput = analysis.safeOutput
- ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput)
- : undefined;
- const open = tokens[token.tokensIndex];
-
- open.type = 'text';
- open.value = literal;
- open.output = safeOutput || utils.escapeRegex(literal);
-
- for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
- tokens[i].value = '';
- tokens[i].output = '';
- delete tokens[i].suffix;
- }
-
- state.output = token.output + open.output;
- state.backtrack = true;
-
- push({ type: 'paren', extglob: true, value, output: '' });
- decrement('parens');
- return;
- }
-
- let output = token.close + (opts.capture ? ')' : '');
- let rest;
-
- if (token.type === 'negate') {
- let extglobStar = star;
-
- if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
- extglobStar = globstar(opts);
- }
-
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
- output = token.close = `)$))${extglobStar}`;
- }
-
- if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
- // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
- // In this case, we need to parse the string and use it in the output of the original pattern.
- // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
- //
- // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
- const expression = parse(rest, { ...options, fastpaths: false }).output;
-
- output = token.close = `)${expression})${extglobStar})`;
- }
-
- if (token.prev.type === 'bos') {
- state.negatedExtglob = true;
- }
- }
-
- push({ type: 'paren', extglob: true, value, output });
- decrement('parens');
- };
-
- /**
- * Fast paths
- */
-
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
- let backslashes = false;
-
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
- if (first === '\\') {
- backslashes = true;
- return m;
- }
-
- if (first === '?') {
- if (esc) {
- return esc + first + (rest ? QMARK.repeat(rest.length) : '');
- }
- if (index === 0) {
- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
- }
- return QMARK.repeat(chars.length);
- }
-
- if (first === '.') {
- return DOT_LITERAL.repeat(chars.length);
- }
-
- if (first === '*') {
- if (esc) {
- return esc + first + (rest ? star : '');
- }
- return star;
- }
- return esc ? m : `\\${m}`;
- });
-
- if (backslashes === true) {
- if (opts.unescape === true) {
- output = output.replace(/\\/g, '');
- } else {
- output = output.replace(/\\+/g, m => {
- return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
- });
- }
- }
-
- if (output === input && opts.contains === true) {
- state.output = input;
- return state;
- }
-
- state.output = utils.wrapOutput(output, state, options);
- return state;
- }
-
- /**
- * Tokenize input until we reach end-of-string
- */
-
- while (!eos()) {
- value = advance();
-
- if (value === '\u0000') {
- continue;
- }
-
- /**
- * Escaped characters
- */
-
- if (value === '\\') {
- const next = peek();
-
- if (next === '/' && opts.bash !== true) {
- continue;
- }
-
- if (next === '.' || next === ';') {
- continue;
- }
-
- if (!next) {
- value += '\\';
- push({ type: 'text', value });
- continue;
- }
-
- // collapse slashes to reduce potential for exploits
- const match = /^\\+/.exec(remaining());
- let slashes = 0;
-
- if (match && match[0].length > 2) {
- slashes = match[0].length;
- state.index += slashes;
- if (slashes % 2 !== 0) {
- value += '\\';
- }
- }
-
- if (opts.unescape === true) {
- value = advance();
- } else {
- value += advance();
- }
-
- if (state.brackets === 0) {
- push({ type: 'text', value });
- continue;
- }
- }
-
- /**
- * If we're inside a regex character class, continue
- * until we reach the closing bracket.
- */
-
- if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
- if (opts.posix !== false && value === ':') {
- const inner = prev.value.slice(1);
- if (inner.includes('[')) {
- prev.posix = true;
-
- if (inner.includes(':')) {
- const idx = prev.value.lastIndexOf('[');
- const pre = prev.value.slice(0, idx);
- const rest = prev.value.slice(idx + 2);
- const posix = POSIX_REGEX_SOURCE[rest];
- if (posix) {
- prev.value = pre + posix;
- state.backtrack = true;
- advance();
-
- if (!bos.output && tokens.indexOf(prev) === 1) {
- bos.output = ONE_CHAR;
- }
- continue;
- }
- }
- }
- }
-
- if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
- value = `\\${value}`;
- }
-
- if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
- value = `\\${value}`;
- }
-
- if (opts.posix === true && value === '!' && prev.value === '[') {
- value = '^';
- }
-
- prev.value += value;
- append({ value });
- continue;
- }
-
- /**
- * If we're inside a quoted string, continue
- * until we reach the closing double quote.
- */
-
- if (state.quotes === 1 && value !== '"') {
- value = utils.escapeRegex(value);
- prev.value += value;
- append({ value });
- continue;
- }
-
- /**
- * Double quotes
- */
-
- if (value === '"') {
- state.quotes = state.quotes === 1 ? 0 : 1;
- if (opts.keepQuotes === true) {
- push({ type: 'text', value });
- }
- continue;
- }
-
- /**
- * Parentheses
- */
-
- if (value === '(') {
- increment('parens');
- push({ type: 'paren', value });
- continue;
- }
-
- if (value === ')') {
- if (state.parens === 0 && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('opening', '('));
- }
-
- const extglob = extglobs[extglobs.length - 1];
- if (extglob && state.parens === extglob.parens + 1) {
- extglobClose(extglobs.pop());
- continue;
- }
-
- push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
- decrement('parens');
- continue;
- }
-
- /**
- * Square brackets
- */
-
- if (value === '[') {
- if (opts.nobracket === true || !remaining().includes(']')) {
- if (opts.nobracket !== true && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('closing', ']'));
- }
-
- value = `\\${value}`;
- } else {
- increment('brackets');
- }
-
- push({ type: 'bracket', value });
- continue;
- }
-
- if (value === ']') {
- if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
- push({ type: 'text', value, output: `\\${value}` });
- continue;
- }
-
- if (state.brackets === 0) {
- if (opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('opening', '['));
- }
-
- push({ type: 'text', value, output: `\\${value}` });
- continue;
- }
-
- decrement('brackets');
-
- const prevValue = prev.value.slice(1);
- if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
- value = `/${value}`;
- }
-
- prev.value += value;
- append({ value });
-
- // when literal brackets are explicitly disabled
- // assume we should match with a regex character class
- if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
- continue;
- }
-
- const escaped = utils.escapeRegex(prev.value);
- state.output = state.output.slice(0, -prev.value.length);
-
- // when literal brackets are explicitly enabled
- // assume we should escape the brackets to match literal characters
- if (opts.literalBrackets === true) {
- state.output += escaped;
- prev.value = escaped;
- continue;
- }
-
- // when the user specifies nothing, try to match both
- prev.value = `(${capture}${escaped}|${prev.value})`;
- state.output += prev.value;
- continue;
- }
-
- /**
- * Braces
- */
-
- if (value === '{' && opts.nobrace !== true) {
- increment('braces');
-
- const open = {
- type: 'brace',
- value,
- output: '(',
- outputIndex: state.output.length,
- tokensIndex: state.tokens.length
- };
-
- braces.push(open);
- push(open);
- continue;
- }
-
- if (value === '}') {
- const brace = braces[braces.length - 1];
-
- if (opts.nobrace === true || !brace) {
- push({ type: 'text', value, output: value });
- continue;
- }
-
- let output = ')';
-
- if (brace.dots === true) {
- const arr = tokens.slice();
- const range = [];
-
- for (let i = arr.length - 1; i >= 0; i--) {
- tokens.pop();
- if (arr[i].type === 'brace') {
- break;
- }
- if (arr[i].type !== 'dots') {
- range.unshift(arr[i].value);
- }
- }
-
- output = expandRange(range, opts);
- state.backtrack = true;
- }
-
- if (brace.comma !== true && brace.dots !== true) {
- const out = state.output.slice(0, brace.outputIndex);
- const toks = state.tokens.slice(brace.tokensIndex);
- brace.value = brace.output = '\\{';
- value = output = '\\}';
- state.output = out;
- for (const t of toks) {
- state.output += (t.output || t.value);
- }
- }
-
- push({ type: 'brace', value, output });
- decrement('braces');
- braces.pop();
- continue;
- }
-
- /**
- * Pipes
- */
-
- if (value === '|') {
- if (extglobs.length > 0) {
- extglobs[extglobs.length - 1].conditions++;
- }
- push({ type: 'text', value });
- continue;
- }
-
- /**
- * Commas
- */
-
- if (value === ',') {
- let output = value;
-
- const brace = braces[braces.length - 1];
- if (brace && stack[stack.length - 1] === 'braces') {
- brace.comma = true;
- output = '|';
- }
-
- push({ type: 'comma', value, output });
- continue;
- }
-
- /**
- * Slashes
- */
-
- if (value === '/') {
- // if the beginning of the glob is "./", advance the start
- // to the current index, and don't add the "./" characters
- // to the state. This greatly simplifies lookbehinds when
- // checking for BOS characters like "!" and "." (not "./")
- if (prev.type === 'dot' && state.index === state.start + 1) {
- state.start = state.index + 1;
- state.consumed = '';
- state.output = '';
- tokens.pop();
- prev = bos; // reset "prev" to the first token
- continue;
- }
-
- push({ type: 'slash', value, output: SLASH_LITERAL });
- continue;
- }
-
- /**
- * Dots
- */
-
- if (value === '.') {
- if (state.braces > 0 && prev.type === 'dot') {
- if (prev.value === '.') prev.output = DOT_LITERAL;
- const brace = braces[braces.length - 1];
- prev.type = 'dots';
- prev.output += value;
- prev.value += value;
- brace.dots = true;
- continue;
- }
-
- if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
- push({ type: 'text', value, output: DOT_LITERAL });
- continue;
- }
-
- push({ type: 'dot', value, output: DOT_LITERAL });
- continue;
- }
-
- /**
- * Question marks
- */
-
- if (value === '?') {
- const isGroup = prev && prev.value === '(';
- if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('qmark', value);
- continue;
- }
-
- if (prev && prev.type === 'paren') {
- const next = peek();
- let output = value;
-
- if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
- output = `\\${value}`;
- }
-
- push({ type: 'text', value, output });
- continue;
- }
-
- if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
- push({ type: 'qmark', value, output: QMARK_NO_DOT });
- continue;
- }
-
- push({ type: 'qmark', value, output: QMARK });
- continue;
- }
-
- /**
- * Exclamation
- */
-
- if (value === '!') {
- if (opts.noextglob !== true && peek() === '(') {
- if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
- extglobOpen('negate', value);
- continue;
- }
- }
-
- if (opts.nonegate !== true && state.index === 0) {
- negate();
- continue;
- }
- }
-
- /**
- * Plus
- */
-
- if (value === '+') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('plus', value);
- continue;
- }
-
- if ((prev && prev.value === '(') || opts.regex === false) {
- push({ type: 'plus', value, output: PLUS_LITERAL });
- continue;
- }
-
- if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
- push({ type: 'plus', value });
- continue;
- }
-
- push({ type: 'plus', value: PLUS_LITERAL });
- continue;
- }
-
- /**
- * Plain text
- */
-
- if (value === '@') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- push({ type: 'at', extglob: true, value, output: '' });
- continue;
- }
-
- push({ type: 'text', value });
- continue;
- }
-
- /**
- * Plain text
- */
-
- if (value !== '*') {
- if (value === '$' || value === '^') {
- value = `\\${value}`;
- }
-
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
- if (match) {
- value += match[0];
- state.index += match[0].length;
- }
-
- push({ type: 'text', value });
- continue;
- }
-
- /**
- * Stars
- */
-
- if (prev && (prev.type === 'globstar' || prev.star === true)) {
- prev.type = 'star';
- prev.star = true;
- prev.value += value;
- prev.output = star;
- state.backtrack = true;
- state.globstar = true;
- consume(value);
- continue;
- }
-
- let rest = remaining();
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
- extglobOpen('star', value);
- continue;
- }
-
- if (prev.type === 'star') {
- if (opts.noglobstar === true) {
- consume(value);
- continue;
- }
-
- const prior = prev.prev;
- const before = prior.prev;
- const isStart = prior.type === 'slash' || prior.type === 'bos';
- const afterStar = before && (before.type === 'star' || before.type === 'globstar');
-
- if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
- push({ type: 'star', value, output: '' });
- continue;
- }
-
- const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
- const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
- if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
- push({ type: 'star', value, output: '' });
- continue;
- }
-
- // strip consecutive `/**/`
- while (rest.slice(0, 3) === '/**') {
- const after = input[state.index + 4];
- if (after && after !== '/') {
- break;
- }
- rest = rest.slice(3);
- consume('/**', 3);
- }
-
- if (prior.type === 'bos' && eos()) {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = globstar(opts);
- state.output = prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
-
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
-
- prev.type = 'globstar';
- prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
- prev.value += value;
- state.globstar = true;
- state.output += prior.output + prev.output;
- consume(value);
- continue;
- }
-
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
- const end = rest[1] !== void 0 ? '|$' : '';
-
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
-
- prev.type = 'globstar';
- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
- prev.value += value;
-
- state.output += prior.output + prev.output;
- state.globstar = true;
-
- consume(value + advance());
-
- push({ type: 'slash', value: '/', output: '' });
- continue;
- }
-
- if (prior.type === 'bos' && rest[0] === '/') {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
- state.output = prev.output;
- state.globstar = true;
- consume(value + advance());
- push({ type: 'slash', value: '/', output: '' });
- continue;
- }
-
- // remove single star from output
- state.output = state.output.slice(0, -prev.output.length);
-
- // reset previous token to globstar
- prev.type = 'globstar';
- prev.output = globstar(opts);
- prev.value += value;
-
- // reset output with globstar
- state.output += prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
-
- const token = { type: 'star', value, output: star };
-
- if (opts.bash === true) {
- token.output = '.*?';
- if (prev.type === 'bos' || prev.type === 'slash') {
- token.output = nodot + token.output;
- }
- push(token);
- continue;
- }
-
- if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
- token.output = value;
- push(token);
- continue;
- }
-
- if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
- if (prev.type === 'dot') {
- state.output += NO_DOT_SLASH;
- prev.output += NO_DOT_SLASH;
-
- } else if (opts.dot === true) {
- state.output += NO_DOTS_SLASH;
- prev.output += NO_DOTS_SLASH;
-
- } else {
- state.output += nodot;
- prev.output += nodot;
- }
-
- if (peek() !== '*') {
- state.output += ONE_CHAR;
- prev.output += ONE_CHAR;
- }
- }
-
- push(token);
- }
-
- while (state.brackets > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
- state.output = utils.escapeLast(state.output, '[');
- decrement('brackets');
- }
-
- while (state.parens > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
- state.output = utils.escapeLast(state.output, '(');
- decrement('parens');
- }
-
- while (state.braces > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
- state.output = utils.escapeLast(state.output, '{');
- decrement('braces');
- }
-
- if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
- push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
- }
-
- // rebuild the output if we had to backtrack at any point
- if (state.backtrack === true) {
- state.output = '';
-
- for (const token of state.tokens) {
- state.output += token.output != null ? token.output : token.value;
-
- if (token.suffix) {
- state.output += token.suffix;
- }
- }
- }
-
- return state;
-};
-
-/**
- * Fast paths for creating regular expressions for common glob patterns.
- * This can significantly speed up processing and has very little downside
- * impact when none of the fast paths match.
- */
-
-parse.fastpaths = (input, options) => {
- const opts = { ...options };
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- const len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
-
- input = REPLACEMENTS[input] || input;
-
- // create constants based on platform, for windows or posix
- const {
- DOT_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOTS_SLASH,
- STAR,
- START_ANCHOR
- } = constants.globChars(opts.windows);
-
- const nodot = opts.dot ? NO_DOTS : NO_DOT;
- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
- const capture = opts.capture ? '' : '?:';
- const state = { negated: false, prefix: '' };
- let star = opts.bash === true ? '.*?' : STAR;
-
- if (opts.capture) {
- star = `(${star})`;
- }
-
- const globstar = opts => {
- if (opts.noglobstar === true) return star;
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
-
- const create = str => {
- switch (str) {
- case '*':
- return `${nodot}${ONE_CHAR}${star}`;
-
- case '.*':
- return `${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- case '*.*':
- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- case '*/*':
- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
-
- case '**':
- return nodot + globstar(opts);
-
- case '**/*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
-
- case '**/*.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- case '**/.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- default: {
- const match = /^(.*?)\.(\w+)$/.exec(str);
- if (!match) return;
-
- const source = create(match[1]);
- if (!source) return;
-
- return source + DOT_LITERAL + match[2];
- }
- }
- };
-
- const output = utils.removePrefix(input, state);
- let source = create(output);
-
- if (source && opts.strictSlashes !== true) {
- source += `${SLASH_LITERAL}?`;
- }
-
- return source;
-};
-
-module.exports = parse;
diff --git a/backend/dev-console/node_modules/picomatch/lib/picomatch.js b/backend/dev-console/node_modules/picomatch/lib/picomatch.js
deleted file mode 100644
index fbb8b1c..0000000
--- a/backend/dev-console/node_modules/picomatch/lib/picomatch.js
+++ /dev/null
@@ -1,349 +0,0 @@
-'use strict';
-
-const scan = require('./scan');
-const parse = require('./parse');
-const utils = require('./utils');
-const constants = require('./constants');
-const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
-
-/**
- * Creates a matcher function from one or more glob patterns. The
- * returned function takes a string to match as its first argument,
- * and returns true if the string is a match. The returned matcher
- * function also takes a boolean as the second argument that, when true,
- * returns an object with additional information.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch(glob[, options]);
- *
- * const isMatch = picomatch('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @name picomatch
- * @param {String|Array} `globs` One or more glob patterns.
- * @param {Object=} `options`
- * @return {Function=} Returns a matcher function.
- * @api public
- */
-
-const picomatch = (glob, options, returnState = false) => {
- if (Array.isArray(glob)) {
- const fns = glob.map(input => picomatch(input, options, returnState));
- const arrayMatcher = str => {
- for (const isMatch of fns) {
- const state = isMatch(str);
- if (state) return state;
- }
- return false;
- };
- return arrayMatcher;
- }
-
- const isState = isObject(glob) && glob.tokens && glob.input;
-
- if (glob === '' || (typeof glob !== 'string' && !isState)) {
- throw new TypeError('Expected pattern to be a non-empty string');
- }
-
- const opts = options || {};
- const posix = opts.windows;
- const regex = isState
- ? picomatch.compileRe(glob, options)
- : picomatch.makeRe(glob, options, false, true);
-
- const state = regex.state;
- delete regex.state;
-
- let isIgnored = () => false;
- if (opts.ignore) {
- const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
- isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
- }
-
- const matcher = (input, returnObject = false) => {
- const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
- const result = { glob, state, regex, posix, input, output, match, isMatch };
-
- if (typeof opts.onResult === 'function') {
- opts.onResult(result);
- }
-
- if (isMatch === false) {
- result.isMatch = false;
- return returnObject ? result : false;
- }
-
- if (isIgnored(input)) {
- if (typeof opts.onIgnore === 'function') {
- opts.onIgnore(result);
- }
- result.isMatch = false;
- return returnObject ? result : false;
- }
-
- if (typeof opts.onMatch === 'function') {
- opts.onMatch(result);
- }
- return returnObject ? result : true;
- };
-
- if (returnState) {
- matcher.state = state;
- }
-
- return matcher;
-};
-
-/**
- * Test `input` with the given `regex`. This is used by the main
- * `picomatch()` function to test the input string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.test(input, regex[, options]);
- *
- * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
- * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp} `regex`
- * @return {Object} Returns an object with matching info.
- * @api public
- */
-
-picomatch.test = (input, regex, options, { glob, posix } = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected input to be a string');
- }
-
- if (input === '') {
- return { isMatch: false, output: '' };
- }
-
- const opts = options || {};
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
- let match = input === glob;
- let output = (match && format) ? format(input) : input;
-
- if (match === false) {
- output = format ? format(input) : input;
- match = output === glob;
- }
-
- if (match === false || opts.capture === true) {
- if (opts.matchBase === true || opts.basename === true) {
- match = picomatch.matchBase(input, regex, options, posix);
- } else {
- match = regex.exec(output);
- }
- }
-
- return { isMatch: Boolean(match), match, output };
-};
-
-/**
- * Match the basename of a filepath.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.matchBase(input, glob[, options]);
- * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
- * @return {Boolean}
- * @api public
- */
-
-picomatch.matchBase = (input, glob, options) => {
- const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
- return regex.test(utils.basename(input));
-};
-
-/**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.isMatch(string, patterns[, options]);
- *
- * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String|Array} str The string to test.
- * @param {String|Array} patterns One or more glob patterns to use for matching.
- * @param {Object} [options] See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
-
-picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
-
-/**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const result = picomatch.parse(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
- * @api public
- */
-
-picomatch.parse = (pattern, options) => {
- if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
- return parse(pattern, { ...options, fastpaths: false });
-};
-
-/**
- * Scan a glob pattern to separate the pattern into segments.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.scan(input[, options]);
- *
- * const result = picomatch.scan('!./foo/*.js');
- * console.log(result);
- * { prefix: '!./',
- * input: '!./foo/*.js',
- * start: 3,
- * base: 'foo',
- * glob: '*.js',
- * isBrace: false,
- * isBracket: false,
- * isGlob: true,
- * isExtglob: false,
- * isGlobstar: false,
- * negated: true }
- * ```
- * @param {String} `input` Glob pattern to scan.
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
- */
-
-picomatch.scan = (input, options) => scan(input, options);
-
-/**
- * Compile a regular expression from the `state` object returned by the
- * [parse()](#parse) method.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const state = picomatch.parse('*.js');
- * // picomatch.compileRe(state[, options]);
- *
- * console.log(picomatch.compileRe(state));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {Object} `state`
- * @param {Object} `options`
- * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
- * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
- * @return {RegExp}
- * @api public
- */
-
-picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
- if (returnOutput === true) {
- return state.output;
- }
-
- const opts = options || {};
- const prepend = opts.contains ? '' : '^';
- const append = opts.contains ? '' : '$';
-
- let source = `${prepend}(?:${state.output})${append}`;
- if (state && state.negated === true) {
- source = `^(?!${source}).*$`;
- }
-
- const regex = picomatch.toRegex(source, options);
- if (returnState === true) {
- regex.state = state;
- }
-
- return regex;
-};
-
-/**
- * Create a regular expression from a parsed glob pattern.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.makeRe(state[, options]);
- *
- * const result = picomatch.makeRe('*.js');
- * console.log(result);
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `state` The object returned from the `.parse` method.
- * @param {Object} `options`
- * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
- * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
- */
-
-picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
- if (!input || typeof input !== 'string') {
- throw new TypeError('Expected a non-empty string');
- }
-
- let parsed = { negated: false, fastpaths: true };
-
- if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
- parsed.output = parse.fastpaths(input, options);
- }
-
- if (!parsed.output) {
- parsed = parse(input, options);
- }
-
- return picomatch.compileRe(parsed, options, returnOutput, returnState);
-};
-
-/**
- * Create a regular expression from the given regex source string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.toRegex(source[, options]);
- *
- * const { output } = picomatch.parse('*.js');
- * console.log(picomatch.toRegex(output));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `source` Regular expression source string.
- * @param {Object} `options`
- * @return {RegExp}
- * @api public
- */
-
-picomatch.toRegex = (source, options) => {
- try {
- const opts = options || {};
- return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
- } catch (err) {
- if (options && options.debug === true) throw err;
- return /$^/;
- }
-};
-
-/**
- * Picomatch constants.
- * @return {Object}
- */
-
-picomatch.constants = constants;
-
-/**
- * Expose "picomatch"
- */
-
-module.exports = picomatch;
diff --git a/backend/dev-console/node_modules/picomatch/lib/scan.js b/backend/dev-console/node_modules/picomatch/lib/scan.js
deleted file mode 100644
index e59cd7a..0000000
--- a/backend/dev-console/node_modules/picomatch/lib/scan.js
+++ /dev/null
@@ -1,391 +0,0 @@
-'use strict';
-
-const utils = require('./utils');
-const {
- CHAR_ASTERISK, /* * */
- CHAR_AT, /* @ */
- CHAR_BACKWARD_SLASH, /* \ */
- CHAR_COMMA, /* , */
- CHAR_DOT, /* . */
- CHAR_EXCLAMATION_MARK, /* ! */
- CHAR_FORWARD_SLASH, /* / */
- CHAR_LEFT_CURLY_BRACE, /* { */
- CHAR_LEFT_PARENTHESES, /* ( */
- CHAR_LEFT_SQUARE_BRACKET, /* [ */
- CHAR_PLUS, /* + */
- CHAR_QUESTION_MARK, /* ? */
- CHAR_RIGHT_CURLY_BRACE, /* } */
- CHAR_RIGHT_PARENTHESES, /* ) */
- CHAR_RIGHT_SQUARE_BRACKET /* ] */
-} = require('./constants');
-
-const isPathSeparator = code => {
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
-};
-
-const depth = token => {
- if (token.isPrefix !== true) {
- token.depth = token.isGlobstar ? Infinity : 1;
- }
-};
-
-/**
- * Quickly scans a glob pattern and returns an object with a handful of
- * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
- * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
- * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
- *
- * ```js
- * const pm = require('picomatch');
- * console.log(pm.scan('foo/bar/*.js'));
- * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {Object} Returns an object with tokens and regex source string.
- * @api public
- */
-
-const scan = (input, options) => {
- const opts = options || {};
-
- const length = input.length - 1;
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
- const slashes = [];
- const tokens = [];
- const parts = [];
-
- let str = input;
- let index = -1;
- let start = 0;
- let lastIndex = 0;
- let isBrace = false;
- let isBracket = false;
- let isGlob = false;
- let isExtglob = false;
- let isGlobstar = false;
- let braceEscaped = false;
- let backslashes = false;
- let negated = false;
- let negatedExtglob = false;
- let finished = false;
- let braces = 0;
- let prev;
- let code;
- let token = { value: '', depth: 0, isGlob: false };
-
- const eos = () => index >= length;
- const peek = () => str.charCodeAt(index + 1);
- const advance = () => {
- prev = code;
- return str.charCodeAt(++index);
- };
-
- while (index < length) {
- code = advance();
- let next;
-
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
-
- if (code === CHAR_LEFT_CURLY_BRACE) {
- braceEscaped = true;
- }
- continue;
- }
-
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
- braces++;
-
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
-
- if (code === CHAR_LEFT_CURLY_BRACE) {
- braces++;
- continue;
- }
-
- if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (braceEscaped !== true && code === CHAR_COMMA) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (code === CHAR_RIGHT_CURLY_BRACE) {
- braces--;
-
- if (braces === 0) {
- braceEscaped = false;
- isBrace = token.isBrace = true;
- finished = true;
- break;
- }
- }
- }
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (code === CHAR_FORWARD_SLASH) {
- slashes.push(index);
- tokens.push(token);
- token = { value: '', depth: 0, isGlob: false };
-
- if (finished === true) continue;
- if (prev === CHAR_DOT && index === (start + 1)) {
- start += 2;
- continue;
- }
-
- lastIndex = index + 1;
- continue;
- }
-
- if (opts.noext !== true) {
- const isExtglobChar = code === CHAR_PLUS
- || code === CHAR_AT
- || code === CHAR_ASTERISK
- || code === CHAR_QUESTION_MARK
- || code === CHAR_EXCLAMATION_MARK;
-
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
- isGlob = token.isGlob = true;
- isExtglob = token.isExtglob = true;
- finished = true;
- if (code === CHAR_EXCLAMATION_MARK && index === start) {
- negatedExtglob = true;
- }
-
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
-
- if (code === CHAR_RIGHT_PARENTHESES) {
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
- }
-
- if (code === CHAR_ASTERISK) {
- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
-
- if (code === CHAR_QUESTION_MARK) {
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
-
- if (code === CHAR_LEFT_SQUARE_BRACKET) {
- while (eos() !== true && (next = advance())) {
- if (next === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
-
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- isBracket = token.isBracket = true;
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
- negated = token.negated = true;
- start++;
- continue;
- }
-
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
- isGlob = token.isGlob = true;
-
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_LEFT_PARENTHESES) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
-
- if (code === CHAR_RIGHT_PARENTHESES) {
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
-
- if (isGlob === true) {
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
- }
-
- if (opts.noext === true) {
- isExtglob = false;
- isGlob = false;
- }
-
- let base = str;
- let prefix = '';
- let glob = '';
-
- if (start > 0) {
- prefix = str.slice(0, start);
- str = str.slice(start);
- lastIndex -= start;
- }
-
- if (base && isGlob === true && lastIndex > 0) {
- base = str.slice(0, lastIndex);
- glob = str.slice(lastIndex);
- } else if (isGlob === true) {
- base = '';
- glob = str;
- } else {
- base = str;
- }
-
- if (base && base !== '' && base !== '/' && base !== str) {
- if (isPathSeparator(base.charCodeAt(base.length - 1))) {
- base = base.slice(0, -1);
- }
- }
-
- if (opts.unescape === true) {
- if (glob) glob = utils.removeBackslashes(glob);
-
- if (base && backslashes === true) {
- base = utils.removeBackslashes(base);
- }
- }
-
- const state = {
- prefix,
- input,
- start,
- base,
- glob,
- isBrace,
- isBracket,
- isGlob,
- isExtglob,
- isGlobstar,
- negated,
- negatedExtglob
- };
-
- if (opts.tokens === true) {
- state.maxDepth = 0;
- if (!isPathSeparator(code)) {
- tokens.push(token);
- }
- state.tokens = tokens;
- }
-
- if (opts.parts === true || opts.tokens === true) {
- let prevIndex;
-
- for (let idx = 0; idx < slashes.length; idx++) {
- const n = prevIndex ? prevIndex + 1 : start;
- const i = slashes[idx];
- const value = input.slice(n, i);
- if (opts.tokens) {
- if (idx === 0 && start !== 0) {
- tokens[idx].isPrefix = true;
- tokens[idx].value = prefix;
- } else {
- tokens[idx].value = value;
- }
- depth(tokens[idx]);
- state.maxDepth += tokens[idx].depth;
- }
- if (idx !== 0 || value !== '') {
- parts.push(value);
- }
- prevIndex = i;
- }
-
- if (prevIndex && prevIndex + 1 < input.length) {
- const value = input.slice(prevIndex + 1);
- parts.push(value);
-
- if (opts.tokens) {
- tokens[tokens.length - 1].value = value;
- depth(tokens[tokens.length - 1]);
- state.maxDepth += tokens[tokens.length - 1].depth;
- }
- }
-
- state.slashes = slashes;
- state.parts = parts;
- }
-
- return state;
-};
-
-module.exports = scan;
diff --git a/backend/dev-console/node_modules/picomatch/lib/utils.js b/backend/dev-console/node_modules/picomatch/lib/utils.js
deleted file mode 100644
index 9c97cae..0000000
--- a/backend/dev-console/node_modules/picomatch/lib/utils.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/*global navigator*/
-'use strict';
-
-const {
- REGEX_BACKSLASH,
- REGEX_REMOVE_BACKSLASH,
- REGEX_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_GLOBAL
-} = require('./constants');
-
-exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
-exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
-exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
-exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
-exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
-
-exports.isWindows = () => {
- if (typeof navigator !== 'undefined' && navigator.platform) {
- const platform = navigator.platform.toLowerCase();
- return platform === 'win32' || platform === 'windows';
- }
-
- if (typeof process !== 'undefined' && process.platform) {
- return process.platform === 'win32';
- }
-
- return false;
-};
-
-exports.removeBackslashes = str => {
- return str.replace(REGEX_REMOVE_BACKSLASH, match => {
- return match === '\\' ? '' : match;
- });
-};
-
-exports.escapeLast = (input, char, lastIdx) => {
- const idx = input.lastIndexOf(char, lastIdx);
- if (idx === -1) return input;
- if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
- return `${input.slice(0, idx)}\\${input.slice(idx)}`;
-};
-
-exports.removePrefix = (input, state = {}) => {
- let output = input;
- if (output.startsWith('./')) {
- output = output.slice(2);
- state.prefix = './';
- }
- return output;
-};
-
-exports.wrapOutput = (input, state = {}, options = {}) => {
- const prepend = options.contains ? '' : '^';
- const append = options.contains ? '' : '$';
-
- let output = `${prepend}(?:${input})${append}`;
- if (state.negated === true) {
- output = `(?:^(?!${output}).*$)`;
- }
- return output;
-};
-
-exports.basename = (path, { windows } = {}) => {
- const segs = path.split(windows ? /[\\/]/ : '/');
- const last = segs[segs.length - 1];
-
- if (last === '') {
- return segs[segs.length - 2];
- }
-
- return last;
-};
diff --git a/backend/dev-console/node_modules/picomatch/package.json b/backend/dev-console/node_modules/picomatch/package.json
deleted file mode 100644
index 9151f1d..0000000
--- a/backend/dev-console/node_modules/picomatch/package.json
+++ /dev/null
@@ -1,82 +0,0 @@
-{
- "name": "picomatch",
- "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.",
- "version": "4.0.4",
- "homepage": "https://github.com/micromatch/picomatch",
- "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
- "funding": "https://github.com/sponsors/jonschlinkert",
- "repository": "micromatch/picomatch",
- "bugs": {
- "url": "https://github.com/micromatch/picomatch/issues"
- },
- "license": "MIT",
- "files": [
- "index.js",
- "posix.js",
- "lib"
- ],
- "sideEffects": false,
- "main": "index.js",
- "engines": {
- "node": ">=12"
- },
- "scripts": {
- "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .",
- "mocha": "mocha --reporter dot",
- "test": "npm run lint && npm run mocha",
- "test:ci": "npm run test:cover",
- "test:cover": "nyc npm run mocha"
- },
- "devDependencies": {
- "eslint": "^8.57.0",
- "fill-range": "^7.0.1",
- "gulp-format-md": "^2.0.0",
- "mocha": "^10.4.0",
- "nyc": "^15.1.0"
- },
- "keywords": [
- "glob",
- "match",
- "picomatch"
- ],
- "nyc": {
- "reporter": [
- "html",
- "lcov",
- "text-summary"
- ]
- },
- "verb": {
- "toc": {
- "render": true,
- "method": "preWrite",
- "maxdepth": 3
- },
- "layout": "empty",
- "tasks": [
- "readme"
- ],
- "plugins": [
- "gulp-format-md"
- ],
- "lint": {
- "reflinks": true
- },
- "related": {
- "list": [
- "braces",
- "micromatch"
- ]
- },
- "reflinks": [
- "braces",
- "expand-brackets",
- "extglob",
- "fill-range",
- "micromatch",
- "minimatch",
- "nanomatch",
- "picomatch"
- ]
- }
-}
diff --git a/backend/dev-console/node_modules/picomatch/posix.js b/backend/dev-console/node_modules/picomatch/posix.js
deleted file mode 100644
index d2f2bc5..0000000
--- a/backend/dev-console/node_modules/picomatch/posix.js
+++ /dev/null
@@ -1,3 +0,0 @@
-'use strict';
-
-module.exports = require('./lib/picomatch');
diff --git a/backend/dev-console/node_modules/postcss/LICENSE b/backend/dev-console/node_modules/postcss/LICENSE
deleted file mode 100644
index c2314d5..0000000
--- a/backend/dev-console/node_modules/postcss/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright 2013 Andrey Sitnik
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/backend/dev-console/node_modules/postcss/README.md b/backend/dev-console/node_modules/postcss/README.md
deleted file mode 100644
index 2df9301..0000000
--- a/backend/dev-console/node_modules/postcss/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# PostCSS
-
-
-
-PostCSS is a tool for transforming styles with JS plugins.
-These plugins can lint your CSS, support variables and mixins,
-transpile future CSS syntax, inline images, and more.
-
-PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
-and JetBrains. The [Autoprefixer] and [Stylelint] PostCSS plugins are some of the most popular CSS tools.
-
----
-
- Built by
-Evil Martians , go-to agency for developer tools .
-
----
-
-[Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
-[Evil Martians]: https://evilmartians.com/?utm_source=postcss
-[Autoprefixer]: https://github.com/postcss/autoprefixer
-[Stylelint]: https://stylelint.io/
-[plugins]: https://github.com/postcss/postcss#plugins
diff --git a/backend/dev-console/node_modules/postcss/lib/at-rule.d.ts b/backend/dev-console/node_modules/postcss/lib/at-rule.d.ts
deleted file mode 100644
index 703e399..0000000
--- a/backend/dev-console/node_modules/postcss/lib/at-rule.d.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import Container, {
- ContainerProps,
- ContainerWithChildren
-} from './container.js'
-
-declare namespace AtRule {
- export interface AtRuleRaws extends Record {
- /**
- * The space symbols after the last child of the node to the end of the node.
- */
- after?: string
-
- /**
- * The space between the at-rule name and its parameters.
- */
- afterName?: string
-
- /**
- * The space symbols before the node. It also stores `*`
- * and `_` symbols before the declaration (IE hack).
- */
- before?: string
-
- /**
- * The symbols between the last parameter and `{` for rules.
- */
- between?: string
-
- /**
- * The rule’s selector with comments.
- */
- params?: {
- raw: string
- value: string
- }
-
- /**
- * Contains `true` if the last child has an (optional) semicolon.
- */
- semicolon?: boolean
- }
-
- export interface AtRuleProps extends ContainerProps {
- /** Name of the at-rule. */
- name: string
- /** Parameters following the name of the at-rule. */
- params?: number | string
- /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
- raws?: AtRuleRaws
- }
-
- export { AtRule_ as default }
-}
-
-/**
- * Represents an at-rule.
- *
- * ```js
- * Once (root, { AtRule }) {
- * let media = new AtRule({ name: 'media', params: 'print' })
- * media.append(…)
- * root.append(media)
- * }
- * ```
- *
- * If it’s followed in the CSS by a `{}` block, this node will have
- * a nodes property representing its children.
- *
- * ```js
- * const root = postcss.parse('@charset "UTF-8"; @media print {}')
- *
- * const charset = root.first
- * charset.type //=> 'atrule'
- * charset.nodes //=> undefined
- *
- * const media = root.last
- * media.nodes //=> []
- * ```
- */
-declare class AtRule_ extends Container {
- /**
- * An array containing the layer’s children.
- *
- * ```js
- * const root = postcss.parse('@layer example { a { color: black } }')
- * const layer = root.first
- * layer.nodes.length //=> 1
- * layer.nodes[0].selector //=> 'a'
- * ```
- *
- * Can be `undefinded` if the at-rule has no body.
- *
- * ```js
- * const root = postcss.parse('@layer a, b, c;')
- * const layer = root.first
- * layer.nodes //=> undefined
- * ```
- */
- nodes: Container['nodes'] | undefined
- parent: ContainerWithChildren | undefined
-
- raws: AtRule.AtRuleRaws
- type: 'atrule'
- /**
- * The at-rule’s name immediately follows the `@`.
- *
- * ```js
- * const root = postcss.parse('@media print {}')
- * const media = root.first
- * media.name //=> 'media'
- * ```
- */
- get name(): string
- set name(value: string)
-
- /**
- * The at-rule’s parameters, the values that follow the at-rule’s name
- * but precede any `{}` block.
- *
- * ```js
- * const root = postcss.parse('@media print, screen {}')
- * const media = root.first
- * media.params //=> 'print, screen'
- * ```
- */
- get params(): string
-
- set params(value: string)
-
- constructor(defaults?: AtRule.AtRuleProps)
- assign(overrides: AtRule.AtRuleProps | object): this
- clone(overrides?: Partial): this
- cloneAfter(overrides?: Partial): this
- cloneBefore(overrides?: Partial): this
-}
-
-declare class AtRule extends AtRule_ {}
-
-export = AtRule
diff --git a/backend/dev-console/node_modules/postcss/lib/at-rule.js b/backend/dev-console/node_modules/postcss/lib/at-rule.js
deleted file mode 100644
index 9486447..0000000
--- a/backend/dev-console/node_modules/postcss/lib/at-rule.js
+++ /dev/null
@@ -1,25 +0,0 @@
-'use strict'
-
-let Container = require('./container')
-
-class AtRule extends Container {
- constructor(defaults) {
- super(defaults)
- this.type = 'atrule'
- }
-
- append(...children) {
- if (!this.proxyOf.nodes) this.nodes = []
- return super.append(...children)
- }
-
- prepend(...children) {
- if (!this.proxyOf.nodes) this.nodes = []
- return super.prepend(...children)
- }
-}
-
-module.exports = AtRule
-AtRule.default = AtRule
-
-Container.registerAtRule(AtRule)
diff --git a/backend/dev-console/node_modules/postcss/lib/comment.d.ts b/backend/dev-console/node_modules/postcss/lib/comment.d.ts
deleted file mode 100644
index f764109..0000000
--- a/backend/dev-console/node_modules/postcss/lib/comment.d.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import Container from './container.js'
-import Node, { NodeProps } from './node.js'
-
-declare namespace Comment {
- export interface CommentRaws extends Record {
- /**
- * The space symbols before the node.
- */
- before?: string
-
- /**
- * The space symbols between `/*` and the comment’s text.
- */
- left?: string
-
- /**
- * The space symbols between the comment’s text.
- */
- right?: string
- }
-
- export interface CommentProps extends NodeProps {
- /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
- raws?: CommentRaws
- /** Content of the comment. */
- text: string
- }
-
- export { Comment_ as default }
-}
-
-/**
- * It represents a class that handles
- * [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
- *
- * ```js
- * Once (root, { Comment }) {
- * const note = new Comment({ text: 'Note: …' })
- * root.append(note)
- * }
- * ```
- *
- * Remember that CSS comments inside selectors, at-rule parameters,
- * or declaration values will be stored in the `raws` properties
- * explained above.
- */
-declare class Comment_ extends Node {
- parent: Container | undefined
- raws: Comment.CommentRaws
- type: 'comment'
- /**
- * The comment's text.
- */
- get text(): string
-
- set text(value: string)
-
- constructor(defaults?: Comment.CommentProps)
- assign(overrides: Comment.CommentProps | object): this
- clone(overrides?: Partial): this
- cloneAfter(overrides?: Partial): this
- cloneBefore(overrides?: Partial): this
-}
-
-declare class Comment extends Comment_ {}
-
-export = Comment
diff --git a/backend/dev-console/node_modules/postcss/lib/comment.js b/backend/dev-console/node_modules/postcss/lib/comment.js
deleted file mode 100644
index c566506..0000000
--- a/backend/dev-console/node_modules/postcss/lib/comment.js
+++ /dev/null
@@ -1,13 +0,0 @@
-'use strict'
-
-let Node = require('./node')
-
-class Comment extends Node {
- constructor(defaults) {
- super(defaults)
- this.type = 'comment'
- }
-}
-
-module.exports = Comment
-Comment.default = Comment
diff --git a/backend/dev-console/node_modules/postcss/lib/container.d.ts b/backend/dev-console/node_modules/postcss/lib/container.d.ts
deleted file mode 100644
index 82b24d0..0000000
--- a/backend/dev-console/node_modules/postcss/lib/container.d.ts
+++ /dev/null
@@ -1,478 +0,0 @@
-import AtRule from './at-rule.js'
-import Comment from './comment.js'
-import Declaration from './declaration.js'
-import Node, { ChildNode, ChildProps, NodeProps } from './node.js'
-import { Root } from './postcss.js'
-import Rule from './rule.js'
-
-declare namespace Container {
- export type ContainerWithChildren = {
- nodes: Child[]
- } & (AtRule | Root | Rule)
-
- export interface ValueOptions {
- /**
- * String that’s used to narrow down values and speed up the regexp search.
- */
- fast?: string
-
- /**
- * An array of property names.
- */
- props?: readonly string[]
- }
-
- export interface ContainerProps extends NodeProps {
- nodes?: readonly (ChildProps | Node)[]
- }
-
- /**
- * All types that can be passed into container methods to create or add a new
- * child node.
- */
- export type NewChild =
- | ChildProps
- | Node
- | readonly ChildProps[]
- | readonly Node[]
- | readonly string[]
- | string
- | undefined
-
- export { Container_ as default }
-}
-
-/**
- * The `Root`, `AtRule`, and `Rule` container nodes
- * inherit some common methods to help work with their children.
- *
- * Note that all containers can store any content. If you write a rule inside
- * a rule, PostCSS will parse it.
- */
-declare abstract class Container_ extends Node {
- /**
- * An array containing the container’s children.
- *
- * ```js
- * const root = postcss.parse('a { color: black }')
- * root.nodes.length //=> 1
- * root.nodes[0].selector //=> 'a'
- * root.nodes[0].nodes[0].prop //=> 'color'
- * ```
- */
- nodes: Child[] | undefined
-
- /**
- * The container’s first child.
- *
- * ```js
- * rule.first === rules.nodes[0]
- * ```
- */
- get first(): Child | undefined
-
- /**
- * The container’s last child.
- *
- * ```js
- * rule.last === rule.nodes[rule.nodes.length - 1]
- * ```
- */
- get last(): Child | undefined
- /**
- * Inserts new nodes to the end of the container.
- *
- * ```js
- * const decl1 = new Declaration({ prop: 'color', value: 'black' })
- * const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
- * rule.append(decl1, decl2)
- *
- * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
- * root.append({ selector: 'a' }) // rule
- * rule.append({ prop: 'color', value: 'black' }) // declaration
- * rule.append({ text: 'Comment' }) // comment
- *
- * root.append('a {}')
- * root.first.append('color: black; z-index: 1')
- * ```
- *
- * @param nodes New nodes.
- * @return This node for methods chain.
- */
- append(...nodes: Container.NewChild[]): this
- assign(overrides: Container.ContainerProps | object): this
- clone(overrides?: Partial): this
-
- cloneAfter(overrides?: Partial): this
-
- cloneBefore(overrides?: Partial): this
- /**
- * Iterates through the container’s immediate children,
- * calling `callback` for each child.
- *
- * Returning `false` in the callback will break iteration.
- *
- * This method only iterates through the container’s immediate children.
- * If you need to recursively iterate through all the container’s descendant
- * nodes, use `Container#walk`.
- *
- * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
- * if you are mutating the array of child nodes during iteration.
- * PostCSS will adjust the current index to match the mutations.
- *
- * ```js
- * const root = postcss.parse('a { color: black; z-index: 1 }')
- * const rule = root.first
- *
- * for (const decl of rule.nodes) {
- * decl.cloneBefore({ prop: '-webkit-' + decl.prop })
- * // Cycle will be infinite, because cloneBefore moves the current node
- * // to the next index
- * }
- *
- * rule.each(decl => {
- * decl.cloneBefore({ prop: '-webkit-' + decl.prop })
- * // Will be executed only for color and z-index
- * })
- * ```
- *
- * @param callback Iterator receives each node and index.
- * @return Returns `false` if iteration was broke.
- */
- each(
- callback: (node: Child, index: number) => false | void
- ): false | undefined
-
- /**
- * Returns `true` if callback returns `true`
- * for all of the container’s children.
- *
- * ```js
- * const noPrefixes = rule.every(i => i.prop[0] !== '-')
- * ```
- *
- * @param condition Iterator returns true or false.
- * @return Is every child pass condition.
- */
- every(
- condition: (node: Child, index: number, nodes: Child[]) => boolean
- ): boolean
- /**
- * Returns a `child`’s index within the `Container#nodes` array.
- *
- * ```js
- * rule.index( rule.nodes[2] ) //=> 2
- * ```
- *
- * @param child Child of the current container.
- * @return Child index.
- */
- index(child: Child | number): number
-
- /**
- * Insert new node after old node within the container.
- *
- * @param oldNode Child or child’s index.
- * @param newNode New node.
- * @return This node for methods chain.
- */
- insertAfter(oldNode: Child | number, newNode: Container.NewChild): this
-
- /**
- * Traverses the container’s descendant nodes, calling callback
- * for each comment node.
- *
- * Like `Container#each`, this method is safe
- * to use if you are mutating arrays during iteration.
- *
- * ```js
- * root.walkComments(comment => {
- * comment.remove()
- * })
- * ```
- *
- * @param callback Iterator receives each node and index.
- * @return Returns `false` if iteration was broke.
- */
-
- /**
- * Insert new node before old node within the container.
- *
- * ```js
- * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
- * ```
- *
- * @param oldNode Child or child’s index.
- * @param newNode New node.
- * @return This node for methods chain.
- */
- insertBefore(oldNode: Child | number, newNode: Container.NewChild): this
- /**
- * Inserts new nodes to the start of the container.
- *
- * ```js
- * const decl1 = new Declaration({ prop: 'color', value: 'black' })
- * const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
- * rule.prepend(decl1, decl2)
- *
- * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
- * root.append({ selector: 'a' }) // rule
- * rule.append({ prop: 'color', value: 'black' }) // declaration
- * rule.append({ text: 'Comment' }) // comment
- *
- * root.append('a {}')
- * root.first.append('color: black; z-index: 1')
- * ```
- *
- * @param nodes New nodes.
- * @return This node for methods chain.
- */
- prepend(...nodes: Container.NewChild[]): this
-
- /**
- * Add child to the end of the node.
- *
- * ```js
- * rule.push(new Declaration({ prop: 'color', value: 'black' }))
- * ```
- *
- * @param child New node.
- * @return This node for methods chain.
- */
- push(child: Child): this
-
- /**
- * Removes all children from the container
- * and cleans their parent properties.
- *
- * ```js
- * rule.removeAll()
- * rule.nodes.length //=> 0
- * ```
- *
- * @return This node for methods chain.
- */
- removeAll(): this
-
- /**
- * Removes node from the container and cleans the parent properties
- * from the node and its children.
- *
- * ```js
- * rule.nodes.length //=> 5
- * rule.removeChild(decl)
- * rule.nodes.length //=> 4
- * decl.parent //=> undefined
- * ```
- *
- * @param child Child or child’s index.
- * @return This node for methods chain.
- */
- removeChild(child: Child | number): this
-
- replaceValues(
- pattern: RegExp | string,
- replaced: { (substring: string, ...args: any[]): string } | string
- ): this
- /**
- * Passes all declaration values within the container that match pattern
- * through callback, replacing those values with the returned result
- * of callback.
- *
- * This method is useful if you are using a custom unit or function
- * and need to iterate through all values.
- *
- * ```js
- * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
- * return 15 * parseInt(string) + 'px'
- * })
- * ```
- *
- * @param pattern Replace pattern.
- * @param {object} options Options to speed up the search.
- * @param replaced String to replace pattern or callback
- * that returns a new value. The callback
- * will receive the same arguments
- * as those passed to a function parameter
- * of `String#replace`.
- * @return This node for methods chain.
- */
- replaceValues(
- pattern: RegExp | string,
- options: Container.ValueOptions,
- replaced: { (substring: string, ...args: any[]): string } | string
- ): this
-
- /**
- * Returns `true` if callback returns `true` for (at least) one
- * of the container’s children.
- *
- * ```js
- * const hasPrefix = rule.some(i => i.prop[0] === '-')
- * ```
- *
- * @param condition Iterator returns true or false.
- * @return Is some child pass condition.
- */
- some(
- condition: (node: Child, index: number, nodes: Child[]) => boolean
- ): boolean
-
- /**
- * Traverses the container’s descendant nodes, calling callback
- * for each node.
- *
- * Like container.each(), this method is safe to use
- * if you are mutating arrays during iteration.
- *
- * If you only need to iterate through the container’s immediate children,
- * use `Container#each`.
- *
- * ```js
- * root.walk(node => {
- * // Traverses all descendant nodes.
- * })
- * ```
- *
- * @param callback Iterator receives each node and index.
- * @return Returns `false` if iteration was broke.
- */
- walk(
- callback: (node: ChildNode, index: number) => false | void
- ): false | undefined
-
- /**
- * Traverses the container’s descendant nodes, calling callback
- * for each at-rule node.
- *
- * If you pass a filter, iteration will only happen over at-rules
- * that have matching names.
- *
- * Like `Container#each`, this method is safe
- * to use if you are mutating arrays during iteration.
- *
- * ```js
- * root.walkAtRules(rule => {
- * if (isOld(rule.name)) rule.remove()
- * })
- *
- * let first = false
- * root.walkAtRules('charset', rule => {
- * if (!first) {
- * first = true
- * } else {
- * rule.remove()
- * }
- * })
- * ```
- *
- * @param name String or regular expression to filter at-rules by name.
- * @param callback Iterator receives each node and index.
- * @return Returns `false` if iteration was broke.
- */
- walkAtRules(
- nameFilter: RegExp | string,
- callback: (atRule: AtRule, index: number) => false | void
- ): false | undefined
- walkAtRules(
- callback: (atRule: AtRule, index: number) => false | void
- ): false | undefined
-
- walkComments(
- callback: (comment: Comment, indexed: number) => false | void
- ): false | undefined
- walkComments(
- callback: (comment: Comment, indexed: number) => false | void
- ): false | undefined
-
- /**
- * Traverses the container’s descendant nodes, calling callback
- * for each declaration node.
- *
- * If you pass a filter, iteration will only happen over declarations
- * with matching properties.
- *
- * ```js
- * root.walkDecls(decl => {
- * checkPropertySupport(decl.prop)
- * })
- *
- * root.walkDecls('border-radius', decl => {
- * decl.remove()
- * })
- *
- * root.walkDecls(/^background/, decl => {
- * decl.value = takeFirstColorFromGradient(decl.value)
- * })
- * ```
- *
- * Like `Container#each`, this method is safe
- * to use if you are mutating arrays during iteration.
- *
- * @param prop String or regular expression to filter declarations
- * by property name.
- * @param callback Iterator receives each node and index.
- * @return Returns `false` if iteration was broke.
- */
- walkDecls(
- propFilter: RegExp | string,
- callback: (decl: Declaration, index: number) => false | void
- ): false | undefined
- walkDecls(
- callback: (decl: Declaration, index: number) => false | void
- ): false | undefined
- /**
- * Traverses the container’s descendant nodes, calling callback
- * for each rule node.
- *
- * If you pass a filter, iteration will only happen over rules
- * with matching selectors.
- *
- * Like `Container#each`, this method is safe
- * to use if you are mutating arrays during iteration.
- *
- * ```js
- * const selectors = []
- * root.walkRules(rule => {
- * selectors.push(rule.selector)
- * })
- * console.log(`Your CSS uses ${ selectors.length } selectors`)
- * ```
- *
- * @param selector String or regular expression to filter rules by selector.
- * @param callback Iterator receives each node and index.
- * @return Returns `false` if iteration was broke.
- */
- walkRules(
- selectorFilter: RegExp | string,
- callback: (rule: Rule, index: number) => false | void
- ): false | undefined
- walkRules(
- callback: (rule: Rule, index: number) => false | void
- ): false | undefined
- /**
- * An internal method that converts a {@link NewChild} into a list of actual
- * child nodes that can then be added to this container.
- *
- * This ensures that the nodes' parent is set to this container, that they use
- * the correct prototype chain, and that they're marked as dirty.
- *
- * @param mnodes The new node or nodes to add.
- * @param sample A node from whose raws the new node's `before` raw should be
- * taken.
- * @param type This should be set to `'prepend'` if the new nodes will be
- * inserted at the beginning of the container.
- * @hidden
- */
- protected normalize(
- nodes: Container.NewChild,
- sample: Node | undefined,
- type?: 'prepend' | false
- ): Child[]
-}
-
-declare class Container<
- Child extends Node = ChildNode
-> extends Container_ {}
-
-export = Container
diff --git a/backend/dev-console/node_modules/postcss/lib/container.js b/backend/dev-console/node_modules/postcss/lib/container.js
deleted file mode 100644
index edb07cc..0000000
--- a/backend/dev-console/node_modules/postcss/lib/container.js
+++ /dev/null
@@ -1,447 +0,0 @@
-'use strict'
-
-let Comment = require('./comment')
-let Declaration = require('./declaration')
-let Node = require('./node')
-let { isClean, my } = require('./symbols')
-
-let AtRule, parse, Root, Rule
-
-function cleanSource(nodes) {
- return nodes.map(i => {
- if (i.nodes) i.nodes = cleanSource(i.nodes)
- delete i.source
- return i
- })
-}
-
-function markTreeDirty(node) {
- node[isClean] = false
- if (node.proxyOf.nodes) {
- for (let i of node.proxyOf.nodes) {
- markTreeDirty(i)
- }
- }
-}
-
-class Container extends Node {
- get first() {
- if (!this.proxyOf.nodes) return undefined
- return this.proxyOf.nodes[0]
- }
-
- get last() {
- if (!this.proxyOf.nodes) return undefined
- return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
- }
-
- append(...children) {
- for (let child of children) {
- let nodes = this.normalize(child, this.last)
- for (let node of nodes) this.proxyOf.nodes.push(node)
- }
-
- this.markDirty()
-
- return this
- }
-
- cleanRaws(keepBetween) {
- super.cleanRaws(keepBetween)
- if (this.nodes) {
- for (let node of this.nodes) node.cleanRaws(keepBetween)
- }
- }
-
- each(callback) {
- if (!this.proxyOf.nodes) return undefined
- let iterator = this.getIterator()
-
- let index, result
- while (this.indexes[iterator] < this.proxyOf.nodes.length) {
- index = this.indexes[iterator]
- result = callback(this.proxyOf.nodes[index], index)
- if (result === false) break
-
- this.indexes[iterator] += 1
- }
-
- delete this.indexes[iterator]
- return result
- }
-
- every(condition) {
- return this.nodes.every(condition)
- }
-
- getIterator() {
- if (!this.lastEach) this.lastEach = 0
- if (!this.indexes) this.indexes = {}
-
- this.lastEach += 1
- let iterator = this.lastEach
- this.indexes[iterator] = 0
-
- return iterator
- }
-
- getProxyProcessor() {
- return {
- get(node, prop) {
- if (prop === 'proxyOf') {
- return node
- } else if (!node[prop]) {
- return node[prop]
- } else if (
- prop === 'each' ||
- (typeof prop === 'string' && prop.startsWith('walk'))
- ) {
- return (...args) => {
- return node[prop](
- ...args.map(i => {
- if (typeof i === 'function') {
- return (child, index) => i(child.toProxy(), index)
- } else {
- return i
- }
- })
- )
- }
- } else if (prop === 'every' || prop === 'some') {
- return cb => {
- return node[prop]((child, ...other) =>
- cb(child.toProxy(), ...other)
- )
- }
- } else if (prop === 'root') {
- return () => node.root().toProxy()
- } else if (prop === 'nodes') {
- return node.nodes.map(i => i.toProxy())
- } else if (prop === 'first' || prop === 'last') {
- return node[prop].toProxy()
- } else {
- return node[prop]
- }
- },
-
- set(node, prop, value) {
- if (node[prop] === value) return true
- node[prop] = value
- if (prop === 'name' || prop === 'params' || prop === 'selector') {
- node.markDirty()
- }
- return true
- }
- }
- }
-
- index(child) {
- if (typeof child === 'number') return child
- if (child.proxyOf) child = child.proxyOf
- return this.proxyOf.nodes.indexOf(child)
- }
-
- insertAfter(exist, add) {
- let existIndex = this.index(exist)
- let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse()
- existIndex = this.index(exist)
- for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node)
-
- let index
- for (let id in this.indexes) {
- index = this.indexes[id]
- if (existIndex < index) {
- this.indexes[id] = index + nodes.length
- }
- }
-
- this.markDirty()
-
- return this
- }
-
- insertBefore(exist, add) {
- let existIndex = this.index(exist)
- let type = existIndex === 0 ? 'prepend' : false
- let nodes = this.normalize(
- add,
- this.proxyOf.nodes[existIndex],
- type
- ).reverse()
- existIndex = this.index(exist)
- for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node)
-
- let index
- for (let id in this.indexes) {
- index = this.indexes[id]
- if (existIndex <= index) {
- this.indexes[id] = index + nodes.length
- }
- }
-
- this.markDirty()
-
- return this
- }
-
- normalize(nodes, sample) {
- if (typeof nodes === 'string') {
- nodes = cleanSource(parse(nodes).nodes)
- } else if (typeof nodes === 'undefined') {
- nodes = []
- } else if (Array.isArray(nodes)) {
- nodes = nodes.slice(0)
- for (let i of nodes) {
- if (i.parent) i.parent.removeChild(i, 'ignore')
- }
- } else if (nodes.type === 'root' && this.type !== 'document') {
- nodes = nodes.nodes.slice(0)
- for (let i of nodes) {
- if (i.parent) i.parent.removeChild(i, 'ignore')
- }
- } else if (nodes.type) {
- nodes = [nodes]
- } else if (nodes.prop) {
- if (typeof nodes.value === 'undefined') {
- throw new Error('Value field is missed in node creation')
- } else if (typeof nodes.value !== 'string') {
- nodes.value = String(nodes.value)
- }
- nodes = [new Declaration(nodes)]
- } else if (nodes.selector || nodes.selectors) {
- nodes = [new Rule(nodes)]
- } else if (nodes.name) {
- nodes = [new AtRule(nodes)]
- } else if (nodes.text) {
- nodes = [new Comment(nodes)]
- } else {
- throw new Error('Unknown node type in node creation')
- }
-
- let processed = nodes.map(i => {
- /* c8 ignore next */
- if (!i[my]) Container.rebuild(i)
- i = i.proxyOf
- if (i.parent) i.parent.removeChild(i)
- if (i[isClean]) markTreeDirty(i)
-
- if (!i.raws) i.raws = {}
- if (typeof i.raws.before === 'undefined') {
- if (sample && typeof sample.raws.before !== 'undefined') {
- i.raws.before = sample.raws.before.replace(/\S/g, '')
- }
- }
- i.parent = this.proxyOf
- return i
- })
-
- return processed
- }
-
- prepend(...children) {
- children = children.reverse()
- for (let child of children) {
- let nodes = this.normalize(child, this.first, 'prepend').reverse()
- for (let node of nodes) this.proxyOf.nodes.unshift(node)
- for (let id in this.indexes) {
- this.indexes[id] = this.indexes[id] + nodes.length
- }
- }
-
- this.markDirty()
-
- return this
- }
-
- push(child) {
- child.parent = this
- this.proxyOf.nodes.push(child)
- return this
- }
-
- removeAll() {
- for (let node of this.proxyOf.nodes) node.parent = undefined
- this.proxyOf.nodes = []
-
- this.markDirty()
-
- return this
- }
-
- removeChild(child) {
- child = this.index(child)
- this.proxyOf.nodes[child].parent = undefined
- this.proxyOf.nodes.splice(child, 1)
-
- let index
- for (let id in this.indexes) {
- index = this.indexes[id]
- if (index >= child) {
- this.indexes[id] = index - 1
- }
- }
-
- this.markDirty()
-
- return this
- }
-
- replaceValues(pattern, opts, callback) {
- if (!callback) {
- callback = opts
- opts = {}
- }
-
- this.walkDecls(decl => {
- if (opts.props && !opts.props.includes(decl.prop)) return
- if (opts.fast && !decl.value.includes(opts.fast)) return
-
- decl.value = decl.value.replace(pattern, callback)
- })
-
- this.markDirty()
-
- return this
- }
-
- some(condition) {
- return this.nodes.some(condition)
- }
-
- walk(callback) {
- return this.each((child, i) => {
- let result
- try {
- result = callback(child, i)
- } catch (e) {
- throw child.addToError(e)
- }
- if (result !== false && child.walk) {
- result = child.walk(callback)
- }
-
- return result
- })
- }
-
- walkAtRules(name, callback) {
- if (!callback) {
- callback = name
- return this.walk((child, i) => {
- if (child.type === 'atrule') {
- return callback(child, i)
- }
- })
- }
- if (name instanceof RegExp) {
- return this.walk((child, i) => {
- if (child.type === 'atrule' && name.test(child.name)) {
- return callback(child, i)
- }
- })
- }
- return this.walk((child, i) => {
- if (child.type === 'atrule' && child.name === name) {
- return callback(child, i)
- }
- })
- }
-
- walkComments(callback) {
- return this.walk((child, i) => {
- if (child.type === 'comment') {
- return callback(child, i)
- }
- })
- }
-
- walkDecls(prop, callback) {
- if (!callback) {
- callback = prop
- return this.walk((child, i) => {
- if (child.type === 'decl') {
- return callback(child, i)
- }
- })
- }
- if (prop instanceof RegExp) {
- return this.walk((child, i) => {
- if (child.type === 'decl' && prop.test(child.prop)) {
- return callback(child, i)
- }
- })
- }
- return this.walk((child, i) => {
- if (child.type === 'decl' && child.prop === prop) {
- return callback(child, i)
- }
- })
- }
-
- walkRules(selector, callback) {
- if (!callback) {
- callback = selector
-
- return this.walk((child, i) => {
- if (child.type === 'rule') {
- return callback(child, i)
- }
- })
- }
- if (selector instanceof RegExp) {
- return this.walk((child, i) => {
- if (child.type === 'rule' && selector.test(child.selector)) {
- return callback(child, i)
- }
- })
- }
- return this.walk((child, i) => {
- if (child.type === 'rule' && child.selector === selector) {
- return callback(child, i)
- }
- })
- }
-}
-
-Container.registerParse = dependant => {
- parse = dependant
-}
-
-Container.registerRule = dependant => {
- Rule = dependant
-}
-
-Container.registerAtRule = dependant => {
- AtRule = dependant
-}
-
-Container.registerRoot = dependant => {
- Root = dependant
-}
-
-module.exports = Container
-Container.default = Container
-
-/* c8 ignore start */
-Container.rebuild = node => {
- if (node.type === 'atrule') {
- Object.setPrototypeOf(node, AtRule.prototype)
- } else if (node.type === 'rule') {
- Object.setPrototypeOf(node, Rule.prototype)
- } else if (node.type === 'decl') {
- Object.setPrototypeOf(node, Declaration.prototype)
- } else if (node.type === 'comment') {
- Object.setPrototypeOf(node, Comment.prototype)
- } else if (node.type === 'root') {
- Object.setPrototypeOf(node, Root.prototype)
- }
-
- node[my] = true
-
- if (node.nodes) {
- node.nodes.forEach(child => {
- Container.rebuild(child)
- })
- }
-}
-/* c8 ignore stop */
diff --git a/backend/dev-console/node_modules/postcss/lib/css-syntax-error.d.ts b/backend/dev-console/node_modules/postcss/lib/css-syntax-error.d.ts
deleted file mode 100644
index 03d9ed1..0000000
--- a/backend/dev-console/node_modules/postcss/lib/css-syntax-error.d.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-import { FilePosition } from './input.js'
-
-declare namespace CssSyntaxError {
- /**
- * A position that is part of a range.
- */
- export interface RangePosition {
- /**
- * The column number in the input.
- */
- column: number
-
- /**
- * The line number in the input.
- */
- line: number
- }
-
- export { CssSyntaxError_ as default }
-}
-
-/**
- * The CSS parser throws this error for broken CSS.
- *
- * Custom parsers can throw this error for broken custom syntax using
- * the `Node#error` method.
- *
- * PostCSS will use the input source map to detect the original error location.
- * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
- * PostCSS will show the original position in the Sass file.
- *
- * If you need the position in the PostCSS input
- * (e.g., to debug the previous compiler), use `error.input.file`.
- *
- * ```js
- * // Raising error from plugin
- * throw node.error('Unknown variable', { plugin: 'postcss-vars' })
- * ```
- *
- * ```js
- * // Catching and checking syntax error
- * try {
- * postcss.parse('a{')
- * } catch (error) {
- * if (error.name === 'CssSyntaxError') {
- * error //=> CssSyntaxError
- * }
- * }
- * ```
- */
-declare class CssSyntaxError_ extends Error {
- /**
- * Source column of the error.
- *
- * ```js
- * error.column //=> 1
- * error.input.column //=> 4
- * ```
- *
- * PostCSS will use the input source map to detect the original location.
- * If you need the position in the PostCSS input, use `error.input.column`.
- */
- column?: number
-
- /**
- * Source column of the error's end, exclusive. Provided if the error pertains
- * to a range.
- *
- * ```js
- * error.endColumn //=> 1
- * error.input.endColumn //=> 4
- * ```
- *
- * PostCSS will use the input source map to detect the original location.
- * If you need the position in the PostCSS input, use `error.input.endColumn`.
- */
- endColumn?: number
-
- /**
- * Source line of the error's end, exclusive. Provided if the error pertains
- * to a range.
- *
- * ```js
- * error.endLine //=> 3
- * error.input.endLine //=> 4
- * ```
- *
- * PostCSS will use the input source map to detect the original location.
- * If you need the position in the PostCSS input, use `error.input.endLine`.
- */
- endLine?: number
-
- /**
- * Absolute path to the broken file.
- *
- * ```js
- * error.file //=> 'a.sass'
- * error.input.file //=> 'a.css'
- * ```
- *
- * PostCSS will use the input source map to detect the original location.
- * If you need the position in the PostCSS input, use `error.input.file`.
- */
- file?: string
-
- /**
- * Input object with PostCSS internal information
- * about input file. If input has source map
- * from previous tool, PostCSS will use origin
- * (for example, Sass) source. You can use this
- * object to get PostCSS input source.
- *
- * ```js
- * error.input.file //=> 'a.css'
- * error.file //=> 'a.sass'
- * ```
- */
- input?: FilePosition
-
- /**
- * Source line of the error.
- *
- * ```js
- * error.line //=> 2
- * error.input.line //=> 4
- * ```
- *
- * PostCSS will use the input source map to detect the original location.
- * If you need the position in the PostCSS input, use `error.input.line`.
- */
- line?: number
-
- /**
- * Full error text in the GNU error format
- * with plugin, file, line and column.
- *
- * ```js
- * error.message //=> 'a.css:1:1: Unclosed block'
- * ```
- */
- message: string
-
- /**
- * Always equal to `'CssSyntaxError'`. You should always check error type
- * by `error.name === 'CssSyntaxError'`
- * instead of `error instanceof CssSyntaxError`,
- * because npm could have several PostCSS versions.
- *
- * ```js
- * if (error.name === 'CssSyntaxError') {
- * error //=> CssSyntaxError
- * }
- * ```
- */
- name: 'CssSyntaxError'
-
- /**
- * Plugin name, if error came from plugin.
- *
- * ```js
- * error.plugin //=> 'postcss-vars'
- * ```
- */
- plugin?: string
-
- /**
- * Error message.
- *
- * ```js
- * error.message //=> 'Unclosed block'
- * ```
- */
- reason: string
-
- /**
- * Source code of the broken file.
- *
- * ```js
- * error.source //=> 'a { b {} }'
- * error.input.source //=> 'a b { }'
- * ```
- */
- source?: string
-
- stack: string
-
- /**
- * Instantiates a CSS syntax error. Can be instantiated for a single position
- * or for a range.
- * @param message Error message.
- * @param lineOrStartPos If for a single position, the line number, or if for
- * a range, the inclusive start position of the error.
- * @param columnOrEndPos If for a single position, the column number, or if for
- * a range, the exclusive end position of the error.
- * @param source Source code of the broken file.
- * @param file Absolute path to the broken file.
- * @param plugin PostCSS plugin name, if error came from plugin.
- */
- constructor(
- message: string,
- lineOrStartPos?: CssSyntaxError.RangePosition | number,
- columnOrEndPos?: CssSyntaxError.RangePosition | number,
- source?: string,
- file?: string,
- plugin?: string
- )
-
- /**
- * Returns a few lines of CSS source that caused the error.
- *
- * If the CSS has an input source map without `sourceContent`,
- * this method will return an empty string.
- *
- * ```js
- * error.showSourceCode() //=> " 4 | }
- * // 5 | a {
- * // > 6 | bad
- * // | ^
- * // 7 | }
- * // 8 | b {"
- * ```
- *
- * @param color Whether arrow will be colored red by terminal
- * color codes. By default, PostCSS will detect
- * color support by `process.stdout.isTTY`
- * and `process.env.NODE_DISABLE_COLORS`.
- * @return Few lines of CSS source that caused the error.
- */
- showSourceCode(color?: boolean): string
-
- /**
- * Returns error position, message and source code of the broken part.
- *
- * ```js
- * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
- * // > 1 | a {
- * // | ^"
- * ```
- *
- * @return Error position, message and source code.
- */
- toString(): string
-}
-
-declare class CssSyntaxError extends CssSyntaxError_ {}
-
-export = CssSyntaxError
diff --git a/backend/dev-console/node_modules/postcss/lib/css-syntax-error.js b/backend/dev-console/node_modules/postcss/lib/css-syntax-error.js
deleted file mode 100644
index 275a4f6..0000000
--- a/backend/dev-console/node_modules/postcss/lib/css-syntax-error.js
+++ /dev/null
@@ -1,133 +0,0 @@
-'use strict'
-
-let pico = require('picocolors')
-
-let terminalHighlight = require('./terminal-highlight')
-
-class CssSyntaxError extends Error {
- constructor(message, line, column, source, file, plugin) {
- super(message)
- this.name = 'CssSyntaxError'
- this.reason = message
-
- if (file) {
- this.file = file
- }
- if (source) {
- this.source = source
- }
- if (plugin) {
- this.plugin = plugin
- }
- if (typeof line !== 'undefined' && typeof column !== 'undefined') {
- if (typeof line === 'number') {
- this.line = line
- this.column = column
- } else {
- this.line = line.line
- this.column = line.column
- this.endLine = column.line
- this.endColumn = column.column
- }
- }
-
- this.setMessage()
-
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, CssSyntaxError)
- }
- }
-
- setMessage() {
- this.message = this.plugin ? this.plugin + ': ' : ''
- this.message += this.file ? this.file : ''
- if (typeof this.line !== 'undefined') {
- this.message += ':' + this.line + ':' + this.column
- }
- this.message += ': ' + this.reason
- }
-
- showSourceCode(color) {
- if (!this.source) return ''
-
- let css = this.source
- if (color == null) color = pico.isColorSupported
-
- let aside = text => text
- let mark = text => text
- let highlight = text => text
- if (color) {
- let { bold, gray, red } = pico.createColors(true)
- mark = text => bold(red(text))
- aside = text => gray(text)
- if (terminalHighlight) {
- highlight = text => terminalHighlight(text)
- }
- }
-
- let lines = css.split(/\r?\n/)
- let start = Math.max(this.line - 3, 0)
- let end = Math.min(this.line + 2, lines.length)
- let maxWidth = String(end).length
-
- return lines
- .slice(start, end)
- .map((line, index) => {
- let number = start + 1 + index
- let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
- if (number === this.line) {
- if (line.length > 160) {
- let padding = 20
- let subLineStart = Math.max(0, this.column - padding)
- let subLineEnd = Math.max(
- this.column + padding,
- this.endColumn + padding
- )
- let subLine = line.slice(subLineStart, subLineEnd)
-
- let spacing =
- aside(gutter.replace(/\d/g, ' ')) +
- line
- .slice(0, Math.min(this.column - 1, padding - 1))
- .replace(/[^\t]/g, ' ')
-
- return (
- mark('>') +
- aside(gutter) +
- highlight(subLine) +
- '\n ' +
- spacing +
- mark('^')
- )
- }
-
- let spacing =
- aside(gutter.replace(/\d/g, ' ')) +
- line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
-
- return (
- mark('>') +
- aside(gutter) +
- highlight(line) +
- '\n ' +
- spacing +
- mark('^')
- )
- }
-
- return ' ' + aside(gutter) + highlight(line)
- })
- .join('\n')
- }
-
- toString() {
- let code = this.showSourceCode()
- if (code) {
- code = '\n\n' + code + '\n'
- }
- return this.name + ': ' + this.message + code
- }
-}
-
-module.exports = CssSyntaxError
-CssSyntaxError.default = CssSyntaxError
diff --git a/backend/dev-console/node_modules/postcss/lib/declaration.d.ts b/backend/dev-console/node_modules/postcss/lib/declaration.d.ts
deleted file mode 100644
index 55dec7f..0000000
--- a/backend/dev-console/node_modules/postcss/lib/declaration.d.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { ContainerWithChildren } from './container.js'
-import Node from './node.js'
-
-declare namespace Declaration {
- export interface DeclarationRaws extends Record {
- /**
- * The space symbols before the node. It also stores `*`
- * and `_` symbols before the declaration (IE hack).
- */
- before?: string
-
- /**
- * The symbols between the property and value for declarations.
- */
- between?: string
-
- /**
- * The content of the important statement, if it is not just `!important`.
- */
- important?: string
-
- /**
- * Declaration value with comments.
- */
- value?: {
- raw: string
- value: string
- }
- }
-
- export interface DeclarationProps {
- /** Whether the declaration has an `!important` annotation. */
- important?: boolean
- /** Name of the declaration. */
- prop: string
- /** Information used to generate byte-to-byte equal node string as it was in the origin input. */
- raws?: DeclarationRaws
- /** Value of the declaration. */
- value: string
- }
-
- export { Declaration_ as default }
-}
-
-/**
- * It represents a class that handles
- * [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
- *
- * ```js
- * Once (root, { Declaration }) {
- * const color = new Declaration({ prop: 'color', value: 'black' })
- * root.append(color)
- * }
- * ```
- *
- * ```js
- * const root = postcss.parse('a { color: black }')
- * const decl = root.first?.first
- *
- * decl.type //=> 'decl'
- * decl.toString() //=> ' color: black'
- * ```
- */
-declare class Declaration_ extends Node {
- parent: ContainerWithChildren | undefined
- raws: Declaration.DeclarationRaws
-
- type: 'decl'
-
- /**
- * It represents a specificity of the declaration.
- *
- * If true, the CSS declaration will have an
- * [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important)
- * specifier.
- *
- * ```js
- * const root = postcss.parse('a { color: black !important; color: red }')
- *
- * root.first.first.important //=> true
- * root.first.last.important //=> undefined
- * ```
- */
- get important(): boolean
- set important(value: boolean)
-
- /**
- * The property name for a CSS declaration.
- *
- * ```js
- * const root = postcss.parse('a { color: black }')
- * const decl = root.first.first
- *
- * decl.prop //=> 'color'
- * ```
- */
- get prop(): string
-
- set prop(value: string)
-
- /**
- * The property value for a CSS declaration.
- *
- * Any CSS comments inside the value string will be filtered out.
- * CSS comments present in the source value will be available in
- * the `raws` property.
- *
- * Assigning new `value` would ignore the comments in `raws`
- * property while compiling node to string.
- *
- * ```js
- * const root = postcss.parse('a { color: black }')
- * const decl = root.first.first
- *
- * decl.value //=> 'black'
- * ```
- */
- get value(): string
- set value(value: string)
-
- /**
- * It represents a getter that returns `true` if a declaration starts with
- * `--` or `$`, which are used to declare variables in CSS and SASS/SCSS.
- *
- * ```js
- * const root = postcss.parse(':root { --one: 1 }')
- * const one = root.first.first
- *
- * one.variable //=> true
- * ```
- *
- * ```js
- * const root = postcss.parse('$one: 1')
- * const one = root.first
- *
- * one.variable //=> true
- * ```
- */
- get variable(): boolean
- constructor(defaults?: Declaration.DeclarationProps)
-
- assign(overrides: Declaration.DeclarationProps | object): this
- clone(overrides?: Partial): this
- cloneAfter(overrides?: Partial): this
- cloneBefore(overrides?: Partial): this
-}
-
-declare class Declaration extends Declaration_ {}
-
-export = Declaration
diff --git a/backend/dev-console/node_modules/postcss/lib/declaration.js b/backend/dev-console/node_modules/postcss/lib/declaration.js
deleted file mode 100644
index 65a03aa..0000000
--- a/backend/dev-console/node_modules/postcss/lib/declaration.js
+++ /dev/null
@@ -1,24 +0,0 @@
-'use strict'
-
-let Node = require('./node')
-
-class Declaration extends Node {
- get variable() {
- return this.prop.startsWith('--') || this.prop[0] === '$'
- }
-
- constructor(defaults) {
- if (
- defaults &&
- typeof defaults.value !== 'undefined' &&
- typeof defaults.value !== 'string'
- ) {
- defaults = { ...defaults, value: String(defaults.value) }
- }
- super(defaults)
- this.type = 'decl'
- }
-}
-
-module.exports = Declaration
-Declaration.default = Declaration
diff --git a/backend/dev-console/node_modules/postcss/lib/document.d.ts b/backend/dev-console/node_modules/postcss/lib/document.d.ts
deleted file mode 100644
index 67194dd..0000000
--- a/backend/dev-console/node_modules/postcss/lib/document.d.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import Container, { ContainerProps } from './container.js'
-import { ProcessOptions } from './postcss.js'
-import Result from './result.js'
-import Root from './root.js'
-
-declare namespace Document {
- export interface DocumentProps extends ContainerProps {
- nodes?: readonly Root[]
-
- /**
- * Information to generate byte-to-byte equal node string as it was
- * in the origin input.
- *
- * Every parser saves its own properties.
- */
- raws?: Record
- }
-
- export { Document_ as default }
-}
-
-/**
- * Represents a file and contains all its parsed nodes.
- *
- * **Experimental:** some aspects of this node could change within minor
- * or patch version releases.
- *
- * ```js
- * const document = htmlParser(
- * ''
- * )
- * document.type //=> 'document'
- * document.nodes.length //=> 2
- * ```
- */
-declare class Document_ extends Container {
- nodes: Root[]
- parent: undefined
- type: 'document'
-
- constructor(defaults?: Document.DocumentProps)
-
- assign(overrides: Document.DocumentProps | object): this
- clone(overrides?: Partial): this
- cloneAfter(overrides?: Partial): this
- cloneBefore(overrides?: Partial): this
-
- /**
- * Returns a `Result` instance representing the document’s CSS roots.
- *
- * ```js
- * const root1 = postcss.parse(css1, { from: 'a.css' })
- * const root2 = postcss.parse(css2, { from: 'b.css' })
- * const document = postcss.document()
- * document.append(root1)
- * document.append(root2)
- * const result = document.toResult({ to: 'all.css', map: true })
- * ```
- *
- * @param opts Options.
- * @return Result with current document’s CSS.
- */
- toResult(options?: ProcessOptions): Result
-}
-
-declare class Document extends Document_ {}
-
-export = Document
diff --git a/backend/dev-console/node_modules/postcss/lib/document.js b/backend/dev-console/node_modules/postcss/lib/document.js
deleted file mode 100644
index 4468991..0000000
--- a/backend/dev-console/node_modules/postcss/lib/document.js
+++ /dev/null
@@ -1,33 +0,0 @@
-'use strict'
-
-let Container = require('./container')
-
-let LazyResult, Processor
-
-class Document extends Container {
- constructor(defaults) {
- // type needs to be passed to super, otherwise child roots won't be normalized correctly
- super({ type: 'document', ...defaults })
-
- if (!this.nodes) {
- this.nodes = []
- }
- }
-
- toResult(opts = {}) {
- let lazy = new LazyResult(new Processor(), this, opts)
-
- return lazy.stringify()
- }
-}
-
-Document.registerLazyResult = dependant => {
- LazyResult = dependant
-}
-
-Document.registerProcessor = dependant => {
- Processor = dependant
-}
-
-module.exports = Document
-Document.default = Document
diff --git a/backend/dev-console/node_modules/postcss/lib/fromJSON.d.ts b/backend/dev-console/node_modules/postcss/lib/fromJSON.d.ts
deleted file mode 100644
index 3a0c5b8..0000000
--- a/backend/dev-console/node_modules/postcss/lib/fromJSON.d.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { JSONHydrator } from './postcss.js'
-
-interface FromJSON extends JSONHydrator {
- default: FromJSON
-}
-
-declare let fromJSON: FromJSON
-
-export = fromJSON
diff --git a/backend/dev-console/node_modules/postcss/lib/fromJSON.js b/backend/dev-console/node_modules/postcss/lib/fromJSON.js
deleted file mode 100644
index a43686d..0000000
--- a/backend/dev-console/node_modules/postcss/lib/fromJSON.js
+++ /dev/null
@@ -1,68 +0,0 @@
-'use strict'
-
-let AtRule = require('./at-rule')
-let Comment = require('./comment')
-let Declaration = require('./declaration')
-let Input = require('./input')
-let PreviousMap = require('./previous-map')
-let Root = require('./root')
-let Rule = require('./rule')
-
-function fromJSON(json, inputs) {
- if (Array.isArray(json)) return json.map(n => fromJSON(n))
-
- let { inputs: ownInputs, ...defaults } = json
- if (ownInputs) {
- inputs = []
- for (let input of ownInputs) {
- let inputHydrated = { ...input, __proto__: Input.prototype }
- if (inputHydrated.map) {
- inputHydrated.map = {
- ...inputHydrated.map,
- __proto__: PreviousMap.prototype
- }
- }
- inputs.push(inputHydrated)
- }
- }
- // Rehydrate children separately and attach them after construction.
- // Passing them through the container constructor would re-run insertion
- // spacing normalization and overwrite each child's own `raws.before`.
- let nodes
- if (defaults.nodes) {
- nodes = json.nodes.map(n => fromJSON(n, inputs))
- delete defaults.nodes
- }
- if (defaults.source) {
- let { inputId, ...source } = defaults.source
- defaults.source = source
- if (inputId != null) {
- defaults.source.input = inputs[inputId]
- }
- }
-
- let node
- if (defaults.type === 'root') {
- node = new Root(defaults)
- } else if (defaults.type === 'decl') {
- node = new Declaration(defaults)
- } else if (defaults.type === 'rule') {
- node = new Rule(defaults)
- } else if (defaults.type === 'comment') {
- node = new Comment(defaults)
- } else if (defaults.type === 'atrule') {
- node = new AtRule(defaults)
- } else {
- throw new Error('Unknown node type: ' + json.type)
- }
-
- if (nodes) {
- node.nodes = nodes
- for (let child of nodes) child.parent = node
- }
-
- return node
-}
-
-module.exports = fromJSON
-fromJSON.default = fromJSON
diff --git a/backend/dev-console/node_modules/postcss/lib/input.d.ts b/backend/dev-console/node_modules/postcss/lib/input.d.ts
deleted file mode 100644
index ca2d26b..0000000
--- a/backend/dev-console/node_modules/postcss/lib/input.d.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-import { CssSyntaxError, ProcessOptions } from './postcss.js'
-import PreviousMap from './previous-map.js'
-
-declare namespace Input {
- export interface FilePosition {
- /**
- * Column of inclusive start position in source file.
- */
- column: number
-
- /**
- * Column of exclusive end position in source file.
- */
- endColumn?: number
-
- /**
- * Line of exclusive end position in source file.
- */
- endLine?: number
-
- /**
- * Offset of exclusive end position in source file.
- */
- endOffset?: number
-
- /**
- * Absolute path to the source file.
- */
- file?: string
-
- /**
- * Line of inclusive start position in source file.
- */
- line: number
-
- /**
- * Offset of inclusive start position in source file.
- */
- offset: number
-
- /**
- * Source code.
- */
- source?: string
-
- /**
- * URL for the source file.
- */
- url: string
- }
-
- export { Input_ as default }
-}
-
-/**
- * Represents the source CSS.
- *
- * ```js
- * const root = postcss.parse(css, { from: file })
- * const input = root.source.input
- * ```
- */
-declare class Input_ {
- /**
- * Input CSS source.
- *
- * ```js
- * const input = postcss.parse('a{}', { from: file }).input
- * input.css //=> "a{}"
- * ```
- */
- css: string
-
- /**
- * Input source with support for non-CSS documents.
- *
- * ```js
- * const input = postcss.parse('a{}', { from: file, document: '' }).input
- * input.document //=> ""
- * input.css //=> "a{}"
- * ```
- */
- document: string
-
- /**
- * The absolute path to the CSS source file defined
- * with the `from` option.
- *
- * ```js
- * const root = postcss.parse(css, { from: 'a.css' })
- * root.source.input.file //=> '/home/ai/a.css'
- * ```
- */
- file?: string
-
- /**
- * The flag to indicate whether or not the source code has Unicode BOM.
- */
- hasBOM: boolean
-
- /**
- * The unique ID of the CSS source. It will be created if `from` option
- * is not provided (because PostCSS does not know the file path).
- *
- * ```js
- * const root = postcss.parse(css)
- * root.source.input.file //=> undefined
- * root.source.input.id //=> " "
- * ```
- */
- id?: string
-
- /**
- * The input source map passed from a compilation step before PostCSS
- * (for example, from Sass compiler).
- *
- * ```js
- * root.source.input.map.consumer().sources //=> ['a.sass']
- * ```
- */
- map: PreviousMap
-
- /**
- * The CSS source identifier. Contains `Input#file` if the user
- * set the `from` option, or `Input#id` if they did not.
- *
- * ```js
- * const root = postcss.parse(css, { from: 'a.css' })
- * root.source.input.from //=> "/home/ai/a.css"
- *
- * const root = postcss.parse(css)
- * root.source.input.from //=> " "
- * ```
- */
- get from(): string
-
- /**
- * @param css Input CSS source.
- * @param opts Process options.
- */
- constructor(css: string, opts?: ProcessOptions)
-
- /**
- * Returns `CssSyntaxError` with information about the error and its position.
- */
- error(
- message: string,
- start:
- | {
- column: number
- line: number
- }
- | {
- offset: number
- },
- end:
- | {
- column: number
- line: number
- }
- | {
- offset: number
- },
- opts?: { plugin?: CssSyntaxError['plugin'] }
- ): CssSyntaxError
- error(
- message: string,
- line: number,
- column: number,
- opts?: { plugin?: CssSyntaxError['plugin'] }
- ): CssSyntaxError
- error(
- message: string,
- offset: number,
- opts?: { plugin?: CssSyntaxError['plugin'] }
- ): CssSyntaxError
-
- /**
- * Converts source line and column to offset.
- *
- * @param line Source line.
- * @param column Source column.
- * @return Source offset.
- */
- fromLineAndColumn(line: number, column: number): number
-
- /**
- * Converts source offset to line and column.
- *
- * @param offset Source offset.
- */
- fromOffset(offset: number): { col: number; line: number } | null
-
- /**
- * Reads the input source map and returns a symbol position
- * in the input source (e.g., in a Sass file that was compiled
- * to CSS before being passed to PostCSS). Optionally takes an
- * end position, exclusive.
- *
- * ```js
- * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
- * root.source.input.origin(1, 1, 1, 4)
- * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 }
- * ```
- *
- * @param line Line for inclusive start position in input CSS.
- * @param column Column for inclusive start position in input CSS.
- * @param endLine Line for exclusive end position in input CSS.
- * @param endColumn Column for exclusive end position in input CSS.
- *
- * @return Position in input source.
- */
- origin(
- line: number,
- column: number,
- endLine?: number,
- endColumn?: number
- ): false | Input.FilePosition
-
- /** Converts this to a JSON-friendly object representation. */
- toJSON(): object
-}
-
-declare class Input extends Input_ {}
-
-export = Input
diff --git a/backend/dev-console/node_modules/postcss/lib/input.js b/backend/dev-console/node_modules/postcss/lib/input.js
deleted file mode 100644
index 88a9c80..0000000
--- a/backend/dev-console/node_modules/postcss/lib/input.js
+++ /dev/null
@@ -1,276 +0,0 @@
-'use strict'
-
-let { nanoid } = require('nanoid/non-secure')
-let { isAbsolute, resolve } = require('path')
-let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
-let { fileURLToPath, pathToFileURL } = require('url')
-
-let CssSyntaxError = require('./css-syntax-error')
-let PreviousMap = require('./previous-map')
-let terminalHighlight = require('./terminal-highlight')
-
-let lineToIndexCache = Symbol('lineToIndexCache')
-
-let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
-let pathAvailable = Boolean(resolve && isAbsolute)
-
-function getLineToIndex(input) {
- if (input[lineToIndexCache]) return input[lineToIndexCache]
- let lines = input.css.split('\n')
- let lineToIndex = new Array(lines.length)
- let prevIndex = 0
-
- for (let i = 0, l = lines.length; i < l; i++) {
- lineToIndex[i] = prevIndex
- prevIndex += lines[i].length + 1
- }
-
- input[lineToIndexCache] = lineToIndex
- return lineToIndex
-}
-
-class Input {
- get from() {
- return this.file || this.id
- }
-
- constructor(css, opts = {}) {
- if (
- css === null ||
- typeof css === 'undefined' ||
- (typeof css === 'object' && !css.toString)
- ) {
- throw new Error(`PostCSS received ${css} instead of CSS string`)
- }
-
- this.css = css.toString()
-
- if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
- this.hasBOM = true
- this.css = this.css.slice(1)
- } else {
- this.hasBOM = false
- }
-
- this.document = this.css
- if (opts.document) this.document = opts.document.toString()
-
- if (opts.from) {
- if (
- !pathAvailable ||
- /^\w+:\/\//.test(opts.from) ||
- isAbsolute(opts.from)
- ) {
- this.file = opts.from
- } else {
- this.file = resolve(opts.from)
- }
- }
-
- if (pathAvailable && sourceMapAvailable) {
- let map = new PreviousMap(this.css, opts)
- if (map.text) {
- this.map = map
- let file = map.consumer().file
- if (!this.file && file) this.file = this.mapResolve(file)
- }
- }
-
- if (!this.file) {
- this.id = ' '
- }
- if (this.map) this.map.file = this.from
- }
-
- error(message, line, column, opts = {}) {
- let endColumn, endLine, endOffset, offset, result
-
- if (line && typeof line === 'object') {
- let start = line
- let end = column
- if (typeof start.offset === 'number') {
- offset = start.offset
- let pos = this.fromOffset(offset)
- line = pos.line
- column = pos.col
- } else {
- line = start.line
- column = start.column
- offset = this.fromLineAndColumn(line, column)
- }
- if (typeof end.offset === 'number') {
- endOffset = end.offset
- let pos = this.fromOffset(endOffset)
- endLine = pos.line
- endColumn = pos.col
- } else {
- endLine = end.line
- endColumn = end.column
- endOffset = this.fromLineAndColumn(end.line, end.column)
- }
- } else if (!column) {
- offset = line
- let pos = this.fromOffset(offset)
- line = pos.line
- column = pos.col
- } else {
- offset = this.fromLineAndColumn(line, column)
- }
-
- let origin = this.origin(line, column, endLine, endColumn)
- if (origin) {
- result = new CssSyntaxError(
- message,
- origin.endLine === undefined
- ? origin.line
- : { column: origin.column, line: origin.line },
- origin.endLine === undefined
- ? origin.column
- : { column: origin.endColumn, line: origin.endLine },
- origin.source,
- origin.file,
- opts.plugin
- )
- } else {
- result = new CssSyntaxError(
- message,
- endLine === undefined ? line : { column, line },
- endLine === undefined ? column : { column: endColumn, line: endLine },
- this.css,
- this.file,
- opts.plugin
- )
- }
-
- result.input = {
- column,
- endColumn,
- endLine,
- endOffset,
- line,
- offset,
- source: this.css
- }
- if (this.file) {
- if (pathToFileURL) {
- result.input.url = pathToFileURL(this.file).toString()
- }
- result.input.file = this.file
- }
-
- return result
- }
-
- fromLineAndColumn(line, column) {
- let lineToIndex = getLineToIndex(this)
- let index = lineToIndex[line - 1]
- return index + column - 1
- }
-
- fromOffset(offset) {
- let lineToIndex = getLineToIndex(this)
- let lastLine = lineToIndex[lineToIndex.length - 1]
-
- let min = 0
- if (offset >= lastLine) {
- min = lineToIndex.length - 1
- } else {
- let max = lineToIndex.length - 2
- let mid
- while (min < max) {
- mid = min + ((max - min) >> 1)
- if (offset < lineToIndex[mid]) {
- max = mid - 1
- } else if (offset >= lineToIndex[mid + 1]) {
- min = mid + 1
- } else {
- min = mid
- break
- }
- }
- }
- return {
- col: offset - lineToIndex[min] + 1,
- line: min + 1
- }
- }
-
- mapResolve(file) {
- if (/^\w+:\/\//.test(file)) {
- return file
- }
- return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
- }
-
- origin(line, column, endLine, endColumn) {
- if (!this.map) return false
- let consumer = this.map.consumer()
-
- let from = consumer.originalPositionFor({ column: column - 1, line })
- if (!from.source) return false
-
- let to
- if (typeof endLine === 'number') {
- to = consumer.originalPositionFor({
- column: endColumn - 1,
- line: endLine
- })
- }
-
- let fromUrl
-
- if (isAbsolute(from.source)) {
- fromUrl = pathToFileURL(from.source)
- } else {
- fromUrl = new URL(
- from.source,
- this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
- )
- }
-
- let result = {
- column: from.column + 1,
- endColumn: to && to.column + 1,
- endLine: to && to.line,
- line: from.line,
- url: fromUrl.toString()
- }
-
- if (fromUrl.protocol === 'file:') {
- if (fileURLToPath) {
- result.file = fileURLToPath(fromUrl)
- } else {
- /* c8 ignore next 2 */
- throw new Error(`file: protocol is not available in this PostCSS build`)
- }
- }
-
- let source = consumer.sourceContentFor(from.source)
- if (source) result.source = source
-
- return result
- }
-
- toJSON() {
- let json = {}
- for (let name of ['hasBOM', 'css', 'file', 'id']) {
- if (this[name] != null) {
- json[name] = this[name]
- }
- }
- if (this.map) {
- json.map = { ...this.map }
- if (json.map.consumerCache) {
- json.map.consumerCache = undefined
- }
- }
- return json
- }
-}
-
-module.exports = Input
-Input.default = Input
-
-if (terminalHighlight && terminalHighlight.registerInput) {
- terminalHighlight.registerInput(Input)
-}
diff --git a/backend/dev-console/node_modules/postcss/lib/lazy-result.d.ts b/backend/dev-console/node_modules/postcss/lib/lazy-result.d.ts
deleted file mode 100644
index 599a614..0000000
--- a/backend/dev-console/node_modules/postcss/lib/lazy-result.d.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import Document from './document.js'
-import { SourceMap } from './postcss.js'
-import Processor from './processor.js'
-import Result, { Message, ResultOptions } from './result.js'
-import Root from './root.js'
-import Warning from './warning.js'
-
-declare namespace LazyResult {
- export { LazyResult_ as default }
-}
-
-/**
- * A Promise proxy for the result of PostCSS transformations.
- *
- * A `LazyResult` instance is returned by `Processor#process`.
- *
- * ```js
- * const lazy = postcss([autoprefixer]).process(css)
- * ```
- */
-declare class LazyResult_ implements PromiseLike<
- Result
-> {
- /**
- * Processes input CSS through synchronous and asynchronous plugins
- * and calls onRejected for each error thrown in any plugin.
- *
- * It implements standard Promise API.
- *
- * ```js
- * postcss([autoprefixer]).process(css).then(result => {
- * console.log(result.css)
- * }).catch(error => {
- * console.error(error)
- * })
- * ```
- */
- catch: Promise>['catch']
-
- /**
- * Processes input CSS through synchronous and asynchronous plugins
- * and calls onFinally on any error or when all plugins will finish work.
- *
- * It implements standard Promise API.
- *
- * ```js
- * postcss([autoprefixer]).process(css).finally(() => {
- * console.log('processing ended')
- * })
- * ```
- */
- finally: Promise>['finally']
-
- /**
- * Processes input CSS through synchronous and asynchronous plugins
- * and calls `onFulfilled` with a Result instance. If a plugin throws
- * an error, the `onRejected` callback will be executed.
- *
- * It implements standard Promise API.
- *
- * ```js
- * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
- * console.log(result.css)
- * })
- * ```
- */
- then: Promise>['then']
-
- /**
- * An alias for the `css` property. Use it with syntaxes
- * that generate non-CSS output.
- *
- * This property will only work with synchronous plugins.
- * If the processor contains any asynchronous plugins
- * it will throw an error.
- *
- * PostCSS runners should always use `LazyResult#then`.
- */
- get content(): string
-
- /**
- * Processes input CSS through synchronous plugins, converts `Root`
- * to a CSS string and returns `Result#css`.
- *
- * This property will only work with synchronous plugins.
- * If the processor contains any asynchronous plugins
- * it will throw an error.
- *
- * PostCSS runners should always use `LazyResult#then`.
- */
- get css(): string
-
- /**
- * Processes input CSS through synchronous plugins
- * and returns `Result#map`.
- *
- * This property will only work with synchronous plugins.
- * If the processor contains any asynchronous plugins
- * it will throw an error.
- *
- * PostCSS runners should always use `LazyResult#then`.
- */
- get map(): SourceMap
-
- /**
- * Processes input CSS through synchronous plugins
- * and returns `Result#messages`.
- *
- * This property will only work with synchronous plugins. If the processor
- * contains any asynchronous plugins it will throw an error.
- *
- * PostCSS runners should always use `LazyResult#then`.
- */
- get messages(): Message[]
-
- /**
- * Options from the `Processor#process` call.
- */
- get opts(): ResultOptions
-
- /**
- * Returns a `Processor` instance, which will be used
- * for CSS transformations.
- */
- get processor(): Processor
-
- /**
- * Processes input CSS through synchronous plugins
- * and returns `Result#root`.
- *
- * This property will only work with synchronous plugins. If the processor
- * contains any asynchronous plugins it will throw an error.
- *
- * PostCSS runners should always use `LazyResult#then`.
- */
- get root(): RootNode
-
- /**
- * Returns the default string description of an object.
- * Required to implement the Promise interface.
- */
- get [Symbol.toStringTag](): string
-
- /**
- * @param processor Processor used for this transformation.
- * @param css CSS to parse and transform.
- * @param opts Options from the `Processor#process` or `Root#toResult`.
- */
- constructor(processor: Processor, css: string, opts: ResultOptions)
-
- /**
- * Run plugin in async way and return `Result`.
- *
- * @return Result with output content.
- */
- async(): Promise>
-
- /**
- * Run plugin in sync way and return `Result`.
- *
- * @return Result with output content.
- */
- sync(): Result
-
- /**
- * Alias for the `LazyResult#css` property.
- *
- * ```js
- * lazy + '' === lazy.css
- * ```
- *
- * @return Output CSS.
- */
- toString(): string
-
- /**
- * Processes input CSS through synchronous plugins
- * and calls `Result#warnings`.
- *
- * @return Warnings from plugins.
- */
- warnings(): Warning[]
-}
-
-declare class LazyResult<
- RootNode = Document | Root
-> extends LazyResult_ {}
-
-export = LazyResult
diff --git a/backend/dev-console/node_modules/postcss/lib/lazy-result.js b/backend/dev-console/node_modules/postcss/lib/lazy-result.js
deleted file mode 100644
index 9026a7c..0000000
--- a/backend/dev-console/node_modules/postcss/lib/lazy-result.js
+++ /dev/null
@@ -1,563 +0,0 @@
-'use strict'
-
-let Container = require('./container')
-let Document = require('./document')
-let MapGenerator = require('./map-generator')
-let parse = require('./parse')
-let Result = require('./result')
-let Root = require('./root')
-let stringify = require('./stringify')
-let { isClean, my } = require('./symbols')
-let warnOnce = require('./warn-once')
-
-const TYPE_TO_CLASS_NAME = {
- atrule: 'AtRule',
- comment: 'Comment',
- decl: 'Declaration',
- document: 'Document',
- root: 'Root',
- rule: 'Rule'
-}
-
-const PLUGIN_PROPS = {
- AtRule: true,
- AtRuleExit: true,
- Comment: true,
- CommentExit: true,
- Declaration: true,
- DeclarationExit: true,
- Document: true,
- DocumentExit: true,
- Once: true,
- OnceExit: true,
- postcssPlugin: true,
- prepare: true,
- Root: true,
- RootExit: true,
- Rule: true,
- RuleExit: true
-}
-
-const NOT_VISITORS = {
- Once: true,
- postcssPlugin: true,
- prepare: true
-}
-
-const CHILDREN = 0
-
-function isPromise(obj) {
- return typeof obj === 'object' && typeof obj.then === 'function'
-}
-
-function getEvents(node) {
- let key = false
- let type = TYPE_TO_CLASS_NAME[node.type]
- if (node.type === 'decl') {
- key = node.prop.toLowerCase()
- } else if (node.type === 'atrule') {
- key = node.name.toLowerCase()
- }
-
- if (key && node.append) {
- return [
- type,
- type + '-' + key,
- CHILDREN,
- type + 'Exit',
- type + 'Exit-' + key
- ]
- } else if (key) {
- return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
- } else if (node.append) {
- return [type, CHILDREN, type + 'Exit']
- } else {
- return [type, type + 'Exit']
- }
-}
-
-function toStack(node) {
- let events
- if (node.type === 'document') {
- events = ['Document', CHILDREN, 'DocumentExit']
- } else if (node.type === 'root') {
- events = ['Root', CHILDREN, 'RootExit']
- } else {
- events = getEvents(node)
- }
-
- return {
- eventIndex: 0,
- events,
- iterator: 0,
- node,
- visitorIndex: 0,
- visitors: []
- }
-}
-
-function cleanMarks(node) {
- node[isClean] = false
- if (node.nodes) node.nodes.forEach(i => cleanMarks(i))
- return node
-}
-
-let postcss = {}
-
-class LazyResult {
- get content() {
- return this.stringify().content
- }
-
- get css() {
- return this.stringify().css
- }
-
- get map() {
- return this.stringify().map
- }
-
- get messages() {
- return this.sync().messages
- }
-
- get opts() {
- return this.result.opts
- }
-
- get processor() {
- return this.result.processor
- }
-
- get root() {
- return this.sync().root
- }
-
- get [Symbol.toStringTag]() {
- return 'LazyResult'
- }
-
- constructor(processor, css, opts) {
- this.stringified = false
- this.processed = false
-
- let root
- if (
- typeof css === 'object' &&
- css !== null &&
- (css.type === 'root' || css.type === 'document')
- ) {
- root = cleanMarks(css)
- } else if (css instanceof LazyResult || css instanceof Result) {
- root = cleanMarks(css.root)
- if (css.map) {
- if (typeof opts.map === 'undefined') opts.map = {}
- if (!opts.map.inline) opts.map.inline = false
- opts.map.prev = css.map
- }
- } else {
- let parser = parse
- if (opts.syntax) parser = opts.syntax.parse
- if (opts.parser) parser = opts.parser
- if (parser.parse) parser = parser.parse
-
- try {
- root = parser(css, opts)
- } catch (error) {
- this.processed = true
- this.error = error
- }
-
- if (root && !root[my]) {
- /* c8 ignore next 2 */
- Container.rebuild(root)
- }
- }
-
- this.result = new Result(processor, root, opts)
- this.helpers = { ...postcss, postcss, result: this.result }
- this.plugins = this.processor.plugins.map(plugin => {
- if (typeof plugin === 'object' && plugin.prepare) {
- return { ...plugin, ...plugin.prepare(this.result) }
- } else {
- return plugin
- }
- })
- }
-
- async() {
- if (this.error) return Promise.reject(this.error)
- if (this.processed) return Promise.resolve(this.result)
- if (!this.processing) {
- this.processing = this.runAsync()
- }
- return this.processing
- }
-
- catch(onRejected) {
- return this.async().catch(onRejected)
- }
-
- finally(onFinally) {
- return this.async().then(onFinally, onFinally)
- }
-
- getAsyncError() {
- throw new Error('Use process(css).then(cb) to work with async plugins')
- }
-
- handleError(error, node) {
- let plugin = this.result.lastPlugin
- try {
- if (node) node.addToError(error)
- this.error = error
- if (error.name === 'CssSyntaxError' && !error.plugin) {
- error.plugin = plugin.postcssPlugin
- error.setMessage()
- } else if (plugin.postcssVersion) {
- if (process.env.NODE_ENV !== 'production') {
- let pluginName = plugin.postcssPlugin
- let pluginVer = plugin.postcssVersion
- let runtimeVer = this.result.processor.version
- let a = pluginVer.split('.')
- let b = runtimeVer.split('.')
-
- if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
- // eslint-disable-next-line no-console
- console.error(
- 'Unknown error from PostCSS plugin. Your current PostCSS ' +
- 'version is ' +
- runtimeVer +
- ', but ' +
- pluginName +
- ' uses ' +
- pluginVer +
- '. Perhaps this is the source of the error below.'
- )
- }
- }
- }
- } catch (err) {
- /* c8 ignore next 3 */
- // eslint-disable-next-line no-console
- if (console && console.error) console.error(err)
- }
- return error
- }
-
- prepareVisitors() {
- this.listeners = {}
- let add = (plugin, type, cb) => {
- if (!this.listeners[type]) this.listeners[type] = []
- this.listeners[type].push([plugin, cb])
- }
- for (let plugin of this.plugins) {
- if (typeof plugin === 'object') {
- for (let event in plugin) {
- if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
- throw new Error(
- `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
- `Try to update PostCSS (${this.processor.version} now).`
- )
- }
- if (!NOT_VISITORS[event]) {
- if (typeof plugin[event] === 'object') {
- for (let filter in plugin[event]) {
- if (filter === '*') {
- add(plugin, event, plugin[event][filter])
- } else {
- add(
- plugin,
- event + '-' + filter.toLowerCase(),
- plugin[event][filter]
- )
- }
- }
- } else if (typeof plugin[event] === 'function') {
- add(plugin, event, plugin[event])
- }
- }
- }
- }
- }
- this.hasListener = Object.keys(this.listeners).length > 0
- }
-
- async runAsync() {
- this.plugin = 0
- for (let i = 0; i < this.plugins.length; i++) {
- let plugin = this.plugins[i]
- let promise = this.runOnRoot(plugin)
- if (isPromise(promise)) {
- try {
- await promise
- } catch (error) {
- throw this.handleError(error)
- }
- }
- }
-
- this.prepareVisitors()
- if (this.hasListener) {
- let root = this.result.root
- while (!root[isClean]) {
- root[isClean] = true
- let stack = [toStack(root)]
- while (stack.length > 0) {
- let promise = this.visitTick(stack)
- if (isPromise(promise)) {
- try {
- await promise
- } catch (e) {
- let node = stack[stack.length - 1].node
- throw this.handleError(e, node)
- }
- }
- }
- }
-
- if (this.listeners.OnceExit) {
- for (let [plugin, visitor] of this.listeners.OnceExit) {
- this.result.lastPlugin = plugin
- try {
- if (root.type === 'document') {
- let roots = root.nodes.map(subRoot =>
- visitor(subRoot, this.helpers)
- )
-
- await Promise.all(roots)
- } else {
- await visitor(root, this.helpers)
- }
- } catch (e) {
- throw this.handleError(e)
- }
- }
- }
- }
-
- this.processed = true
- return this.stringify()
- }
-
- runOnRoot(plugin) {
- this.result.lastPlugin = plugin
- try {
- if (typeof plugin === 'object' && plugin.Once) {
- if (this.result.root.type === 'document') {
- let roots = this.result.root.nodes.map(root =>
- plugin.Once(root, this.helpers)
- )
-
- if (isPromise(roots[0])) {
- return Promise.all(roots)
- }
-
- return roots
- }
-
- return plugin.Once(this.result.root, this.helpers)
- } else if (typeof plugin === 'function') {
- return plugin(this.result.root, this.result)
- }
- } catch (error) {
- throw this.handleError(error)
- }
- }
-
- stringify() {
- if (this.error) throw this.error
- if (this.stringified) return this.result
- this.stringified = true
-
- this.sync()
-
- let opts = this.result.opts
- let str = stringify
- if (opts.syntax) str = opts.syntax.stringify
- if (opts.stringifier) str = opts.stringifier
- if (str.stringify) str = str.stringify
-
- let rootSource = this.result.root.source
- if (
- opts.map === undefined &&
- !(rootSource && rootSource.input && rootSource.input.map)
- ) {
- let result = ''
- str(this.result.root, i => {
- result += i
- })
- this.result.css = result
- return this.result
- }
-
- let map = new MapGenerator(str, this.result.root, this.result.opts)
- let data = map.generate()
- this.result.css = data[0]
- this.result.map = data[1]
-
- return this.result
- }
-
- sync() {
- if (this.error) throw this.error
- if (this.processed) return this.result
- this.processed = true
-
- if (this.processing) {
- throw this.getAsyncError()
- }
-
- for (let plugin of this.plugins) {
- let promise = this.runOnRoot(plugin)
- if (isPromise(promise)) {
- throw this.getAsyncError()
- }
- }
-
- this.prepareVisitors()
- if (this.hasListener) {
- let root = this.result.root
- while (!root[isClean]) {
- root[isClean] = true
- this.walkSync(root)
- }
- if (this.listeners.OnceExit) {
- if (root.type === 'document') {
- for (let subRoot of root.nodes) {
- this.visitSync(this.listeners.OnceExit, subRoot)
- }
- } else {
- this.visitSync(this.listeners.OnceExit, root)
- }
- }
- }
-
- return this.result
- }
-
- then(onFulfilled, onRejected) {
- if (process.env.NODE_ENV !== 'production') {
- if (!('from' in this.opts)) {
- warnOnce(
- 'Without `from` option PostCSS could generate wrong source map ' +
- 'and will not find Browserslist config. Set it to CSS file path ' +
- 'or to `undefined` to prevent this warning.'
- )
- }
- }
- return this.async().then(onFulfilled, onRejected)
- }
-
- toString() {
- return this.css
- }
-
- visitSync(visitors, node) {
- for (let [plugin, visitor] of visitors) {
- this.result.lastPlugin = plugin
- let promise
- try {
- promise = visitor(node, this.helpers)
- } catch (e) {
- throw this.handleError(e, node.proxyOf)
- }
- if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
- return true
- }
- if (isPromise(promise)) {
- throw this.getAsyncError()
- }
- }
- }
-
- visitTick(stack) {
- let visit = stack[stack.length - 1]
- let { node, visitors } = visit
-
- if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
- stack.pop()
- return
- }
-
- if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
- let [plugin, visitor] = visitors[visit.visitorIndex]
- visit.visitorIndex += 1
- if (visit.visitorIndex === visitors.length) {
- visit.visitors = []
- visit.visitorIndex = 0
- }
- this.result.lastPlugin = plugin
- try {
- return visitor(node.toProxy(), this.helpers)
- } catch (e) {
- throw this.handleError(e, node)
- }
- }
-
- if (visit.iterator !== 0) {
- let iterator = visit.iterator
- let child
- while ((child = node.nodes[node.indexes[iterator]])) {
- node.indexes[iterator] += 1
- if (!child[isClean]) {
- child[isClean] = true
- stack.push(toStack(child))
- return
- }
- }
- visit.iterator = 0
- delete node.indexes[iterator]
- }
-
- let events = visit.events
- while (visit.eventIndex < events.length) {
- let event = events[visit.eventIndex]
- visit.eventIndex += 1
- if (event === CHILDREN) {
- if (node.nodes && node.nodes.length) {
- node[isClean] = true
- visit.iterator = node.getIterator()
- }
- return
- } else if (this.listeners[event]) {
- visit.visitors = this.listeners[event]
- return
- }
- }
- stack.pop()
- }
-
- walkSync(node) {
- node[isClean] = true
- let events = getEvents(node)
- for (let event of events) {
- if (event === CHILDREN) {
- if (node.nodes) {
- node.each(child => {
- if (!child[isClean]) this.walkSync(child)
- })
- }
- } else {
- let visitors = this.listeners[event]
- if (visitors) {
- if (this.visitSync(visitors, node.toProxy())) return
- }
- }
- }
- }
-
- warnings() {
- return this.sync().warnings()
- }
-}
-
-LazyResult.registerPostcss = dependant => {
- postcss = dependant
-}
-
-module.exports = LazyResult
-LazyResult.default = LazyResult
-
-Root.registerLazyResult(LazyResult)
-Document.registerLazyResult(LazyResult)
diff --git a/backend/dev-console/node_modules/postcss/lib/list.d.ts b/backend/dev-console/node_modules/postcss/lib/list.d.ts
deleted file mode 100644
index 119624e..0000000
--- a/backend/dev-console/node_modules/postcss/lib/list.d.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-declare namespace list {
- type List = {
- /**
- * Safely splits comma-separated values (such as those for `transition-*`
- * and `background` properties).
- *
- * ```js
- * Once (root, { list }) {
- * list.comma('black, linear-gradient(white, black)')
- * //=> ['black', 'linear-gradient(white, black)']
- * }
- * ```
- *
- * @param str Comma-separated values.
- * @return Split values.
- */
- comma(str: string): string[]
-
- default: List
-
- /**
- * Safely splits space-separated values (such as those for `background`,
- * `border-radius`, and other shorthand properties).
- *
- * ```js
- * Once (root, { list }) {
- * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
- * }
- * ```
- *
- * @param str Space-separated values.
- * @return Split values.
- */
- space(str: string): string[]
-
- /**
- * Safely splits values.
- *
- * ```js
- * Once (root, { list }) {
- * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)']
- * }
- * ```
- *
- * @param string separated values.
- * @param separators array of separators.
- * @param last boolean indicator.
- * @return Split values.
- */
- split(
- string: string,
- separators: readonly string[],
- last: boolean
- ): string[]
- }
-}
-
-declare let list: list.List
-
-export = list
diff --git a/backend/dev-console/node_modules/postcss/lib/list.js b/backend/dev-console/node_modules/postcss/lib/list.js
deleted file mode 100644
index 1b31f98..0000000
--- a/backend/dev-console/node_modules/postcss/lib/list.js
+++ /dev/null
@@ -1,58 +0,0 @@
-'use strict'
-
-let list = {
- comma(string) {
- return list.split(string, [','], true)
- },
-
- space(string) {
- let spaces = [' ', '\n', '\t']
- return list.split(string, spaces)
- },
-
- split(string, separators, last) {
- let array = []
- let current = ''
- let split = false
-
- let func = 0
- let inQuote = false
- let prevQuote = ''
- let escape = false
-
- for (let letter of string) {
- if (escape) {
- escape = false
- } else if (letter === '\\') {
- escape = true
- } else if (inQuote) {
- if (letter === prevQuote) {
- inQuote = false
- }
- } else if (letter === '"' || letter === "'") {
- inQuote = true
- prevQuote = letter
- } else if (letter === '(') {
- func += 1
- } else if (letter === ')') {
- if (func > 0) func -= 1
- } else if (func === 0) {
- if (separators.includes(letter)) split = true
- }
-
- if (split) {
- if (current !== '') array.push(current.trim())
- current = ''
- split = false
- } else {
- current += letter
- }
- }
-
- if (last || current !== '') array.push(current.trim())
- return array
- }
-}
-
-module.exports = list
-list.default = list
diff --git a/backend/dev-console/node_modules/postcss/lib/map-generator.js b/backend/dev-console/node_modules/postcss/lib/map-generator.js
deleted file mode 100644
index df880ac..0000000
--- a/backend/dev-console/node_modules/postcss/lib/map-generator.js
+++ /dev/null
@@ -1,376 +0,0 @@
-'use strict'
-
-let { dirname, relative, resolve, sep } = require('path')
-let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
-let { pathToFileURL } = require('url')
-
-let Input = require('./input')
-
-let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
-let pathAvailable = Boolean(dirname && resolve && relative && sep)
-
-class MapGenerator {
- constructor(stringify, root, opts, cssString) {
- this.stringify = stringify
- this.mapOpts = opts.map || {}
- this.root = root
- this.opts = opts
- this.css = cssString
- this.originalCSS = cssString
- this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute
-
- this.memoizedFileURLs = new Map()
- this.memoizedPaths = new Map()
- this.memoizedURLs = new Map()
- }
-
- addAnnotation() {
- let content
-
- if (this.isInline()) {
- content =
- 'data:application/json;base64,' + this.toBase64(this.map.toString())
- } else if (typeof this.mapOpts.annotation === 'string') {
- content = this.mapOpts.annotation
- } else if (typeof this.mapOpts.annotation === 'function') {
- content = this.mapOpts.annotation(this.opts.to, this.root)
- } else {
- content = this.outputFile() + '.map'
- }
- let eol = '\n'
- if (this.css.includes('\r\n')) eol = '\r\n'
-
- this.css += eol + '/*# sourceMappingURL=' + content + ' */'
- }
-
- applyPrevMaps() {
- for (let prev of this.previous()) {
- let from = this.toUrl(this.path(prev.file))
- let root = prev.root || dirname(prev.file)
- let map
-
- if (this.mapOpts.sourcesContent === false) {
- map = new SourceMapConsumer(prev.text)
- if (map.sourcesContent) {
- map.sourcesContent = null
- }
- } else {
- map = prev.consumer()
- }
-
- this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
- }
- }
-
- clearAnnotation() {
- if (this.mapOpts.annotation === false) return
-
- if (this.root) {
- let node
- for (let i = this.root.nodes.length - 1; i >= 0; i--) {
- node = this.root.nodes[i]
- if (node.type !== 'comment') continue
- if (node.text.startsWith('# sourceMappingURL=')) {
- this.root.removeChild(i)
- }
- }
- } else if (this.css) {
- let startIndex
- while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) {
- let endIndex = this.css.indexOf('*/', startIndex + 3)
- if (endIndex === -1) break
- while (startIndex > 0 && this.css[startIndex - 1] === '\n') {
- startIndex--
- }
- this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2)
- }
- }
- }
-
- generate() {
- this.clearAnnotation()
- if (pathAvailable && sourceMapAvailable && this.isMap()) {
- return this.generateMap()
- } else {
- let result = ''
- this.stringify(this.root, i => {
- result += i
- })
- return [result]
- }
- }
-
- generateMap() {
- if (this.root) {
- this.generateString()
- } else if (this.previous().length === 1) {
- let prev = this.previous()[0].consumer()
- prev.file = this.outputFile()
- this.map = SourceMapGenerator.fromSourceMap(prev, {
- ignoreInvalidMapping: true
- })
- } else {
- this.map = new SourceMapGenerator({
- file: this.outputFile(),
- ignoreInvalidMapping: true
- })
- this.map.addMapping({
- generated: { column: 0, line: 1 },
- original: { column: 0, line: 1 },
- source: this.opts.from
- ? this.toUrl(this.path(this.opts.from))
- : ''
- })
- }
-
- if (this.isSourcesContent()) this.setSourcesContent()
- if (this.root && this.previous().length > 0) this.applyPrevMaps()
- if (this.isAnnotation()) this.addAnnotation()
-
- if (this.isInline()) {
- return [this.css]
- } else {
- return [this.css, this.map]
- }
- }
-
- generateString() {
- this.css = ''
- this.map = new SourceMapGenerator({
- file: this.outputFile(),
- ignoreInvalidMapping: true
- })
-
- let line = 1
- let column = 1
-
- let noSource = ''
- let mapping = {
- generated: { column: 0, line: 0 },
- original: { column: 0, line: 0 },
- source: ''
- }
-
- let last, lines
- this.stringify(this.root, (str, node, type) => {
- this.css += str
-
- if (node && type !== 'end') {
- mapping.generated.line = line
- mapping.generated.column = column - 1
- if (node.source && node.source.start) {
- mapping.source = this.sourcePath(node)
- mapping.original.line = node.source.start.line
- mapping.original.column = node.source.start.column - 1
- this.map.addMapping(mapping)
- } else {
- mapping.source = noSource
- mapping.original.line = 1
- mapping.original.column = 0
- this.map.addMapping(mapping)
- }
- }
-
- lines = str.match(/\n/g)
- if (lines) {
- line += lines.length
- last = str.lastIndexOf('\n')
- column = str.length - last
- } else {
- column += str.length
- }
-
- if (node && type !== 'start') {
- let p = node.parent || { raws: {} }
- let childless =
- node.type === 'decl' || (node.type === 'atrule' && !node.nodes)
- if (!childless || node !== p.last || p.raws.semicolon) {
- if (node.source && node.source.end) {
- mapping.source = this.sourcePath(node)
- mapping.original.line = node.source.end.line
- mapping.original.column = node.source.end.column - 1
- mapping.generated.line = line
- mapping.generated.column = column - 2
- this.map.addMapping(mapping)
- } else {
- mapping.source = noSource
- mapping.original.line = 1
- mapping.original.column = 0
- mapping.generated.line = line
- mapping.generated.column = column - 1
- this.map.addMapping(mapping)
- }
- }
- }
- })
- }
-
- isAnnotation() {
- if (this.isInline()) {
- return true
- }
- if (typeof this.mapOpts.annotation !== 'undefined') {
- return this.mapOpts.annotation
- }
- if (this.previous().length) {
- return this.previous().some(i => i.annotation)
- }
- return true
- }
-
- isInline() {
- if (typeof this.mapOpts.inline !== 'undefined') {
- return this.mapOpts.inline
- }
-
- let annotation = this.mapOpts.annotation
- if (typeof annotation !== 'undefined' && annotation !== true) {
- return false
- }
-
- if (this.previous().length) {
- return this.previous().some(i => i.inline)
- }
- return true
- }
-
- isMap() {
- if (typeof this.opts.map !== 'undefined') {
- return !!this.opts.map
- }
- return this.previous().length > 0
- }
-
- isSourcesContent() {
- if (typeof this.mapOpts.sourcesContent !== 'undefined') {
- return this.mapOpts.sourcesContent
- }
- if (this.previous().length) {
- return this.previous().some(i => i.withContent())
- }
- return true
- }
-
- outputFile() {
- if (this.opts.to) {
- return this.path(this.opts.to)
- } else if (this.opts.from) {
- return this.path(this.opts.from)
- } else {
- return 'to.css'
- }
- }
-
- path(file) {
- if (this.mapOpts.absolute) return file
- if (file.charCodeAt(0) === 60 /* `<` */) return file
- if (/^\w+:\/\//.test(file)) return file
- let cached = this.memoizedPaths.get(file)
- if (cached) return cached
-
- let from = this.opts.to ? dirname(this.opts.to) : '.'
-
- if (typeof this.mapOpts.annotation === 'string') {
- from = dirname(resolve(from, this.mapOpts.annotation))
- }
-
- let path = relative(from, file)
- this.memoizedPaths.set(file, path)
-
- return path
- }
-
- previous() {
- if (!this.previousMaps) {
- this.previousMaps = []
- if (this.root) {
- this.root.walk(node => {
- if (node.source && node.source.input.map) {
- let map = node.source.input.map
- if (!this.previousMaps.includes(map)) {
- this.previousMaps.push(map)
- }
- }
- })
- } else {
- let input = new Input(this.originalCSS, this.opts)
- if (input.map) this.previousMaps.push(input.map)
- }
- }
-
- return this.previousMaps
- }
-
- setSourcesContent() {
- let already = {}
- if (this.root) {
- this.root.walk(node => {
- if (node.source) {
- let from = node.source.input.from
- if (from && !already[from]) {
- already[from] = true
- let fromUrl = this.usesFileUrls
- ? this.toFileUrl(from)
- : this.toUrl(this.path(from))
- this.map.setSourceContent(fromUrl, node.source.input.css)
- }
- }
- })
- } else if (this.css) {
- let from = this.opts.from
- ? this.toUrl(this.path(this.opts.from))
- : ''
- this.map.setSourceContent(from, this.css)
- }
- }
-
- sourcePath(node) {
- if (this.mapOpts.from) {
- return this.toUrl(this.mapOpts.from)
- } else if (this.usesFileUrls) {
- return this.toFileUrl(node.source.input.from)
- } else {
- return this.toUrl(this.path(node.source.input.from))
- }
- }
-
- toBase64(str) {
- if (Buffer) {
- return Buffer.from(str).toString('base64')
- } else {
- return window.btoa(unescape(encodeURIComponent(str)))
- }
- }
-
- toFileUrl(path) {
- let cached = this.memoizedFileURLs.get(path)
- if (cached) return cached
-
- if (pathToFileURL) {
- let fileURL = pathToFileURL(path).toString()
- this.memoizedFileURLs.set(path, fileURL)
-
- return fileURL
- } else {
- throw new Error(
- '`map.absolute` option is not available in this PostCSS build'
- )
- }
- }
-
- toUrl(path) {
- let cached = this.memoizedURLs.get(path)
- if (cached) return cached
-
- if (sep === '\\') {
- path = path.replace(/\\/g, '/')
- }
-
- let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent)
- this.memoizedURLs.set(path, url)
-
- return url
- }
-}
-
-module.exports = MapGenerator
diff --git a/backend/dev-console/node_modules/postcss/lib/no-work-result.d.ts b/backend/dev-console/node_modules/postcss/lib/no-work-result.d.ts
deleted file mode 100644
index fa9d284..0000000
--- a/backend/dev-console/node_modules/postcss/lib/no-work-result.d.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import LazyResult from './lazy-result.js'
-import { SourceMap } from './postcss.js'
-import Processor from './processor.js'
-import Result, { Message, ResultOptions } from './result.js'
-import Root from './root.js'
-import Warning from './warning.js'
-
-declare namespace NoWorkResult {
- export { NoWorkResult_ as default }
-}
-
-/**
- * A Promise proxy for the result of PostCSS transformations.
- * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root`
- * are accessed. See the example below for details.
- * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined.
- *
- * ```js
- * const noWorkResult = postcss().process(css) // No plugins are defined.
- * // CSS is not parsed
- * let root = noWorkResult.root // now css is parsed because we accessed the root
- * ```
- */
-declare class NoWorkResult_ implements LazyResult {
- catch: Promise>['catch']
- finally: Promise>['finally']
- then: Promise>['then']
- get content(): string
- get css(): string
- get map(): SourceMap
- get messages(): Message[]
- get opts(): ResultOptions
- get processor(): Processor
- get root(): Root
- get [Symbol.toStringTag](): string
- constructor(processor: Processor, css: string, opts: ResultOptions)
- async(): Promise>
- sync(): Result
- toString(): string
- warnings(): Warning[]
-}
-
-declare class NoWorkResult extends NoWorkResult_ {}
-
-export = NoWorkResult
diff --git a/backend/dev-console/node_modules/postcss/lib/no-work-result.js b/backend/dev-console/node_modules/postcss/lib/no-work-result.js
deleted file mode 100644
index 7ec1a74..0000000
--- a/backend/dev-console/node_modules/postcss/lib/no-work-result.js
+++ /dev/null
@@ -1,137 +0,0 @@
-'use strict'
-
-let MapGenerator = require('./map-generator')
-let parse = require('./parse')
-let Result = require('./result')
-let stringify = require('./stringify')
-let warnOnce = require('./warn-once')
-
-class NoWorkResult {
- get content() {
- return this.result.css
- }
-
- get css() {
- return this.result.css
- }
-
- get map() {
- return this.result.map
- }
-
- get messages() {
- return []
- }
-
- get opts() {
- return this.result.opts
- }
-
- get processor() {
- return this.result.processor
- }
-
- get root() {
- if (this._root) {
- return this._root
- }
-
- let root
- let parser = parse
-
- try {
- root = parser(this._css, this._opts)
- } catch (error) {
- this.error = error
- }
-
- if (this.error) {
- throw this.error
- } else {
- this._root = root
- return root
- }
- }
-
- get [Symbol.toStringTag]() {
- return 'NoWorkResult'
- }
-
- constructor(processor, css, opts) {
- css = css.toString()
- this.stringified = false
-
- this._processor = processor
- this._css = css
- this._opts = opts
- this._map = undefined
-
- let str = stringify
- this.result = new Result(this._processor, undefined, this._opts)
- this.result.css = css
-
- let self = this
- Object.defineProperty(this.result, 'root', {
- get() {
- return self.root
- }
- })
-
- let map = new MapGenerator(str, undefined, this._opts, css)
- if (map.isMap()) {
- let [generatedCSS, generatedMap] = map.generate()
- if (generatedCSS) {
- this.result.css = generatedCSS
- }
- if (generatedMap) {
- this.result.map = generatedMap
- }
- } else {
- map.clearAnnotation()
- this.result.css = map.css
- }
- }
-
- async() {
- if (this.error) return Promise.reject(this.error)
- return Promise.resolve(this.result)
- }
-
- catch(onRejected) {
- return this.async().catch(onRejected)
- }
-
- finally(onFinally) {
- return this.async().then(onFinally, onFinally)
- }
-
- sync() {
- if (this.error) throw this.error
- return this.result
- }
-
- then(onFulfilled, onRejected) {
- if (process.env.NODE_ENV !== 'production') {
- if (!('from' in this._opts)) {
- warnOnce(
- 'Without `from` option PostCSS could generate wrong source map ' +
- 'and will not find Browserslist config. Set it to CSS file path ' +
- 'or to `undefined` to prevent this warning.'
- )
- }
- }
-
- return this.async().then(onFulfilled, onRejected)
- }
-
- toString() {
- return this._css
- }
-
- warnings() {
- return []
- }
-}
-
-module.exports = NoWorkResult
-NoWorkResult.default = NoWorkResult
diff --git a/backend/dev-console/node_modules/postcss/lib/node.d.ts b/backend/dev-console/node_modules/postcss/lib/node.d.ts
deleted file mode 100644
index ecd86e2..0000000
--- a/backend/dev-console/node_modules/postcss/lib/node.d.ts
+++ /dev/null
@@ -1,555 +0,0 @@
-import AtRule = require('./at-rule.js')
-import { AtRuleProps } from './at-rule.js'
-import Comment, { CommentProps } from './comment.js'
-import Container, { NewChild } from './container.js'
-import CssSyntaxError from './css-syntax-error.js'
-import Declaration, { DeclarationProps } from './declaration.js'
-import Document from './document.js'
-import Input from './input.js'
-import { Stringifier, Syntax } from './postcss.js'
-import Result from './result.js'
-import Root from './root.js'
-import Rule, { RuleProps } from './rule.js'
-import Warning, { WarningOptions } from './warning.js'
-
-declare namespace Node {
- export type ChildNode = AtRule.default | Comment | Declaration | Rule
-
- export type AnyNode =
- | AtRule.default
- | Comment
- | Declaration
- | Document
- | Root
- | Rule
-
- export type ChildProps =
- | AtRuleProps
- | CommentProps
- | DeclarationProps
- | RuleProps
-
- export interface Position {
- /**
- * Source line in file. In contrast to `offset` it starts from 1.
- */
- column: number
-
- /**
- * Source column in file.
- */
- line: number
-
- /**
- * Source offset in file. It starts from 0.
- */
- offset: number
- }
-
- export interface Range {
- /**
- * End position, exclusive.
- */
- end: Position
-
- /**
- * Start position, inclusive.
- */
- start: Position
- }
-
- /**
- * Source represents an interface for the {@link Node.source} property.
- */
- export interface Source {
- /**
- * The inclusive ending position for the source
- * code of a node.
- *
- * However, `end.offset` of a non `Root` node is the exclusive position.
- * See https://github.com/postcss/postcss/pull/1879 for details.
- *
- * ```js
- * const root = postcss.parse('a { color: black }')
- * const a = root.first
- * const color = a.first
- *
- * // The offset of `Root` node is the inclusive position
- * css.source.end // { line: 1, column: 19, offset: 18 }
- *
- * // The offset of non `Root` node is the exclusive position
- * a.source.end // { line: 1, column: 18, offset: 18 }
- * color.source.end // { line: 1, column: 16, offset: 16 }
- * ```
- */
- end?: Position
-
- /**
- * The source file from where a node has originated.
- */
- input: Input
-
- /**
- * The inclusive starting position for the source
- * code of a node.
- */
- start?: Position
- }
-
- /**
- * Interface represents an interface for an object received
- * as parameter by Node class constructor.
- */
- export interface NodeProps {
- source?: Source
- }
-
- export interface NodeErrorOptions {
- /**
- * An ending index inside a node's string that should be highlighted as
- * source of error.
- */
- endIndex?: number
- /**
- * An index inside a node's string that should be highlighted as source
- * of error.
- */
- index?: number
- /**
- * Plugin name that created this error. PostCSS will set it automatically.
- */
- plugin?: string
- /**
- * A word inside a node's string, that should be highlighted as source
- * of error.
- */
- word?: string
- }
-
- class Node extends Node_ {}
- export { Node as default }
-}
-
-/**
- * It represents an abstract class that handles common
- * methods for other CSS abstract syntax tree nodes.
- *
- * Any node that represents CSS selector or value should
- * not extend the `Node` class.
- */
-declare abstract class Node_ {
- /**
- * It represents parent of the current node.
- *
- * ```js
- * root.nodes[0].parent === root //=> true
- * ```
- */
- parent: Container | Document | undefined
-
- /**
- * It represents unnecessary whitespace and characters present
- * in the css source code.
- *
- * Information to generate byte-to-byte equal node string as it was
- * in the origin input.
- *
- * The properties of the raws object are decided by parser,
- * the default parser uses the following properties:
- *
- * * `before`: the space symbols before the node. It also stores `*`
- * and `_` symbols before the declaration (IE hack).
- * * `after`: the space symbols after the last child of the node
- * to the end of the node.
- * * `between`: the symbols between the property and value
- * for declarations, selector and `{` for rules, or last parameter
- * and `{` for at-rules.
- * * `semicolon`: contains true if the last child has
- * an (optional) semicolon.
- * * `afterName`: the space between the at-rule name and its parameters.
- * * `left`: the space symbols between `/*` and the comment’s text.
- * * `right`: the space symbols between the comment’s text
- * and */.
- * - `important`: the content of the important statement,
- * if it is not just `!important`.
- *
- * PostCSS filters out the comments inside selectors, declaration values
- * and at-rule parameters but it stores the origin content in raws.
- *
- * ```js
- * const root = postcss.parse('a {\n color:black\n}')
- * root.first.first.raws //=> { before: '\n ', between: ':' }
- * ```
- */
- raws: any
-
- /**
- * It represents information related to origin of a node and is required
- * for generating source maps.
- *
- * The nodes that are created manually using the public APIs
- * provided by PostCSS will have `source` undefined and
- * will be absent in the source map.
- *
- * For this reason, the plugin developer should consider
- * duplicating nodes as the duplicate node will have the
- * same source as the original node by default or assign
- * source to a node created manually.
- *
- * ```js
- * decl.source.input.from //=> '/home/ai/source.css'
- * decl.source.start //=> { line: 10, column: 2 }
- * decl.source.end //=> { line: 10, column: 12 }
- * ```
- *
- * ```js
- * // Incorrect method, source not specified!
- * const prefixed = postcss.decl({
- * prop: '-moz-' + decl.prop,
- * value: decl.value
- * })
- *
- * // Correct method, source is inherited when duplicating.
- * const prefixed = decl.clone({
- * prop: '-moz-' + decl.prop
- * })
- * ```
- *
- * ```js
- * if (atrule.name === 'add-link') {
- * const rule = postcss.rule({
- * selector: 'a',
- * source: atrule.source
- * })
- *
- * atrule.parent.insertBefore(atrule, rule)
- * }
- * ```
- */
- source?: Node.Source
-
- /**
- * It represents type of a node in
- * an abstract syntax tree.
- *
- * A type of node helps in identification of a node
- * and perform operation based on it's type.
- *
- * ```js
- * const declaration = new Declaration({
- * prop: 'color',
- * value: 'black'
- * })
- *
- * declaration.type //=> 'decl'
- * ```
- */
- type: string
-
- constructor(defaults?: object)
-
- /**
- * Insert new node after current node to current node’s parent.
- *
- * Just alias for `node.parent.insertAfter(node, add)`.
- *
- * ```js
- * decl.after('color: black')
- * ```
- *
- * @param newNode New node.
- * @return This node for methods chain.
- */
- after(
- newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
- ): this
-
- /**
- * It assigns properties to an existing node instance.
- *
- * ```js
- * decl.assign({ prop: 'word-wrap', value: 'break-word' })
- * ```
- *
- * @param overrides New properties to override the node.
- *
- * @return `this` for method chaining.
- */
- assign(overrides: object): this
-
- /**
- * Insert new node before current node to current node’s parent.
- *
- * Just alias for `node.parent.insertBefore(node, add)`.
- *
- * ```js
- * decl.before('content: ""')
- * ```
- *
- * @param newNode New node.
- * @return This node for methods chain.
- */
- before(
- newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
- ): this
-
- /**
- * Clear the code style properties for the node and its children.
- *
- * ```js
- * node.raws.before //=> ' '
- * node.cleanRaws()
- * node.raws.before //=> undefined
- * ```
- *
- * @param keepBetween Keep the `raws.between` symbols.
- */
- cleanRaws(keepBetween?: boolean): void
-
- /**
- * It creates clone of an existing node, which includes all the properties
- * and their values, that includes `raws` but not `type`.
- *
- * ```js
- * decl.raws.before //=> "\n "
- * const cloned = decl.clone({ prop: '-moz-' + decl.prop })
- * cloned.raws.before //=> "\n "
- * cloned.toString() //=> -moz-transform: scale(0)
- * ```
- *
- * @param overrides New properties to override in the clone.
- *
- * @return Duplicate of the node instance.
- */
- clone(overrides?: object): this
-
- /**
- * Shortcut to clone the node and insert the resulting cloned node
- * after the current node.
- *
- * @param overrides New properties to override in the clone.
- * @return New node.
- */
- cloneAfter(overrides?: object): this
-
- /**
- * Shortcut to clone the node and insert the resulting cloned node
- * before the current node.
- *
- * ```js
- * decl.cloneBefore({ prop: '-moz-' + decl.prop })
- * ```
- *
- * @param overrides Mew properties to override in the clone.
- *
- * @return New node
- */
- cloneBefore(overrides?: object): this
-
- /**
- * It creates an instance of the class `CssSyntaxError` and parameters passed
- * to this method are assigned to the error instance.
- *
- * The error instance will have description for the
- * error, original position of the node in the
- * source, showing line and column number.
- *
- * If any previous map is present, it would be used
- * to get original position of the source.
- *
- * The Previous Map here is referred to the source map
- * generated by previous compilation, example: Less,
- * Stylus and Sass.
- *
- * This method returns the error instance instead of
- * throwing it.
- *
- * ```js
- * if (!variables[name]) {
- * throw decl.error(`Unknown variable ${name}`, { word: name })
- * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
- * // color: $black
- * // a
- * // ^
- * // background: white
- * }
- * ```
- *
- * @param message Description for the error instance.
- * @param options Options for the error instance.
- *
- * @return Error instance is returned.
- */
- error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError
-
- /**
- * Returns the next child of the node’s parent.
- * Returns `undefined` if the current node is the last child.
- *
- * ```js
- * if (comment.text === 'delete next') {
- * const next = comment.next()
- * if (next) {
- * next.remove()
- * }
- * }
- * ```
- *
- * @return Next node.
- */
- next(): Node.ChildNode | undefined
-
- /**
- * Get the position for a word or an index inside the node.
- *
- * @param opts Options.
- * @return Position.
- */
- positionBy(opts?: Pick): Node.Position
-
- /**
- * Convert string index to line/column.
- *
- * @param index The symbol number in the node’s string.
- * @return Symbol position in file.
- */
- positionInside(index: number): Node.Position
-
- /**
- * Returns the previous child of the node’s parent.
- * Returns `undefined` if the current node is the first child.
- *
- * ```js
- * const annotation = decl.prev()
- * if (annotation.type === 'comment') {
- * readAnnotation(annotation.text)
- * }
- * ```
- *
- * @return Previous node.
- */
- prev(): Node.ChildNode | undefined
-
- /**
- * Get the range for a word or start and end index inside the node.
- * The start index is inclusive; the end index is exclusive.
- *
- * @param opts Options.
- * @return Range.
- */
- rangeBy(
- opts?: Pick
- ): Node.Range
-
- /**
- * Returns a `raws` value. If the node is missing
- * the code style property (because the node was manually built or cloned),
- * PostCSS will try to autodetect the code style property by looking
- * at other nodes in the tree.
- *
- * ```js
- * const root = postcss.parse('a { background: white }')
- * root.nodes[0].append({ prop: 'color', value: 'black' })
- * root.nodes[0].nodes[1].raws.before //=> undefined
- * root.nodes[0].nodes[1].raw('before') //=> ' '
- * ```
- *
- * @param prop Name of code style property.
- * @param defaultType Name of default value, it can be missed
- * if the value is the same as prop.
- * @return {string} Code style value.
- */
- raw(prop: string, defaultType?: string): string
-
- /**
- * It removes the node from its parent and deletes its parent property.
- *
- * ```js
- * if (decl.prop.match(/^-webkit-/)) {
- * decl.remove()
- * }
- * ```
- *
- * @return `this` for method chaining.
- */
- remove(): this
-
- /**
- * Inserts node(s) before the current node and removes the current node.
- *
- * ```js
- * AtRule: {
- * mixin: atrule => {
- * atrule.replaceWith(mixinRules[atrule.params])
- * }
- * }
- * ```
- *
- * @param nodes Mode(s) to replace current one.
- * @return Current node to methods chain.
- */
- replaceWith(...nodes: NewChild[]): this
-
- /**
- * Finds the Root instance of the node’s tree.
- *
- * ```js
- * root.nodes[0].nodes[0].root() === root
- * ```
- *
- * @return Root parent.
- */
- root(): Root
-
- /**
- * Fix circular links on `JSON.stringify()`.
- *
- * @return Cleaned object.
- */
- toJSON(): object
-
- /**
- * It compiles the node to browser readable cascading style sheets string
- * depending on it's type.
- *
- * ```js
- * new Rule({ selector: 'a' }).toString() //=> "a {}"
- * ```
- *
- * @param stringifier A syntax to use in string generation.
- * @return CSS string of this node.
- */
- toString(stringifier?: Stringifier | Syntax): string
-
- /**
- * It is a wrapper for {@link Result#warn}, providing convenient
- * way of generating warnings.
- *
- * ```js
- * Declaration: {
- * bad: (decl, { result }) => {
- * decl.warn(result, 'Deprecated property: bad')
- * }
- * }
- * ```
- *
- * @param result The `Result` instance that will receive the warning.
- * @param message Description for the warning.
- * @param options Options for the warning.
- *
- * @return `Warning` instance is returned
- */
- warn(result: Result, message: string, options?: WarningOptions): Warning
-
- /**
- * If this node isn't already dirty, marks it and its ancestors as such. This
- * indicates to the LazyResult processor that the {@link Root} has been
- * modified by the current plugin and may need to be processed again by other
- * plugins.
- */
- protected markDirty(): void
-}
-
-declare class Node extends Node_ {}
-
-export = Node
diff --git a/backend/dev-console/node_modules/postcss/lib/node.js b/backend/dev-console/node_modules/postcss/lib/node.js
deleted file mode 100644
index f249c35..0000000
--- a/backend/dev-console/node_modules/postcss/lib/node.js
+++ /dev/null
@@ -1,456 +0,0 @@
-'use strict'
-
-let CssSyntaxError = require('./css-syntax-error')
-let Stringifier = require('./stringifier')
-let stringify = require('./stringify')
-let { isClean, my } = require('./symbols')
-
-function cloneNode(obj, parent) {
- let cloned = new obj.constructor()
-
- for (let i in obj) {
- if (!Object.prototype.hasOwnProperty.call(obj, i)) {
- /* c8 ignore next 2 */
- continue
- }
- if (i === 'proxyCache') continue
- let value = obj[i]
- let type = typeof value
-
- if (i === 'parent' && type === 'object') {
- if (parent) cloned[i] = parent
- } else if (i === 'source') {
- cloned[i] = value
- } else if (Array.isArray(value)) {
- cloned[i] = value.map(j => cloneNode(j, cloned))
- } else {
- if (type === 'object' && value !== null) value = cloneNode(value)
- cloned[i] = value
- }
- }
-
- return cloned
-}
-
-function sourceOffset(inputCSS, position) {
- // Not all custom syntaxes support `offset` in `source.start` and `source.end`
- if (position && typeof position.offset !== 'undefined') {
- return position.offset
- }
-
- let column = 1
- let line = 1
- let offset = 0
-
- for (let i = 0; i < inputCSS.length; i++) {
- if (line === position.line && column === position.column) {
- offset = i
- break
- }
-
- if (inputCSS[i] === '\n') {
- column = 1
- line += 1
- } else {
- column += 1
- }
- }
-
- return offset
-}
-
-class Node {
- get proxyOf() {
- return this
- }
-
- constructor(defaults = {}) {
- this.raws = {}
- this[isClean] = false
- this[my] = true
-
- for (let name in defaults) {
- if (name === 'nodes') {
- this.nodes = []
- for (let node of defaults[name]) {
- // Clone only nodes that already belong to another tree, so passing a
- // freshly created (parent-less) node adopts that instance instead of
- // a copy and keeps the caller's reference usable. See #1987.
- if (typeof node.clone === 'function' && node.parent) {
- this.append(node.clone())
- } else {
- this.append(node)
- }
- }
- } else {
- this[name] = defaults[name]
- }
- }
- }
-
- addToError(error) {
- error.postcssNode = this
- if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
- let s = this.source
- error.stack = error.stack.replace(
- /\n\s{4}at /,
- `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
- )
- }
- return error
- }
-
- after(add) {
- this.parent.insertAfter(this, add)
- return this
- }
-
- assign(overrides = {}) {
- for (let name in overrides) {
- this[name] = overrides[name]
- }
- return this
- }
-
- before(add) {
- this.parent.insertBefore(this, add)
- return this
- }
-
- cleanRaws(keepBetween) {
- delete this.raws.before
- delete this.raws.after
- if (!keepBetween) delete this.raws.between
- }
-
- clone(overrides = {}) {
- let cloned = cloneNode(this)
- for (let name in overrides) {
- cloned[name] = overrides[name]
- }
- return cloned
- }
-
- cloneAfter(overrides = {}) {
- let cloned = this.clone(overrides)
- this.parent.insertAfter(this, cloned)
- return cloned
- }
-
- cloneBefore(overrides = {}) {
- let cloned = this.clone(overrides)
- this.parent.insertBefore(this, cloned)
- return cloned
- }
-
- error(message, opts = {}) {
- if (this.source) {
- let { end, start } = this.rangeBy(opts)
- return this.source.input.error(
- message,
- { column: start.column, line: start.line },
- { column: end.column, line: end.line },
- opts
- )
- }
- return new CssSyntaxError(message)
- }
-
- getProxyProcessor() {
- return {
- get(node, prop) {
- if (prop === 'proxyOf') {
- return node
- } else if (prop === 'root') {
- return () => node.root().toProxy()
- } else {
- return node[prop]
- }
- },
-
- set(node, prop, value) {
- if (node[prop] === value) return true
- node[prop] = value
- if (
- prop === 'prop' ||
- prop === 'value' ||
- prop === 'name' ||
- prop === 'params' ||
- prop === 'important' ||
- /* c8 ignore next */
- prop === 'text'
- ) {
- node.markDirty()
- }
- return true
- }
- }
- }
-
- /* c8 ignore next 3 */
- markClean() {
- this[isClean] = true
- }
-
- markDirty() {
- if (this[isClean]) {
- this[isClean] = false
- let next = this
- while ((next = next.parent)) {
- next[isClean] = false
- }
- }
- }
-
- next() {
- if (!this.parent) return undefined
- let index = this.parent.index(this)
- return this.parent.nodes[index + 1]
- }
-
- positionBy(opts = {}) {
- let inputString =
- 'document' in this.source.input
- ? this.source.input.document
- : this.source.input.css
- let pos = {
- column: this.source.start.column,
- line: this.source.start.line,
- offset: sourceOffset(inputString, this.source.start)
- }
- if (opts.index) {
- pos = this.positionInside(opts.index)
- } else if (opts.word) {
- let stringRepresentation = inputString.slice(
- sourceOffset(inputString, this.source.start),
- sourceOffset(inputString, this.source.end)
- )
- let index = stringRepresentation.indexOf(opts.word)
- if (index !== -1) pos = this.positionInside(index)
- }
- return pos
- }
-
- positionInside(index) {
- let column = this.source.start.column
- let line = this.source.start.line
- let inputString =
- 'document' in this.source.input
- ? this.source.input.document
- : this.source.input.css
- let offset = sourceOffset(inputString, this.source.start)
- let end = offset + index
-
- for (let i = offset; i < end; i++) {
- if (inputString[i] === '\n') {
- column = 1
- line += 1
- } else {
- column += 1
- }
- }
-
- return { column, line, offset: end }
- }
-
- prev() {
- if (!this.parent) return undefined
- let index = this.parent.index(this)
- return this.parent.nodes[index - 1]
- }
-
- rangeBy(opts = {}) {
- let inputString =
- 'document' in this.source.input
- ? this.source.input.document
- : this.source.input.css
- let start = {
- column: this.source.start.column,
- line: this.source.start.line,
- offset: sourceOffset(inputString, this.source.start)
- }
- let end = this.source.end
- ? {
- column: this.source.end.column + 1,
- line: this.source.end.line,
- offset:
- typeof this.source.end.offset === 'number'
- ? // `source.end.offset` is exclusive, so we don't need to add 1
- this.source.end.offset
- : // Since line/column in this.source.end is inclusive,
- // the `sourceOffset(... , this.source.end)` returns an inclusive offset.
- // So, we add 1 to convert it to exclusive.
- sourceOffset(inputString, this.source.end) + 1
- }
- : {
- column: start.column + 1,
- line: start.line,
- offset: start.offset + 1
- }
-
- if (opts.word) {
- let stringRepresentation = inputString.slice(
- sourceOffset(inputString, this.source.start),
- sourceOffset(inputString, this.source.end)
- )
- let index = stringRepresentation.indexOf(opts.word)
- if (index !== -1) {
- start = this.positionInside(index)
- end = this.positionInside(index + opts.word.length)
- }
- } else {
- if (opts.start) {
- start = {
- column: opts.start.column,
- line: opts.start.line,
- offset: sourceOffset(inputString, opts.start)
- }
- } else if (typeof opts.index === 'number') {
- start = this.positionInside(opts.index)
- }
-
- if (opts.end) {
- end = {
- column: opts.end.column,
- line: opts.end.line,
- offset: sourceOffset(inputString, opts.end)
- }
- } else if (typeof opts.endIndex === 'number') {
- end = this.positionInside(opts.endIndex)
- } else if (typeof opts.index === 'number') {
- end = this.positionInside(opts.index + 1)
- }
- }
-
- if (
- end.line < start.line ||
- (end.line === start.line && end.column <= start.column)
- ) {
- end = {
- column: start.column + 1,
- line: start.line,
- offset: start.offset + 1
- }
- }
-
- return { end, start }
- }
-
- raw(prop, defaultType) {
- let str = new Stringifier()
- return str.raw(this, prop, defaultType)
- }
-
- remove() {
- if (this.parent) {
- this.parent.removeChild(this)
- }
- this.parent = undefined
- return this
- }
-
- replaceWith(...nodes) {
- if (this.parent) {
- let bookmark = this
- let foundSelf = false
- for (let node of nodes) {
- if (node === this) {
- foundSelf = true
- } else if (foundSelf) {
- this.parent.insertAfter(bookmark, node)
- bookmark = node
- } else {
- this.parent.insertBefore(bookmark, node)
- }
- }
-
- if (!foundSelf) {
- this.remove()
- }
- }
-
- return this
- }
-
- root() {
- let result = this
- while (result.parent && result.parent.type !== 'document') {
- result = result.parent
- }
- return result
- }
-
- toJSON(_, inputs) {
- let fixed = {}
- let emitInputs = inputs == null
- inputs = inputs || new Map()
- let inputsNextIndex = 0
-
- for (let name in this) {
- if (!Object.prototype.hasOwnProperty.call(this, name)) {
- /* c8 ignore next 2 */
- continue
- }
- if (name === 'parent' || name === 'proxyCache') continue
- let value = this[name]
-
- if (Array.isArray(value)) {
- fixed[name] = value.map(i => {
- if (typeof i === 'object' && i.toJSON) {
- return i.toJSON(null, inputs)
- } else {
- return i
- }
- })
- } else if (typeof value === 'object' && value.toJSON) {
- fixed[name] = value.toJSON(null, inputs)
- } else if (name === 'source') {
- if (value == null) continue
- let inputId = inputs.get(value.input)
- if (inputId == null) {
- inputId = inputsNextIndex
- inputs.set(value.input, inputsNextIndex)
- inputsNextIndex++
- }
- fixed[name] = {
- end: value.end,
- inputId,
- start: value.start
- }
- } else {
- fixed[name] = value
- }
- }
-
- if (emitInputs) {
- fixed.inputs = [...inputs.keys()].map(input => input.toJSON())
- }
-
- return fixed
- }
-
- toProxy() {
- if (!this.proxyCache) {
- this.proxyCache = new Proxy(this, this.getProxyProcessor())
- }
- return this.proxyCache
- }
-
- toString(stringifier = stringify) {
- if (stringifier.stringify) stringifier = stringifier.stringify
- let result = ''
- stringifier(this, i => {
- result += i
- })
- return result
- }
-
- warn(result, text, opts = {}) {
- let data = { node: this }
- for (let i in opts) data[i] = opts[i]
- return result.warn(text, data)
- }
-}
-
-module.exports = Node
-Node.default = Node
diff --git a/backend/dev-console/node_modules/postcss/lib/parse.d.ts b/backend/dev-console/node_modules/postcss/lib/parse.d.ts
deleted file mode 100644
index ffe35b4..0000000
--- a/backend/dev-console/node_modules/postcss/lib/parse.d.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { Parser } from './postcss.js'
-
-interface Parse extends Parser {
- default: Parse
-}
-
-declare let parse: Parse
-
-export = parse
diff --git a/backend/dev-console/node_modules/postcss/lib/parse.js b/backend/dev-console/node_modules/postcss/lib/parse.js
deleted file mode 100644
index 00a1037..0000000
--- a/backend/dev-console/node_modules/postcss/lib/parse.js
+++ /dev/null
@@ -1,42 +0,0 @@
-'use strict'
-
-let Container = require('./container')
-let Input = require('./input')
-let Parser = require('./parser')
-
-function parse(css, opts) {
- let input = new Input(css, opts)
- let parser = new Parser(input)
- try {
- parser.parse()
- } catch (e) {
- if (process.env.NODE_ENV !== 'production') {
- if (e.name === 'CssSyntaxError' && opts && opts.from) {
- if (/\.scss$/i.test(opts.from)) {
- e.message +=
- '\nYou tried to parse SCSS with ' +
- 'the standard CSS parser; ' +
- 'try again with the postcss-scss parser'
- } else if (/\.sass/i.test(opts.from)) {
- e.message +=
- '\nYou tried to parse Sass with ' +
- 'the standard CSS parser; ' +
- 'try again with the postcss-sass parser'
- } else if (/\.less$/i.test(opts.from)) {
- e.message +=
- '\nYou tried to parse Less with ' +
- 'the standard CSS parser; ' +
- 'try again with the postcss-less parser'
- }
- }
- }
- throw e
- }
-
- return parser.root
-}
-
-module.exports = parse
-parse.default = parse
-
-Container.registerParse(parse)
diff --git a/backend/dev-console/node_modules/postcss/lib/parser.js b/backend/dev-console/node_modules/postcss/lib/parser.js
deleted file mode 100644
index 2a16584..0000000
--- a/backend/dev-console/node_modules/postcss/lib/parser.js
+++ /dev/null
@@ -1,618 +0,0 @@
-'use strict'
-
-let AtRule = require('./at-rule')
-let Comment = require('./comment')
-let Declaration = require('./declaration')
-let Root = require('./root')
-let Rule = require('./rule')
-let tokenizer = require('./tokenize')
-
-const SAFE_COMMENT_NEIGHBOR = {
- empty: true,
- space: true
-}
-
-function findLastWithPosition(tokens) {
- for (let i = tokens.length - 1; i >= 0; i--) {
- let token = tokens[i]
- let pos = token[3] || token[2]
- if (pos) return pos
- }
-}
-
-function tokensToString(tokens, from, to) {
- let result = ''
- for (let i = from; i < to; i++) result += tokens[i][1]
- return result
-}
-
-class Parser {
- constructor(input) {
- this.input = input
-
- this.root = new Root()
- this.current = this.root
- this.spaces = ''
- this.semicolon = false
-
- this.createTokenizer()
- this.root.source = { input, start: { column: 1, line: 1, offset: 0 } }
- }
-
- atrule(token) {
- let node = new AtRule()
- node.name = token[1].slice(1)
- if (node.name === '') {
- this.unnamedAtrule(node, token)
- }
- this.init(node, token[2])
-
- let type
- let prev
- let shift
- let last = false
- let open = false
- let params = []
- let brackets = []
-
- while (!this.tokenizer.endOfFile()) {
- token = this.tokenizer.nextToken()
- type = token[0]
-
- if (type === '(' || type === '[') {
- brackets.push(type === '(' ? ')' : ']')
- } else if (type === '{' && brackets.length > 0) {
- brackets.push('}')
- } else if (type === brackets[brackets.length - 1]) {
- brackets.pop()
- }
-
- if (brackets.length === 0) {
- if (type === ';') {
- node.source.end = this.getPosition(token[2])
- node.source.end.offset++
- this.semicolon = true
- break
- } else if (type === '{') {
- open = true
- break
- } else if (type === '}') {
- if (params.length > 0) {
- shift = params.length - 1
- prev = params[shift]
- while (prev && prev[0] === 'space') {
- prev = params[--shift]
- }
- if (prev) {
- node.source.end = this.getPosition(prev[3] || prev[2])
- node.source.end.offset++
- }
- }
- this.end(token)
- break
- } else {
- params.push(token)
- }
- } else {
- params.push(token)
- }
-
- if (this.tokenizer.endOfFile()) {
- last = true
- break
- }
- }
-
- node.raws.between = this.spacesAndCommentsFromEnd(params)
- if (params.length) {
- node.raws.afterName = this.spacesAndCommentsFromStart(params)
- this.raw(node, 'params', params)
- if (last) {
- token = params[params.length - 1]
- node.source.end = this.getPosition(token[3] || token[2])
- node.source.end.offset++
- this.spaces = node.raws.between
- node.raws.between = ''
- }
- } else {
- node.raws.afterName = ''
- node.params = ''
- }
-
- if (open) {
- node.nodes = []
- this.current = node
- }
- }
-
- checkMissedSemicolon(tokens) {
- let colon = this.colon(tokens)
- if (colon === false) return
-
- let founded = 0
- let token
- for (let j = colon - 1; j >= 0; j--) {
- token = tokens[j]
- if (token[0] !== 'space') {
- founded += 1
- if (founded === 2) break
- }
- }
- // If the token is a word, e.g. `!important`, `red` or any other valid
- // property's value. Then we need to return the colon after that word
- // token. [3] is the "end" colon of that word. And because we need it
- // after that one we do +1 to get the next one.
- throw this.input.error(
- 'Missed semicolon',
- token[0] === 'word' ? token[3] + 1 : token[2]
- )
- }
-
- colon(tokens) {
- let brackets = 0
- let prev, token, type
- for (let [i, element] of tokens.entries()) {
- token = element
- type = token[0]
-
- if (type === '(') {
- brackets += 1
- }
- if (type === ')') {
- brackets -= 1
- }
- if (brackets === 0 && type === ':') {
- if (!prev) {
- this.doubleColon(token)
- } else if (prev[0] === 'word' && prev[1] === 'progid') {
- continue
- } else {
- return i
- }
- }
-
- prev = token
- }
- return false
- }
-
- comment(token) {
- let node = new Comment()
- this.init(node, token[2])
- node.source.end = this.getPosition(token[3] || token[2])
- node.source.end.offset++
-
- let text = token[1].slice(2, -2)
- if (!text.trim()) {
- node.text = ''
- node.raws.left = text
- node.raws.right = ''
- } else {
- let match = text.match(/^(\s*)([^]*\S)(\s*)$/)
- node.text = match[2]
- node.raws.left = match[1]
- node.raws.right = match[3]
- }
- }
-
- createTokenizer() {
- this.tokenizer = tokenizer(this.input)
- }
-
- decl(tokens, customProperty) {
- let node = new Declaration()
- this.init(node, tokens[0][2])
-
- let last = tokens[tokens.length - 1]
- if (last[0] === ';') {
- this.semicolon = true
- tokens.pop()
- }
-
- node.source.end = this.getPosition(
- last[3] || last[2] || findLastWithPosition(tokens)
- )
- node.source.end.offset++
-
- let start = 0
- while (tokens[start][0] !== 'word') {
- if (start === tokens.length - 1) this.unknownWord([tokens[start]])
- start++
- }
- node.raws.before += tokensToString(tokens, 0, start)
- node.source.start = this.getPosition(tokens[start][2])
-
- let propStart = start
- while (start < tokens.length) {
- let type = tokens[start][0]
- if (type === ':' || type === 'space' || type === 'comment') {
- break
- }
- start++
- }
- node.prop = tokensToString(tokens, propStart, start)
-
- let betweenStart = start
- let token
- while (start < tokens.length) {
- token = tokens[start]
- start++
- if (token[0] === ':') break
- if (token[0] === 'word' && /\w/.test(token[1])) {
- this.unknownWord([token])
- }
- }
- node.raws.between = tokensToString(tokens, betweenStart, start)
-
- if (node.prop[0] === '_' || node.prop[0] === '*') {
- node.raws.before += node.prop[0]
- node.prop = node.prop.slice(1)
- }
-
- let firstSpacesStart = start
- while (start < tokens.length) {
- let next = tokens[start][0]
- if (next !== 'space' && next !== 'comment') break
- start++
- }
- let firstSpaces = tokens.slice(firstSpacesStart, start)
-
- tokens = tokens.slice(start)
-
- this.precheckMissedSemicolon(tokens)
-
- for (let i = tokens.length - 1; i >= 0; i--) {
- token = tokens[i]
- if (token[1].toLowerCase() === '!important') {
- node.important = true
- let string = this.stringFrom(tokens, i)
- string = this.spacesFromEnd(tokens) + string
- if (string !== ' !important') node.raws.important = string
- break
- } else if (token[1].toLowerCase() === 'important') {
- let cache = tokens.slice(0)
- let str = ''
- for (let j = i; j > 0; j--) {
- let type = cache[j][0]
- if (str.trim().startsWith('!') && type !== 'space') {
- break
- }
- str = cache.pop()[1] + str
- }
- if (str.trim().startsWith('!')) {
- node.important = true
- node.raws.important = str
- tokens = cache
- }
- }
-
- if (token[0] !== 'space' && token[0] !== 'comment') {
- break
- }
- }
-
- let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment')
-
- if (hasWord) {
- node.raws.between += firstSpaces.map(i => i[1]).join('')
- firstSpaces = []
- }
- this.raw(node, 'value', firstSpaces.concat(tokens), customProperty)
-
- if (node.value.includes(':') && !customProperty) {
- this.checkMissedSemicolon(tokens)
- }
- }
-
- doubleColon(token) {
- throw this.input.error(
- 'Double colon',
- { offset: token[2] },
- { offset: token[2] + token[1].length }
- )
- }
-
- emptyRule(token) {
- let node = new Rule()
- this.init(node, token[2])
- node.selector = ''
- node.raws.between = ''
- this.current = node
- }
-
- end(token) {
- if (this.current.nodes && this.current.nodes.length) {
- this.current.raws.semicolon = this.semicolon
- }
- this.semicolon = false
-
- this.current.raws.after = (this.current.raws.after || '') + this.spaces
- this.spaces = ''
-
- if (this.current.parent) {
- this.current.source.end = this.getPosition(token[2])
- this.current.source.end.offset++
- this.current = this.current.parent
- } else {
- this.unexpectedClose(token)
- }
- }
-
- endFile() {
- if (this.current.parent) this.unclosedBlock()
- if (this.current.nodes && this.current.nodes.length) {
- this.current.raws.semicolon = this.semicolon
- }
- this.current.raws.after = (this.current.raws.after || '') + this.spaces
- this.root.source.end = this.getPosition(this.tokenizer.position())
- }
-
- freeSemicolon(token) {
- this.spaces += token[1]
- if (this.current.nodes) {
- let prev = this.current.nodes[this.current.nodes.length - 1]
- if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
- prev.raws.ownSemicolon = this.spaces
- this.spaces = ''
- prev.source.end = this.getPosition(token[2])
- prev.source.end.offset += prev.raws.ownSemicolon.length
- }
- }
- }
-
- // Helpers
-
- getPosition(offset) {
- let pos = this.input.fromOffset(offset)
- return {
- column: pos.col,
- line: pos.line,
- offset
- }
- }
-
- init(node, offset) {
- this.current.push(node)
- node.source = {
- input: this.input,
- start: this.getPosition(offset)
- }
- node.raws.before = this.spaces
- this.spaces = ''
- if (node.type !== 'comment') this.semicolon = false
- }
-
- other(start) {
- let end = false
- let type = null
- let colon = false
- let bracket = null
- let brackets = []
- let customProperty = start[1].startsWith('--')
-
- let tokens = []
- let token = start
- while (token) {
- type = token[0]
- tokens.push(token)
-
- if (type === '(' || type === '[') {
- if (!bracket) bracket = token
- brackets.push(type === '(' ? ')' : ']')
- } else if (customProperty && colon && type === '{') {
- if (!bracket) bracket = token
- brackets.push('}')
- } else if (brackets.length === 0) {
- if (type === ';') {
- if (colon) {
- this.decl(tokens, customProperty)
- return
- } else {
- break
- }
- } else if (type === '{') {
- this.rule(tokens)
- return
- } else if (type === '}') {
- this.tokenizer.back(tokens.pop())
- end = true
- break
- } else if (type === ':') {
- colon = true
- }
- } else if (type === brackets[brackets.length - 1]) {
- brackets.pop()
- if (brackets.length === 0) bracket = null
- }
-
- token = this.tokenizer.nextToken()
- }
-
- if (this.tokenizer.endOfFile()) end = true
- if (brackets.length > 0) this.unclosedBracket(bracket)
-
- if (end && colon) {
- if (!customProperty) {
- while (tokens.length) {
- token = tokens[tokens.length - 1][0]
- if (token !== 'space' && token !== 'comment') break
- this.tokenizer.back(tokens.pop())
- }
- }
- this.decl(tokens, customProperty)
- } else {
- this.unknownWord(tokens)
- }
- }
-
- parse() {
- let token
- while (!this.tokenizer.endOfFile()) {
- token = this.tokenizer.nextToken()
-
- switch (token[0]) {
- case 'space':
- this.spaces += token[1]
- break
-
- case ';':
- this.freeSemicolon(token)
- break
-
- case '}':
- this.end(token)
- break
-
- case 'comment':
- this.comment(token)
- break
-
- case 'at-word':
- this.atrule(token)
- break
-
- case '{':
- this.emptyRule(token)
- break
-
- default:
- this.other(token)
- break
- }
- }
- this.endFile()
- }
-
- precheckMissedSemicolon(/* tokens */) {
- // Hook for Safe Parser
- }
-
- raw(node, prop, tokens, customProperty) {
- let token, type
- let length = tokens.length
- let value = ''
- let clean = true
- let next, prev
-
- for (let i = 0; i < length; i += 1) {
- token = tokens[i]
- type = token[0]
- if (type === 'space' && i === length - 1 && !customProperty) {
- clean = false
- } else if (type === 'comment') {
- prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty'
- next = tokens[i + 1] ? tokens[i + 1][0] : 'empty'
- if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
- if (value.slice(-1) === ',') {
- clean = false
- } else {
- value += token[1]
- }
- } else {
- clean = false
- }
- } else {
- value += token[1]
- }
- }
- if (!clean) {
- let raw = tokens.reduce((all, i) => all + i[1], '')
- node.raws[prop] = { raw, value }
- }
- node[prop] = value
- }
-
- rule(tokens) {
- tokens.pop()
-
- let node = new Rule()
- this.init(node, tokens[0][2])
-
- node.raws.between = this.spacesAndCommentsFromEnd(tokens)
- this.raw(node, 'selector', tokens)
- this.current = node
- }
-
- spacesAndCommentsFromEnd(tokens) {
- let lastTokenType
- let spaces = ''
- while (tokens.length) {
- lastTokenType = tokens[tokens.length - 1][0]
- if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
- spaces = tokens.pop()[1] + spaces
- }
- return spaces
- }
-
- // Errors
-
- spacesAndCommentsFromStart(tokens) {
- let next
- let spaces = ''
- while (tokens.length) {
- next = tokens[0][0]
- if (next !== 'space' && next !== 'comment') break
- spaces += tokens.shift()[1]
- }
- return spaces
- }
-
- spacesFromEnd(tokens) {
- let lastTokenType
- let spaces = ''
- while (tokens.length) {
- lastTokenType = tokens[tokens.length - 1][0]
- if (lastTokenType !== 'space') break
- spaces = tokens.pop()[1] + spaces
- }
- return spaces
- }
-
- stringFrom(tokens, from) {
- let result = ''
- for (let i = from; i < tokens.length; i++) {
- result += tokens[i][1]
- }
- tokens.splice(from, tokens.length - from)
- return result
- }
-
- unclosedBlock() {
- let pos = this.current.source.start
- throw this.input.error('Unclosed block', pos.line, pos.column)
- }
-
- unclosedBracket(bracket) {
- throw this.input.error(
- 'Unclosed bracket',
- { offset: bracket[2] },
- { offset: bracket[2] + 1 }
- )
- }
-
- unexpectedClose(token) {
- throw this.input.error(
- 'Unexpected }',
- { offset: token[2] },
- { offset: token[2] + 1 }
- )
- }
-
- unknownWord(tokens) {
- throw this.input.error(
- 'Unknown word ' + tokens[0][1],
- { offset: tokens[0][2] },
- { offset: tokens[0][2] + tokens[0][1].length }
- )
- }
-
- unnamedAtrule(node, token) {
- throw this.input.error(
- 'At-rule without name',
- { offset: token[2] },
- { offset: token[2] + token[1].length }
- )
- }
-}
-
-module.exports = Parser
diff --git a/backend/dev-console/node_modules/postcss/lib/postcss.d.mts b/backend/dev-console/node_modules/postcss/lib/postcss.d.mts
deleted file mode 100644
index eaec868..0000000
--- a/backend/dev-console/node_modules/postcss/lib/postcss.d.mts
+++ /dev/null
@@ -1,66 +0,0 @@
-export {
- // Type-only exports
- AcceptedPlugin,
- AnyNode,
- atRule,
- AtRule,
- AtRuleProps,
- Builder,
- ChildNode,
- ChildProps,
- comment,
- Comment,
- CommentProps,
- Container,
- ContainerProps,
- CssSyntaxError,
- decl,
- Declaration,
- DeclarationProps,
- // postcss function / namespace
- default,
- document,
- Document,
- DocumentProps,
- FilePosition,
- fromJSON,
- Helpers,
- Input,
- JSONHydrator,
- // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here.
- type LazyResult,
- list,
- Message,
- Node,
- NodeErrorOptions,
- NodeProps,
- OldPlugin,
- parse,
- Parser,
- // @ts-expect-error This value exists, but it’s untyped.
- plugin,
- Plugin,
- PluginCreator,
- Position,
- Postcss,
- ProcessOptions,
- Processor,
- Result,
- root,
- Root,
- RootProps,
- rule,
- Rule,
- RuleProps,
- Source,
- SourceMap,
- SourceMapOptions,
- Stringifier,
- // Value exports from postcss.mjs
- stringify,
- Syntax,
- TransformCallback,
- Transformer,
- Warning,
- WarningOptions
-} from './postcss.js'
diff --git a/backend/dev-console/node_modules/postcss/lib/postcss.d.ts b/backend/dev-console/node_modules/postcss/lib/postcss.d.ts
deleted file mode 100644
index 667d820..0000000
--- a/backend/dev-console/node_modules/postcss/lib/postcss.d.ts
+++ /dev/null
@@ -1,461 +0,0 @@
-import { RawSourceMap, SourceMapGenerator } from 'source-map-js'
-
-import AtRule, { AtRuleProps } from './at-rule.js'
-import Comment, { CommentProps } from './comment.js'
-import Container, { ContainerProps, NewChild } from './container.js'
-import CssSyntaxError from './css-syntax-error.js'
-import Declaration, { DeclarationProps } from './declaration.js'
-import Document, { DocumentProps } from './document.js'
-import Input, { FilePosition } from './input.js'
-import LazyResult from './lazy-result.js'
-import list from './list.js'
-import Node, {
- AnyNode,
- ChildNode,
- ChildProps,
- NodeErrorOptions,
- NodeProps,
- Position,
- Source
-} from './node.js'
-import Processor from './processor.js'
-import Result, { Message } from './result.js'
-import Root, { RootProps } from './root.js'
-import Rule, { RuleProps } from './rule.js'
-import Warning, { WarningOptions } from './warning.js'
-
-type DocumentProcessor = (
- document: Document,
- helper: postcss.Helpers
-) => Promise | void
-type RootProcessor = (
- root: Root,
- helper: postcss.Helpers
-) => Promise | void
-type DeclarationProcessor = (
- decl: Declaration,
- helper: postcss.Helpers
-) => Promise | void
-type RuleProcessor = (
- rule: Rule,
- helper: postcss.Helpers
-) => Promise | void
-type AtRuleProcessor = (
- atRule: AtRule,
- helper: postcss.Helpers
-) => Promise | void
-type CommentProcessor = (
- comment: Comment,
- helper: postcss.Helpers
-) => Promise | void
-
-interface Processors {
- /**
- * Will be called on all`AtRule` nodes.
- *
- * Will be called again on node or children changes.
- */
- AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor
-
- /**
- * Will be called on all `AtRule` nodes, when all children will be processed.
- *
- * Will be called again on node or children changes.
- */
- AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor
-
- /**
- * Will be called on all `Comment` nodes.
- *
- * Will be called again on node or children changes.
- */
- Comment?: CommentProcessor
-
- /**
- * Will be called on all `Comment` nodes after listeners
- * for `Comment` event.
- *
- * Will be called again on node or children changes.
- */
- CommentExit?: CommentProcessor
-
- /**
- * Will be called on all `Declaration` nodes after listeners
- * for `Declaration` event.
- *
- * Will be called again on node or children changes.
- */
- Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor
-
- /**
- * Will be called on all `Declaration` nodes.
- *
- * Will be called again on node or children changes.
- */
- DeclarationExit?:
- | { [prop: string]: DeclarationProcessor }
- | DeclarationProcessor
-
- /**
- * Will be called on `Document` node.
- *
- * Will be called again on children changes.
- */
- Document?: DocumentProcessor
-
- /**
- * Will be called on `Document` node, when all children will be processed.
- *
- * Will be called again on children changes.
- */
- DocumentExit?: DocumentProcessor
-
- /**
- * Will be called on `Root` node once.
- */
- Once?: RootProcessor
-
- /**
- * Will be called on `Root` node once, when all children will be processed.
- */
- OnceExit?: RootProcessor
-
- /**
- * Will be called on `Root` node.
- *
- * Will be called again on children changes.
- */
- Root?: RootProcessor
-
- /**
- * Will be called on `Root` node, when all children will be processed.
- *
- * Will be called again on children changes.
- */
- RootExit?: RootProcessor
-
- /**
- * Will be called on all `Rule` nodes.
- *
- * Will be called again on node or children changes.
- */
- Rule?: RuleProcessor
-
- /**
- * Will be called on all `Rule` nodes, when all children will be processed.
- *
- * Will be called again on node or children changes.
- */
- RuleExit?: RuleProcessor
-}
-
-declare namespace postcss {
- export {
- AnyNode,
- AtRule,
- AtRuleProps,
- ChildNode,
- ChildProps,
- Comment,
- CommentProps,
- Container,
- ContainerProps,
- CssSyntaxError,
- Declaration,
- DeclarationProps,
- Document,
- DocumentProps,
- FilePosition,
- Input,
- LazyResult,
- list,
- Message,
- NewChild,
- Node,
- NodeErrorOptions,
- NodeProps,
- Position,
- Processor,
- Result,
- Root,
- RootProps,
- Rule,
- RuleProps,
- Source,
- Warning,
- WarningOptions
- }
-
- export type SourceMap = {
- toJSON(): RawSourceMap
- } & SourceMapGenerator
-
- export type Helpers = { postcss: Postcss; result: Result } & Postcss
-
- export interface Plugin extends Processors {
- postcssPlugin: string
- prepare?: (result: Result) => Processors
- }
-
- export interface PluginCreator {
- (opts?: PluginOptions): Plugin | Processor
- postcss: true
- }
-
- export interface Transformer extends TransformCallback {
- postcssPlugin: string
- postcssVersion: string
- }
-
- export interface TransformCallback {
- (root: Root, result: Result): Promise | void
- }
-
- export interface OldPlugin extends Transformer {
- (opts?: T): Transformer
- postcss: Transformer
- }
-
- export type AcceptedPlugin =
- | {
- postcss: Processor | TransformCallback
- }
- | OldPlugin
- | Plugin
- | PluginCreator
- | Processor
- | TransformCallback
-
- export interface Parser {
- (
- css: { toString(): string } | string,
- opts?: Pick
- ): RootNode
- }
-
- export interface Builder {
- (part: string, node?: AnyNode, type?: 'end' | 'start'): void
- }
-
- export interface Stringifier {
- (node: AnyNode, builder: Builder): void
- }
-
- export interface JSONHydrator {
- (data: object): Node
- (data: object[]): Node[]
- }
-
- export interface Syntax {
- /**
- * Function to generate AST by string.
- */
- parse?: Parser
-
- /**
- * Class to generate string by AST.
- */
- stringify?: Stringifier
- }
-
- export interface SourceMapOptions {
- /**
- * Use absolute path in generated source map.
- */
- absolute?: boolean
-
- /**
- * Indicates that PostCSS should add annotation comments to the CSS.
- * By default, PostCSS will always add a comment with a path
- * to the source map. PostCSS will not add annotations to CSS files
- * that do not contain any comments.
- *
- * By default, PostCSS presumes that you want to save the source map as
- * `opts.to + '.map'` and will use this path in the annotation comment.
- * A different path can be set by providing a string value for annotation.
- *
- * If you have set `inline: true`, annotation cannot be disabled.
- */
- annotation?: ((file: string, root: Root) => string) | boolean | string
-
- /**
- * Override `from` in map’s sources.
- */
- from?: string
-
- /**
- * Indicates that the source map should be embedded in the output CSS
- * as a Base64-encoded comment. By default, it is `true`.
- * But if all previous maps are external, not inline, PostCSS will not embed
- * the map even if you do not set this option.
- *
- * If you have an inline source map, the result.map property will be empty,
- * as the source map will be contained within the text of `result.css`.
- */
- inline?: boolean
-
- /**
- * Source map content from a previous processing step (e.g., Sass).
- *
- * PostCSS will try to read the previous source map
- * automatically (based on comments within the source CSS), but you can use
- * this option to identify it manually.
- *
- * If desired, you can omit the previous map with prev: `false`.
- */
- prev?: ((file: string) => string) | boolean | object | string
-
- /**
- * Indicates that PostCSS should set the origin content (e.g., Sass source)
- * of the source map. By default, it is true. But if all previous maps do not
- * contain sources content, PostCSS will also leave it out even if you
- * do not set this option.
- */
- sourcesContent?: boolean
- }
-
- export interface ProcessOptions {
- /**
- * Input file if it is not simple CSS file, but HTML with
-
- `;
-}
-
-const ERR_LOAD_URL = "ERR_LOAD_URL";
-const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
-const ERR_DENIED_ID = "ERR_DENIED_ID";
-const debugLoad = createDebugger("vite:load");
-const debugTransform = createDebugger("vite:transform");
-const debugCache$1 = createDebugger("vite:cache");
-function transformRequest(environment, url, options = {}) {
- if (!options.ssr) {
- options = { ...options, ssr: environment.config.consumer === "server" };
- }
- if (environment._closing && environment.config.dev.recoverable)
- throwClosedServerError();
- const cacheKey = `${options.html ? "html:" : ""}${url}`;
- const timestamp = Date.now();
- const pending = environment._pendingRequests.get(cacheKey);
- if (pending) {
- return environment.moduleGraph.getModuleByUrl(removeTimestampQuery(url)).then((module) => {
- if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
- return pending.request;
- } else {
- pending.abort();
- return transformRequest(environment, url, options);
- }
- });
- }
- const request = doTransform(environment, url, options, timestamp);
- let cleared = false;
- const clearCache = () => {
- if (!cleared) {
- environment._pendingRequests.delete(cacheKey);
- cleared = true;
- }
- };
- environment._pendingRequests.set(cacheKey, {
- request,
- timestamp,
- abort: clearCache
- });
- return request.finally(clearCache);
-}
-async function doTransform(environment, url, options, timestamp) {
- url = removeTimestampQuery(url);
- const { pluginContainer } = environment;
- let module = await environment.moduleGraph.getModuleByUrl(url);
- if (module) {
- const cached = await getCachedTransformResult(
- environment,
- url,
- module,
- timestamp
- );
- if (cached) return cached;
- }
- const resolved = module ? void 0 : await pluginContainer.resolveId(url, void 0) ?? void 0;
- const id = module?.id ?? resolved?.id ?? url;
- module ??= environment.moduleGraph.getModuleById(id);
- if (module) {
- await environment.moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
- const cached = await getCachedTransformResult(
- environment,
- url,
- module,
- timestamp
- );
- if (cached) return cached;
- }
- const result = loadAndTransform(
- environment,
- id,
- url,
- options,
- timestamp,
- module,
- resolved
- );
- const { depsOptimizer } = environment;
- if (!depsOptimizer?.isOptimizedDepFile(id)) {
- environment._registerRequestProcessing(id, () => result);
- }
- return result;
-}
-async function getCachedTransformResult(environment, url, module, timestamp) {
- const prettyUrl = debugCache$1 ? prettifyUrl(url, environment.config.root) : "";
- const softInvalidatedTransformResult = await handleModuleSoftInvalidation(
- environment,
- module,
- timestamp
- );
- if (softInvalidatedTransformResult) {
- debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
- return softInvalidatedTransformResult;
- }
- const cached = module.transformResult;
- if (cached) {
- debugCache$1?.(`[memory] ${prettyUrl}`);
- return cached;
- }
-}
-async function loadAndTransform(environment, id, url, options, timestamp, mod, resolved) {
- const { config, pluginContainer, logger } = environment;
- const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
- const moduleGraph = environment.moduleGraph;
- if (!options.skipFsCheck && id[0] !== "\0" && isServerAccessDeniedForTransform(config, id)) {
- const err = new Error(`Denied ID ${id}`);
- err.id = id;
- err.code = ERR_DENIED_ID;
- throw err;
- }
- let code = null;
- let map = null;
- const loadStart = debugLoad ? performance$1.now() : 0;
- const loadResult = await pluginContainer.load(id);
- if (loadResult == null) {
- const file = cleanUrl(id);
- if (options.html && !id.endsWith(".html")) {
- return null;
- }
- if (options.skipFsCheck || isFileLoadingAllowed(environment.getTopLevelConfig(), slash$1(file))) {
- try {
- code = await fsp.readFile(file, "utf-8");
- debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
- } catch (e) {
- if (e.code !== "ENOENT") {
- if (e.code === "EISDIR") {
- e.message = `${e.message} ${file}`;
- }
- throw e;
- }
- }
- if (code != null && environment.pluginContainer.watcher) {
- ensureWatchedFile(
- environment.pluginContainer.watcher,
- file,
- config.root
- );
- }
- }
- if (code) {
- try {
- const extracted = await extractSourcemapFromFile(code, file);
- if (extracted) {
- code = extracted.code;
- map = extracted.map;
- }
- } catch (e) {
- logger.warn(`Failed to load source map for ${file}.
-${e}`, {
- timestamp: true
- });
- }
- }
- } else {
- debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
- if (isObject$1(loadResult)) {
- code = loadResult.code;
- map = loadResult.map;
- } else {
- code = loadResult;
- }
- }
- if (code == null) {
- const isPublicFile = checkPublicFile(url, environment.getTopLevelConfig());
- let publicDirName = path$b.relative(config.root, config.publicDir);
- if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName;
- const msg = isPublicFile ? `This file is in ${publicDirName} and will be copied as-is during build without going through the plugin transforms, and therefore should not be imported from source code. It can only be referenced via HTML tags.` : `Does the file exist?`;
- const importerMod = moduleGraph.idToModuleMap.get(id)?.importers.values().next().value;
- const importer = importerMod?.file || importerMod?.url;
- const err = new Error(
- `Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`
- );
- err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
- throw err;
- }
- if (environment._closing && environment.config.dev.recoverable)
- throwClosedServerError();
- mod ??= await moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
- const transformStart = debugTransform ? performance$1.now() : 0;
- const transformResult = await pluginContainer.transform(code, id, {
- inMap: map
- });
- const originalCode = code;
- if (transformResult.code === originalCode) {
- debugTransform?.(
- timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`)
- );
- } else {
- debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
- code = transformResult.code;
- map = transformResult.map;
- }
- let normalizedMap;
- if (typeof map === "string") {
- normalizedMap = JSON.parse(map);
- } else if (map) {
- normalizedMap = map;
- } else {
- normalizedMap = null;
- }
- if (normalizedMap && "version" in normalizedMap && mod.file) {
- if (normalizedMap.mappings) {
- await injectSourcesContent(normalizedMap, mod.file, logger);
- }
- const sourcemapPath = `${mod.file}.map`;
- applySourcemapIgnoreList(
- normalizedMap,
- sourcemapPath,
- config.server.sourcemapIgnoreList,
- logger
- );
- if (path$b.isAbsolute(mod.file)) {
- let modDirname;
- for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
- const sourcePath = normalizedMap.sources[sourcesIndex];
- if (sourcePath) {
- if (path$b.isAbsolute(sourcePath)) {
- modDirname ??= path$b.dirname(mod.file);
- normalizedMap.sources[sourcesIndex] = path$b.relative(
- modDirname,
- sourcePath
- );
- }
- }
- }
- }
- }
- if (environment._closing && environment.config.dev.recoverable)
- throwClosedServerError();
- const topLevelConfig = environment.getTopLevelConfig();
- const result = environment.config.dev.moduleRunnerTransform ? await ssrTransform(code, normalizedMap, url, originalCode, {
- json: {
- stringify: topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true
- }
- }) : {
- code,
- map: normalizedMap,
- etag: getEtag(code, { weak: true })
- };
- if (timestamp > mod.lastInvalidationTimestamp)
- moduleGraph.updateModuleTransformResult(mod, result);
- return result;
-}
-async function handleModuleSoftInvalidation(environment, mod, timestamp) {
- const transformResult = mod.invalidationState;
- mod.invalidationState = void 0;
- if (!transformResult || transformResult === "HARD_INVALIDATED") return;
- if (mod.transformResult) {
- throw new Error(
- `Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`
- );
- }
- let result;
- if (transformResult.ssr) {
- result = transformResult;
- } else {
- await init;
- const source = transformResult.code;
- const s = new MagicString(source);
- const [imports] = parse$d(source, mod.id || void 0);
- for (const imp of imports) {
- let rawUrl = source.slice(imp.s, imp.e);
- if (rawUrl === "import.meta") continue;
- const hasQuotes = rawUrl[0] === '"' || rawUrl[0] === "'";
- if (hasQuotes) {
- rawUrl = rawUrl.slice(1, -1);
- }
- const urlWithoutTimestamp = removeTimestampQuery(rawUrl);
- const hmrUrl = unwrapId$1(
- stripBase(
- removeImportQuery(urlWithoutTimestamp),
- environment.config.base
- )
- );
- for (const importedMod of mod.importedModules) {
- if (importedMod.url !== hmrUrl) continue;
- if (importedMod.lastHMRTimestamp > 0) {
- const replacedUrl = injectQuery(
- urlWithoutTimestamp,
- `t=${importedMod.lastHMRTimestamp}`
- );
- const start = hasQuotes ? imp.s + 1 : imp.s;
- const end = hasQuotes ? imp.e - 1 : imp.e;
- s.overwrite(start, end, replacedUrl);
- }
- if (imp.d === -1 && environment.config.dev.preTransformRequests) {
- environment.warmupRequest(hmrUrl);
- }
- break;
- }
- }
- const code = s.toString();
- result = {
- ...transformResult,
- code,
- etag: getEtag(code, { weak: true })
- };
- }
- if (timestamp > mod.lastInvalidationTimestamp)
- environment.moduleGraph.updateModuleTransformResult(mod, result);
- return result;
-}
-
-const ALLOWED_META_NAME = [
- "msapplication-tileimage",
- "msapplication-square70x70logo",
- "msapplication-square150x150logo",
- "msapplication-wide310x150logo",
- "msapplication-square310x310logo",
- "msapplication-config",
- "twitter:image"
-];
-const ALLOWED_META_PROPERTY = [
- "og:image",
- "og:image:url",
- "og:image:secure_url",
- "og:audio",
- "og:audio:secure_url",
- "og:video",
- "og:video:secure_url"
-];
-const DEFAULT_HTML_ASSET_SOURCES = {
- audio: {
- srcAttributes: ["src"]
- },
- embed: {
- srcAttributes: ["src"]
- },
- img: {
- srcAttributes: ["src"],
- srcsetAttributes: ["srcset"]
- },
- image: {
- srcAttributes: ["href", "xlink:href"]
- },
- input: {
- srcAttributes: ["src"]
- },
- link: {
- srcAttributes: ["href"],
- srcsetAttributes: ["imagesrcset"]
- },
- object: {
- srcAttributes: ["data"]
- },
- source: {
- srcAttributes: ["src"],
- srcsetAttributes: ["srcset"]
- },
- track: {
- srcAttributes: ["src"]
- },
- use: {
- srcAttributes: ["href", "xlink:href"]
- },
- video: {
- srcAttributes: ["src", "poster"]
- },
- meta: {
- srcAttributes: ["content"],
- filter({ attributes }) {
- if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) {
- return true;
- }
- if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) {
- return true;
- }
- return false;
- }
- }
-};
-function getNodeAssetAttributes(node) {
- const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
- if (!matched) return [];
- const attributes = {};
- for (const attr of node.attrs) {
- attributes[getAttrKey(attr)] = attr.value;
- }
- if ("vite-ignore" in attributes) {
- return [
- {
- type: "remove",
- key: "vite-ignore",
- value: "",
- attributes,
- location: node.sourceCodeLocation.attrs["vite-ignore"]
- }
- ];
- }
- const actions = [];
- function handleAttributeKey(key, type) {
- const value = attributes[key];
- if (!value) return;
- if (matched.filter && !matched.filter({ key, value, attributes })) return;
- const location = node.sourceCodeLocation.attrs[key];
- actions.push({ type, key, value, attributes, location });
- }
- matched.srcAttributes?.forEach((key) => handleAttributeKey(key, "src"));
- matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset"));
- return actions;
-}
-function getAttrKey(attr) {
- return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
-}
-
-const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
-const resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
-function modulePreloadPolyfillPlugin(config) {
- let polyfillString;
- return {
- name: "vite:modulepreload-polyfill",
- resolveId: {
- handler(id) {
- if (id === modulePreloadPolyfillId) {
- return resolvedModulePreloadPolyfillId;
- }
- }
- },
- load: {
- handler(id) {
- if (id === resolvedModulePreloadPolyfillId) {
- if (config.command !== "build" || this.environment.config.consumer !== "client") {
- return "";
- }
- if (!polyfillString) {
- polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
- }
- return { code: polyfillString, moduleSideEffects: true };
- }
- }
- }
- };
-}
-function polyfill() {
- const relList = document.createElement("link").relList;
- if (relList && relList.supports && relList.supports("modulepreload")) {
- return;
- }
- for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
- processPreload(link);
- }
- new MutationObserver((mutations) => {
- for (const mutation of mutations) {
- if (mutation.type !== "childList") {
- continue;
- }
- for (const node of mutation.addedNodes) {
- if (node.tagName === "LINK" && node.rel === "modulepreload")
- processPreload(node);
- }
- }
- }).observe(document, { childList: true, subtree: true });
- function getFetchOpts(link) {
- const fetchOpts = {};
- if (link.integrity) fetchOpts.integrity = link.integrity;
- if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
- if (link.crossOrigin === "use-credentials")
- fetchOpts.credentials = "include";
- else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
- else fetchOpts.credentials = "same-origin";
- return fetchOpts;
- }
- function processPreload(link) {
- if (link.ep)
- return;
- link.ep = true;
- const fetchOpts = getFetchOpts(link);
- fetch(link.href, fetchOpts);
- }
-}
-
-const htmlProxyRE$1 = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/;
-const isHtmlProxyRE = /[?&]html-proxy\b/;
-const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
-const inlineImportRE = /(?]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
-const moduleScriptRE = /[ \t]*`
- ].join("") + result2.join("");
- return { value: html2, size: html2.length };
- });
- return { html, pageId: snapshot3.pageId, frameId: snapshot3.frameId, index: this._index };
- }
- resourceByUrl(url2, method) {
- const snapshot3 = this._snapshot;
- let sameFrameResource;
- let otherFrameResource;
- for (const resource of this._resources) {
- if (typeof resource._monotonicTime === "number" && resource._monotonicTime >= snapshot3.timestamp)
- break;
- if (resource.response.status === 304) {
- continue;
- }
- if (resource.request.url === url2 && resource.request.method === method) {
- if (resource._frameref === snapshot3.frameId)
- sameFrameResource = resource;
- else
- otherFrameResource = resource;
- }
- }
- let result2 = sameFrameResource ?? otherFrameResource;
- if (result2 && method.toUpperCase() === "GET") {
- let override = snapshot3.resourceOverrides.find((o) => o.url === url2);
- if (override?.ref) {
- const index = this._index - override.ref;
- if (index >= 0 && index < this._snapshots.length)
- override = this._snapshots[index].resourceOverrides.find((o) => o.url === url2);
- }
- if (override?.sha1) {
- result2 = {
- ...result2,
- response: {
- ...result2.response,
- content: {
- ...result2.response.content,
- _sha1: override.sha1
- }
- }
- };
- }
- }
- return result2;
- }
- };
- autoClosing = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]);
- kAllowedMetaHttpEquivs = /* @__PURE__ */ new Set(["content-type", "content-language", "default-style", "x-ua-compatible"]);
- schemas = ["about:", "blob:", "data:", "file:", "ftp:", "http:", "https:", "mailto:", "sftp:", "ws:", "wss:"];
- kLegacyBlobPrefix = "http://playwright.bloburl/#";
- urlInCSSRegex = /url\(['"]?([\w-]+:)\/\//ig;
- urlToEscapeRegex1 = /url\(\s*'([^']*)'\s*\)/ig;
- urlToEscapeRegex2 = /url\(\s*"([^"]*)"\s*\)/ig;
- blankSnapshotUrl = "data:text/html;base64," + btoa(``);
- }
-});
-
-// packages/isomorphic/lruCache.ts
-var LRUCache;
-var init_lruCache = __esm({
- "packages/isomorphic/lruCache.ts"() {
- "use strict";
- LRUCache = class {
- constructor(maxSize) {
- this._maxSize = maxSize;
- this._map = /* @__PURE__ */ new Map();
- this._size = 0;
- }
- getOrCompute(key, compute) {
- if (this._map.has(key)) {
- const result3 = this._map.get(key);
- this._map.delete(key);
- this._map.set(key, result3);
- return result3.value;
- }
- const result2 = compute();
- while (this._map.size && this._size + result2.size > this._maxSize) {
- const [firstKey, firstValue] = this._map.entries().next().value;
- this._size -= firstValue.size;
- this._map.delete(firstKey);
- }
- this._map.set(key, result2);
- this._size += result2.size;
- return result2.value;
- }
- };
- }
-});
-
-// packages/isomorphic/trace/snapshotStorage.ts
-var SnapshotStorage;
-var init_snapshotStorage = __esm({
- "packages/isomorphic/trace/snapshotStorage.ts"() {
- "use strict";
- init_snapshotRenderer();
- init_lruCache();
- SnapshotStorage = class {
- constructor() {
- this._frameSnapshots = /* @__PURE__ */ new Map();
- this._cache = new LRUCache(1e8);
- // 100MB per each trace
- this._contextToResources = /* @__PURE__ */ new Map();
- this._resourceUrlsWithOverrides = /* @__PURE__ */ new Set();
- }
- addResource(contextId4, resource) {
- resource.request.url = rewriteURLForCustomProtocol(resource.request.url);
- this._ensureResourcesForContext(contextId4).push(resource);
- }
- addFrameSnapshot(contextId4, snapshot3, screencastFrames) {
- for (const override of snapshot3.resourceOverrides)
- override.url = rewriteURLForCustomProtocol(override.url);
- let frameSnapshots = this._frameSnapshots.get(snapshot3.frameId);
- if (!frameSnapshots) {
- frameSnapshots = {
- raw: [],
- renderers: []
- };
- this._frameSnapshots.set(snapshot3.frameId, frameSnapshots);
- if (snapshot3.isMainFrame)
- this._frameSnapshots.set(snapshot3.pageId, frameSnapshots);
- }
- frameSnapshots.raw.push(snapshot3);
- const resources = this._ensureResourcesForContext(contextId4);
- const renderer = new SnapshotRenderer(this._cache, resources, frameSnapshots.raw, screencastFrames, frameSnapshots.raw.length - 1);
- frameSnapshots.renderers.push(renderer);
- return renderer;
- }
- snapshotByName(pageOrFrameId, snapshotName) {
- const snapshot3 = this._frameSnapshots.get(pageOrFrameId);
- return snapshot3?.renderers.find((r) => r.snapshotName === snapshotName);
- }
- snapshotsForTest() {
- return [...this._frameSnapshots.keys()];
- }
- finalize() {
- for (const resources of this._contextToResources.values())
- resources.sort((a, b) => (a._monotonicTime || 0) - (b._monotonicTime || 0));
- for (const frameSnapshots of this._frameSnapshots.values()) {
- for (const snapshot3 of frameSnapshots.raw) {
- for (const override of snapshot3.resourceOverrides)
- this._resourceUrlsWithOverrides.add(override.url);
- }
- }
- }
- hasResourceOverride(url2) {
- return this._resourceUrlsWithOverrides.has(url2);
- }
- _ensureResourcesForContext(contextId4) {
- let resources = this._contextToResources.get(contextId4);
- if (!resources) {
- resources = [];
- this._contextToResources.set(contextId4, resources);
- }
- return resources;
- }
- };
- }
-});
-
-// packages/isomorphic/trace/traceUtils.ts
-function parseClientSideCallMetadata(data) {
- const result2 = /* @__PURE__ */ new Map();
- const { files, stacks } = data;
- for (const s of stacks) {
- const [id, ff] = s;
- result2.set(`call@${id}`, ff.map((f) => ({ file: files[f[0]], line: f[1], column: f[2], function: f[3] })));
- }
- return result2;
-}
-function serializeClientSideCallMetadata(metadatas) {
- const fileNames = /* @__PURE__ */ new Map();
- const stacks = [];
- for (const m of metadatas) {
- if (!m.stack || !m.stack.length)
- continue;
- const stack = [];
- for (const frame of m.stack) {
- let ordinal = fileNames.get(frame.file);
- if (typeof ordinal !== "number") {
- ordinal = fileNames.size;
- fileNames.set(frame.file, ordinal);
- }
- const stackFrame = [ordinal, frame.line || 0, frame.column || 0, frame.function || ""];
- stack.push(stackFrame);
- }
- stacks.push([m.id, stack]);
- }
- return { files: [...fileNames.keys()], stacks };
-}
-var init_traceUtils = __esm({
- "packages/isomorphic/trace/traceUtils.ts"() {
- "use strict";
- }
-});
-
-// packages/isomorphic/trace/traceModernizer.ts
-var TraceVersionError, latestVersion, TraceModernizer;
-var init_traceModernizer = __esm({
- "packages/isomorphic/trace/traceModernizer.ts"() {
- "use strict";
- TraceVersionError = class extends Error {
- constructor(message) {
- super(message);
- this.name = "TraceVersionError";
- }
- };
- latestVersion = 8;
- TraceModernizer = class {
- constructor(contextEntry, snapshotStorage) {
- this._actionMap = /* @__PURE__ */ new Map();
- this._pageEntries = /* @__PURE__ */ new Map();
- this._jsHandles = /* @__PURE__ */ new Map();
- this._consoleObjects = /* @__PURE__ */ new Map();
- this._contextEntry = contextEntry;
- this._snapshotStorage = snapshotStorage;
- }
- appendTrace(trace) {
- for (const line of trace.split("\n"))
- this._appendEvent(line);
- }
- actions() {
- return [...this._actionMap.values()];
- }
- _pageEntry(pageId4) {
- let pageEntry = this._pageEntries.get(pageId4);
- if (!pageEntry) {
- pageEntry = {
- pageId: pageId4,
- screencastFrames: []
- };
- this._pageEntries.set(pageId4, pageEntry);
- this._contextEntry.pages.push(pageEntry);
- }
- return pageEntry;
- }
- _appendEvent(line) {
- if (!line)
- return;
- const events = this._modernize(JSON.parse(line));
- for (const event of events)
- this._innerAppendEvent(event);
- }
- _innerAppendEvent(event) {
- const contextEntry = this._contextEntry;
- switch (event.type) {
- case "context-options": {
- if (event.version > latestVersion)
- throw new TraceVersionError("The trace was created by a newer version of Playwright and is not supported by this version of the viewer. Please use latest Playwright to open the trace.");
- this._version = event.version;
- contextEntry.origin = event.origin;
- contextEntry.browserName = event.browserName;
- contextEntry.channel = event.channel;
- contextEntry.title = event.title;
- contextEntry.platform = event.platform;
- contextEntry.playwrightVersion = event.playwrightVersion;
- contextEntry.wallTime = event.wallTime;
- contextEntry.startTime = event.monotonicTime;
- contextEntry.sdkLanguage = event.sdkLanguage;
- contextEntry.options = event.options;
- contextEntry.testIdAttributeName = event.testIdAttributeName;
- contextEntry.contextId = event.contextId ?? "";
- contextEntry.testTimeout = event.testTimeout;
- break;
- }
- case "screencast-frame": {
- this._pageEntry(event.pageId).screencastFrames.push(event);
- break;
- }
- case "before": {
- this._actionMap.set(event.callId, { ...event, type: "action", endTime: 0, log: [] });
- break;
- }
- case "input": {
- const existing = this._actionMap.get(event.callId);
- existing.inputSnapshot = event.inputSnapshot;
- existing.point = event.point;
- break;
- }
- case "log": {
- const existing = this._actionMap.get(event.callId);
- if (!existing)
- return;
- existing.log.push({
- time: event.time,
- message: event.message
- });
- break;
- }
- case "after": {
- const existing = this._actionMap.get(event.callId);
- existing.afterSnapshot = event.afterSnapshot;
- existing.endTime = event.endTime;
- existing.result = event.result;
- existing.error = event.error;
- existing.attachments = event.attachments;
- existing.annotations = event.annotations;
- if (event.point)
- existing.point = event.point;
- break;
- }
- case "action": {
- this._actionMap.set(event.callId, { ...event, log: [] });
- break;
- }
- case "event": {
- contextEntry.events.push(event);
- break;
- }
- case "stdout": {
- contextEntry.stdio.push(event);
- break;
- }
- case "stderr": {
- contextEntry.stdio.push(event);
- break;
- }
- case "error": {
- contextEntry.errors.push(event);
- break;
- }
- case "console": {
- contextEntry.events.push(event);
- break;
- }
- case "resource-snapshot":
- this._snapshotStorage.addResource(this._contextEntry.contextId, event.snapshot);
- contextEntry.resources.push(event.snapshot);
- break;
- case "frame-snapshot":
- this._snapshotStorage.addFrameSnapshot(this._contextEntry.contextId, event.snapshot, this._pageEntry(event.snapshot.pageId).screencastFrames);
- break;
- }
- if ("pageId" in event && event.pageId)
- this._pageEntry(event.pageId);
- if (event.type === "action" || event.type === "before")
- contextEntry.startTime = Math.min(contextEntry.startTime, event.startTime);
- if (event.type === "action" || event.type === "after")
- contextEntry.endTime = Math.max(contextEntry.endTime, event.endTime);
- if (event.type === "event") {
- contextEntry.startTime = Math.min(contextEntry.startTime, event.time);
- contextEntry.endTime = Math.max(contextEntry.endTime, event.time);
- }
- if (event.type === "screencast-frame") {
- contextEntry.startTime = Math.min(contextEntry.startTime, event.timestamp);
- contextEntry.endTime = Math.max(contextEntry.endTime, event.timestamp);
- }
- }
- _processedContextCreatedEvent() {
- return this._version !== void 0;
- }
- _modernize(event) {
- let version3 = this._version ?? event.version ?? 6;
- let events = [event];
- for (; version3 < latestVersion; ++version3)
- events = this[`_modernize_${version3}_to_${version3 + 1}`].call(this, events);
- return events;
- }
- _modernize_0_to_1(events) {
- for (const event of events) {
- if (event.type !== "action")
- continue;
- if (typeof event.metadata.error === "string")
- event.metadata.error = { error: { name: "Error", message: event.metadata.error } };
- }
- return events;
- }
- _modernize_1_to_2(events) {
- for (const event of events) {
- if (event.type !== "frame-snapshot" || !event.snapshot.isMainFrame)
- continue;
- event.snapshot.viewport = this._contextEntry.options?.viewport || { width: 1280, height: 720 };
- }
- return events;
- }
- _modernize_2_to_3(events) {
- for (const event of events) {
- if (event.type !== "resource-snapshot" || event.snapshot.request)
- continue;
- const resource = event.snapshot;
- event.snapshot = {
- _frameref: resource.frameId,
- request: {
- url: resource.url,
- method: resource.method,
- headers: resource.requestHeaders,
- postData: resource.requestSha1 ? { _sha1: resource.requestSha1 } : void 0
- },
- response: {
- status: resource.status,
- headers: resource.responseHeaders,
- content: {
- mimeType: resource.contentType,
- _sha1: resource.responseSha1
- }
- },
- _monotonicTime: resource.timestamp
- };
- }
- return events;
- }
- _modernize_3_to_4(events) {
- const result2 = [];
- for (const event of events) {
- const e = this._modernize_event_3_to_4(event);
- if (e)
- result2.push(e);
- }
- return result2;
- }
- _modernize_event_3_to_4(event) {
- if (event.type !== "action" && event.type !== "event") {
- return event;
- }
- const metadata = event.metadata;
- if (metadata.internal || metadata.method.startsWith("tracing"))
- return null;
- if (event.type === "event") {
- if (metadata.method === "__create__" && metadata.type === "ConsoleMessage") {
- return {
- type: "object",
- class: metadata.type,
- guid: metadata.params.guid,
- initializer: metadata.params.initializer
- };
- }
- return {
- type: "event",
- time: metadata.startTime,
- class: metadata.type,
- method: metadata.method,
- params: metadata.params,
- pageId: metadata.pageId
- };
- }
- return {
- type: "action",
- callId: metadata.id,
- startTime: metadata.startTime,
- endTime: metadata.endTime,
- apiName: metadata.apiName || metadata.type + "." + metadata.method,
- class: metadata.type,
- method: metadata.method,
- params: metadata.params,
- // eslint-disable-next-line no-restricted-globals
- wallTime: metadata.wallTime || Date.now(),
- log: metadata.log,
- beforeSnapshot: metadata.snapshots.find((s) => s.title === "before")?.snapshotName,
- inputSnapshot: metadata.snapshots.find((s) => s.title === "input")?.snapshotName,
- afterSnapshot: metadata.snapshots.find((s) => s.title === "after")?.snapshotName,
- error: metadata.error?.error,
- result: metadata.result,
- point: metadata.point,
- pageId: metadata.pageId
- };
- }
- _modernize_4_to_5(events) {
- const result2 = [];
- for (const event of events) {
- const e = this._modernize_event_4_to_5(event);
- if (e)
- result2.push(e);
- }
- return result2;
- }
- _modernize_event_4_to_5(event) {
- if (event.type === "event" && event.method === "__create__" && event.class === "JSHandle")
- this._jsHandles.set(event.params.guid, event.params.initializer);
- if (event.type === "object") {
- if (event.class !== "ConsoleMessage")
- return null;
- const args = event.initializer.args?.map((arg) => {
- if (arg.guid) {
- const handle = this._jsHandles.get(arg.guid);
- return { preview: handle?.preview || "", value: "" };
- }
- return { preview: arg.preview || "", value: arg.value || "" };
- });
- this._consoleObjects.set(event.guid, {
- type: event.initializer.type,
- text: event.initializer.text,
- location: event.initializer.location,
- args
- });
- return null;
- }
- if (event.type === "event" && event.method === "console") {
- const consoleMessage = this._consoleObjects.get(event.params.message?.guid || "");
- if (!consoleMessage)
- return null;
- return {
- type: "console",
- time: event.time,
- pageId: event.pageId,
- messageType: consoleMessage.type,
- text: consoleMessage.text,
- args: consoleMessage.args,
- location: consoleMessage.location
- };
- }
- return event;
- }
- _modernize_5_to_6(events) {
- const result2 = [];
- for (const event of events) {
- result2.push(event);
- if (event.type !== "after" || !event.log.length)
- continue;
- for (const log2 of event.log) {
- result2.push({
- type: "log",
- callId: event.callId,
- message: log2,
- time: -1
- });
- }
- }
- return result2;
- }
- _modernize_6_to_7(events) {
- const result2 = [];
- if (!this._processedContextCreatedEvent() && events[0].type !== "context-options") {
- const event = {
- type: "context-options",
- origin: "testRunner",
- version: 6,
- browserName: "",
- options: {},
- platform: "unknown",
- wallTime: 0,
- monotonicTime: 0,
- sdkLanguage: "javascript",
- contextId: ""
- };
- result2.push(event);
- }
- for (const event of events) {
- if (event.type === "context-options") {
- result2.push({ ...event, monotonicTime: 0, origin: "library", contextId: "" });
- continue;
- }
- if (event.type === "before" || event.type === "action") {
- if (!this._contextEntry.wallTime)
- this._contextEntry.wallTime = event.wallTime;
- const eventAsV6 = event;
- const eventAsV7 = event;
- eventAsV7.stepId = `${eventAsV6.apiName}@${eventAsV6.wallTime}`;
- result2.push(eventAsV7);
- } else {
- result2.push(event);
- }
- }
- return result2;
- }
- _modernize_7_to_8(events) {
- const result2 = [];
- for (const event of events) {
- if (event.type === "before" || event.type === "action") {
- const eventAsV7 = event;
- const eventAsV8 = event;
- if (eventAsV7.apiName) {
- eventAsV8.title = eventAsV7.apiName;
- delete eventAsV8.apiName;
- }
- eventAsV8.stepId = eventAsV7.stepId ?? eventAsV7.callId;
- result2.push(eventAsV8);
- } else {
- result2.push(event);
- }
- }
- return result2;
- }
- };
- }
-});
-
-// packages/isomorphic/trace/traceLoader.ts
-function stripEncodingFromContentType(contentType) {
- const charset = contentType.match(/^(.*);\s*charset=.*$/);
- if (charset)
- return charset[1];
- return contentType;
-}
-function createEmptyContext() {
- return {
- origin: "testRunner",
- startTime: Number.MAX_SAFE_INTEGER,
- wallTime: Number.MAX_SAFE_INTEGER,
- endTime: 0,
- browserName: "",
- options: {
- deviceScaleFactor: 1,
- isMobile: false,
- viewport: { width: 1280, height: 800 }
- },
- pages: [],
- resources: [],
- actions: [],
- events: [],
- errors: [],
- stdio: [],
- hasSource: false,
- contextId: ""
- };
-}
-var TraceLoader;
-var init_traceLoader = __esm({
- "packages/isomorphic/trace/traceLoader.ts"() {
- "use strict";
- init_traceUtils();
- init_snapshotStorage();
- init_traceModernizer();
- TraceLoader = class {
- constructor() {
- this.contextEntries = [];
- this._resourceToContentType = /* @__PURE__ */ new Map();
- }
- async load(backend, traceFile, unzipProgress) {
- this._backend = backend;
- const prefix = traceFile?.match(/(.+)\.trace$/)?.[1];
- const prefixes = [];
- let hasSource = false;
- for (const entryName of await this._backend.entryNames()) {
- const match = entryName.match(/(.+)\.trace$/);
- if (match && (!prefix || prefix === match[1]))
- prefixes.push(match[1] || "");
- if (entryName.includes("src@"))
- hasSource = true;
- }
- if (!prefixes.length)
- throw new Error("Cannot find .trace file");
- this._snapshotStorage = new SnapshotStorage();
- const total = prefixes.length * 3;
- let done = 0;
- for (const prefix2 of prefixes) {
- const contextEntry = createEmptyContext();
- contextEntry.hasSource = hasSource;
- const modernizer = new TraceModernizer(contextEntry, this._snapshotStorage);
- const trace = await this._backend.readText(prefix2 + ".trace") || "";
- modernizer.appendTrace(trace);
- unzipProgress?.(++done, total);
- const network = await this._backend.readText(prefix2 + ".network") || "";
- modernizer.appendTrace(network);
- unzipProgress?.(++done, total);
- contextEntry.actions = modernizer.actions().sort((a1, a2) => a1.startTime - a2.startTime);
- if (!backend.isLive()) {
- for (const action of contextEntry.actions.slice().reverse()) {
- if (!action.endTime && !action.error) {
- for (const a of contextEntry.actions) {
- if (a.parentId === action.callId && action.endTime < a.endTime)
- action.endTime = a.endTime;
- }
- }
- }
- }
- const stacks = await this._backend.readText(prefix2 + ".stacks");
- if (stacks) {
- const callMetadata = parseClientSideCallMetadata(JSON.parse(stacks));
- for (const action of contextEntry.actions)
- action.stack = action.stack || callMetadata.get(action.callId);
- }
- unzipProgress?.(++done, total);
- for (const resource of contextEntry.resources) {
- if (resource.request.postData?._sha1)
- this._resourceToContentType.set(resource.request.postData._sha1, stripEncodingFromContentType(resource.request.postData.mimeType));
- if (resource.response.content?._sha1)
- this._resourceToContentType.set(resource.response.content._sha1, stripEncodingFromContentType(resource.response.content.mimeType));
- }
- this.contextEntries.push(contextEntry);
- }
- this._snapshotStorage.finalize();
- }
- async hasEntry(filename) {
- return this._backend.hasEntry(filename);
- }
- async resourceForSha1(sha1) {
- const blob = await this._backend.readBlob("resources/" + sha1);
- const contentType = this._resourceToContentType.get(sha1);
- if (!blob || contentType === void 0 || contentType === "x-unknown")
- return blob;
- return new Blob([blob], { type: contentType });
- }
- storage() {
- return this._snapshotStorage;
- }
- };
- }
-});
-
-// packages/isomorphic/trace/traceModel.ts
-function indexModel(context2) {
- for (const page of context2.pages)
- page[contextSymbol] = context2;
- for (let i = 0; i < context2.actions.length; ++i) {
- const action = context2.actions[i];
- action[contextSymbol] = context2;
- }
- let lastNonRouteAction = void 0;
- for (let i = context2.actions.length - 1; i >= 0; i--) {
- const action = context2.actions[i];
- action[nextInContextSymbol] = lastNonRouteAction;
- if (action.class !== "Route")
- lastNonRouteAction = action;
- }
- for (const event of context2.events)
- event[contextSymbol] = context2;
- for (const resource of context2.resources)
- resource[contextSymbol] = context2;
-}
-function mergeActionsAndUpdateTiming(contexts) {
- const result2 = [];
- const actions = mergeActionsAndUpdateTimingSameTrace(contexts);
- result2.push(...actions);
- result2.sort((a1, a2) => {
- if (a2.parentId === a1.callId)
- return 1;
- if (a1.parentId === a2.callId)
- return -1;
- return a1.endTime - a2.endTime;
- });
- for (let i = 1; i < result2.length; ++i)
- result2[i][prevByEndTimeSymbol] = result2[i - 1];
- result2.sort((a1, a2) => {
- if (a2.parentId === a1.callId)
- return -1;
- if (a1.parentId === a2.callId)
- return 1;
- return a1.startTime - a2.startTime;
- });
- for (let i = 0; i + 1 < result2.length; ++i)
- result2[i][nextByStartTimeSymbol] = result2[i + 1];
- return result2;
-}
-function mergeActionsAndUpdateTimingSameTrace(contexts) {
- const map = /* @__PURE__ */ new Map();
- const libraryContexts = contexts.filter((context2) => context2.origin === "library");
- const testRunnerContexts = contexts.filter((context2) => context2.origin === "testRunner");
- if (!testRunnerContexts.length || !libraryContexts.length) {
- return contexts.map((context2) => {
- return context2.actions.map((action) => ({ ...action, context: context2 }));
- }).flat();
- }
- for (const context2 of libraryContexts) {
- for (const action of context2.actions) {
- map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action, context: context2 });
- }
- }
- const delta = monotonicTimeDeltaBetweenLibraryAndRunner(testRunnerContexts, map);
- if (delta)
- adjustMonotonicTime(libraryContexts, delta);
- const nonPrimaryIdToPrimaryId = /* @__PURE__ */ new Map();
- for (const context2 of testRunnerContexts) {
- for (const action of context2.actions) {
- const existing = action.stepId && map.get(action.stepId);
- if (existing) {
- nonPrimaryIdToPrimaryId.set(action.callId, existing.callId);
- if (action.error)
- existing.error = action.error;
- if (action.attachments)
- existing.attachments = action.attachments;
- if (action.annotations)
- existing.annotations = action.annotations;
- if (action.parentId)
- existing.parentId = nonPrimaryIdToPrimaryId.get(action.parentId) ?? action.parentId;
- if (action.group)
- existing.group = action.group;
- existing.startTime = action.startTime;
- existing.endTime = action.endTime;
- continue;
- }
- if (action.parentId)
- action.parentId = nonPrimaryIdToPrimaryId.get(action.parentId) ?? action.parentId;
- map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action, context: context2 });
- }
- }
- return [...map.values()];
-}
-function adjustMonotonicTime(contexts, monotonicTimeDelta) {
- for (const context2 of contexts) {
- context2.startTime += monotonicTimeDelta;
- context2.endTime += monotonicTimeDelta;
- for (const action of context2.actions) {
- if (action.startTime)
- action.startTime += monotonicTimeDelta;
- if (action.endTime)
- action.endTime += monotonicTimeDelta;
- }
- for (const event of context2.events)
- event.time += monotonicTimeDelta;
- for (const event of context2.stdio)
- event.timestamp += monotonicTimeDelta;
- for (const page of context2.pages) {
- for (const frame of page.screencastFrames)
- frame.timestamp += monotonicTimeDelta;
- }
- for (const resource of context2.resources) {
- if (resource._monotonicTime)
- resource._monotonicTime += monotonicTimeDelta;
- }
- }
-}
-function monotonicTimeDeltaBetweenLibraryAndRunner(nonPrimaryContexts, libraryActions) {
- for (const context2 of nonPrimaryContexts) {
- for (const action of context2.actions) {
- if (!action.startTime)
- continue;
- const libraryAction = action.stepId ? libraryActions.get(action.stepId) : void 0;
- if (libraryAction)
- return action.startTime - libraryAction.startTime;
- }
- }
- return 0;
-}
-function buildActionTree(actions) {
- const itemMap = /* @__PURE__ */ new Map();
- for (const action of actions) {
- itemMap.set(action.callId, {
- id: action.callId,
- parent: void 0,
- children: [],
- action
- });
- }
- const rootItem = { action: { ...kFakeRootAction }, id: "", parent: void 0, children: [] };
- for (const item of itemMap.values()) {
- rootItem.action.startTime = Math.min(rootItem.action.startTime, item.action.startTime);
- rootItem.action.endTime = Math.max(rootItem.action.endTime, item.action.endTime);
- const parent = item.action.parentId ? itemMap.get(item.action.parentId) || rootItem : rootItem;
- parent.children.push(item);
- item.parent = parent;
- }
- const inheritStack = (item) => {
- for (const child of item.children) {
- child.action.stack = child.action.stack ?? item.action.stack;
- inheritStack(child);
- }
- };
- inheritStack(rootItem);
- return { rootItem, itemMap };
-}
-function context(action) {
- return action[contextSymbol];
-}
-function nextInContext(action) {
- return action[nextInContextSymbol];
-}
-function previousActionByEndTime(action) {
- return action[prevByEndTimeSymbol];
-}
-function nextActionByStartTime(action) {
- return action[nextByStartTimeSymbol];
-}
-function stats(action) {
- let errors = 0;
- let warnings = 0;
- for (const event of eventsForAction(action)) {
- if (event.type === "console") {
- const type3 = event.messageType;
- if (type3 === "warning")
- ++warnings;
- else if (type3 === "error")
- ++errors;
- }
- if (event.type === "event" && event.method === "pageError")
- ++errors;
- }
- return { errors, warnings };
-}
-function eventsForAction(action) {
- let result2 = action[eventsSymbol];
- if (result2)
- return result2;
- const nextAction = nextInContext(action);
- result2 = context(action).events.filter((event) => {
- return event.time >= action.startTime && (!nextAction || event.time < nextAction.startTime);
- });
- action[eventsSymbol] = result2;
- return result2;
-}
-function collectSources(actions, errorDescriptors) {
- const result2 = /* @__PURE__ */ new Map();
- for (const action of actions) {
- for (const frame of action.stack || []) {
- let source11 = result2.get(frame.file);
- if (!source11) {
- source11 = { errors: [], content: void 0 };
- result2.set(frame.file, source11);
- }
- }
- }
- for (const error of errorDescriptors) {
- const { action, stack, message } = error;
- if (!action || !stack)
- continue;
- result2.get(stack[0].file)?.errors.push({
- line: stack[0].line || 0,
- message
- });
- }
- return result2;
-}
-var contextSymbol, nextInContextSymbol, prevByEndTimeSymbol, nextByStartTimeSymbol, eventsSymbol, TraceModel, lastTmpStepId, kFakeRootAction;
-var init_traceModel = __esm({
- "packages/isomorphic/trace/traceModel.ts"() {
- "use strict";
- init_protocolFormatter();
- contextSymbol = Symbol("context");
- nextInContextSymbol = Symbol("nextInContext");
- prevByEndTimeSymbol = Symbol("prevByEndTime");
- nextByStartTimeSymbol = Symbol("nextByStartTime");
- eventsSymbol = Symbol("events");
- TraceModel = class {
- constructor(traceUri, contexts) {
- contexts.forEach((contextEntry) => indexModel(contextEntry));
- const libraryContext = contexts.find((context2) => context2.origin === "library");
- this.traceUri = traceUri;
- this.browserName = libraryContext?.browserName || "";
- this.sdkLanguage = libraryContext?.sdkLanguage;
- this.channel = libraryContext?.channel;
- this.testIdAttributeName = libraryContext?.testIdAttributeName;
- this.platform = libraryContext?.platform || "";
- this.playwrightVersion = contexts.find((c) => c.playwrightVersion)?.playwrightVersion;
- this.title = libraryContext?.title || "";
- this.options = libraryContext?.options || {};
- this.testTimeout = contexts.find((c) => c.origin === "testRunner")?.testTimeout;
- this.actions = mergeActionsAndUpdateTiming(contexts);
- this.pages = [].concat(...contexts.map((c) => c.pages));
- this.wallTime = contexts.map((c) => c.wallTime).reduce((prev, cur) => Math.min(prev || Number.MAX_VALUE, cur), Number.MAX_VALUE);
- this.startTime = contexts.map((c) => c.startTime).reduce((prev, cur) => Math.min(prev, cur), Number.MAX_VALUE);
- this.endTime = contexts.map((c) => c.endTime).reduce((prev, cur) => Math.max(prev, cur), Number.MIN_VALUE);
- this.events = [].concat(...contexts.map((c) => c.events));
- this.stdio = [].concat(...contexts.map((c) => c.stdio));
- this.errors = [].concat(...contexts.map((c) => c.errors));
- this.hasSource = contexts.some((c) => c.hasSource);
- this.hasStepData = contexts.some((context2) => context2.origin === "testRunner");
- this.resources = [...contexts.map((c) => c.resources)].flat().map((entry) => ({ ...entry, id: `${entry.pageref}-${entry.startedDateTime}-${entry.request.url}` }));
- this.attachments = this.actions.flatMap((action) => action.attachments?.map((attachment) => ({ ...attachment, callId: action.callId, traceUri })) ?? []);
- this.visibleAttachments = this.attachments.filter((attachment) => !attachment.name.startsWith("_"));
- this.events.sort((a1, a2) => a1.time - a2.time);
- this.resources.sort((a1, a2) => a1._monotonicTime - a2._monotonicTime);
- this.errorDescriptors = this.hasStepData ? this._errorDescriptorsFromTestRunner() : this._errorDescriptorsFromActions();
- this.sources = collectSources(this.actions, this.errorDescriptors);
- this.actionCounters = /* @__PURE__ */ new Map();
- for (const action of this.actions) {
- action.group = action.group ?? getActionGroup({ type: action.class, method: action.method });
- if (action.group)
- this.actionCounters.set(action.group, 1 + (this.actionCounters.get(action.group) || 0));
- }
- }
- createRelativeUrl(path59) {
- const url2 = new URL("http://localhost/" + path59);
- url2.searchParams.set("trace", this.traceUri);
- return url2.toString().substring("http://localhost/".length);
- }
- failedAction() {
- return this.actions.findLast((a) => a.error);
- }
- filteredActions(actionsFilter) {
- const filter = new Set(actionsFilter);
- return this.actions.filter((action) => !action.group || filter.has(action.group));
- }
- renderActionTree(filter) {
- const actions = this.filteredActions(filter ?? []);
- const { rootItem } = buildActionTree(actions);
- const actionTree = [];
- const visit = (actionItem, indent) => {
- const title = renderTitleForCall({ ...actionItem.action, type: actionItem.action.class });
- actionTree.push(`${indent}${title || actionItem.id}`);
- for (const child of actionItem.children)
- visit(child, indent + " ");
- };
- rootItem.children.forEach((a) => visit(a, ""));
- return actionTree;
- }
- _errorDescriptorsFromActions() {
- const errors = [];
- for (const action of this.actions || []) {
- if (!action.error?.message)
- continue;
- errors.push({
- action,
- stack: action.stack,
- message: action.error.message
- });
- }
- return errors;
- }
- _errorDescriptorsFromTestRunner() {
- return this.errors.filter((e) => !!e.message).map((error, i) => ({
- stack: error.stack,
- message: error.message
- }));
- }
- };
- lastTmpStepId = 0;
- kFakeRootAction = {
- type: "action",
- callId: "",
- startTime: 0,
- endTime: 0,
- class: "",
- method: "",
- params: {},
- log: [],
- context: {
- origin: "library",
- startTime: 0,
- endTime: 0,
- browserName: "",
- wallTime: 0,
- options: {},
- pages: [],
- resources: [],
- actions: [],
- events: [],
- stdio: [],
- errors: [],
- hasSource: false,
- contextId: ""
- }
- };
- }
-});
-
-// packages/isomorphic/yaml.ts
-function yamlEscapeKeyIfNeeded(str) {
- if (!yamlStringNeedsQuotes(str))
- return str;
- return `'` + str.replace(/'/g, `''`) + `'`;
-}
-function yamlEscapeValueIfNeeded(str) {
- if (!yamlStringNeedsQuotes(str))
- return str;
- return '"' + str.replace(/[\\"\x00-\x1f\x7f-\x9f]/g, (c) => {
- switch (c) {
- case "\\":
- return "\\\\";
- case '"':
- return '\\"';
- case "\b":
- return "\\b";
- case "\f":
- return "\\f";
- case "\n":
- return "\\n";
- case "\r":
- return "\\r";
- case " ":
- return "\\t";
- default:
- const code = c.charCodeAt(0);
- return "\\x" + code.toString(16).padStart(2, "0");
- }
- }) + '"';
-}
-function yamlStringNeedsQuotes(str) {
- if (str.length === 0)
- return true;
- if (/^\s|\s$/.test(str))
- return true;
- if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/.test(str))
- return true;
- if (/^-/.test(str))
- return true;
- if (/[\n:](\s|$)/.test(str))
- return true;
- if (/\s#/.test(str))
- return true;
- if (/[\n\r]/.test(str))
- return true;
- if (/^[&*\],?!>|@"'#%]/.test(str))
- return true;
- if (/[{}`]/.test(str))
- return true;
- if (/^\[/.test(str))
- return true;
- if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null"].includes(str.toLowerCase()))
- return true;
- return false;
-}
-var init_yaml = __esm({
- "packages/isomorphic/yaml.ts"() {
- "use strict";
- }
-});
-
-// packages/isomorphic/index.ts
-var isomorphic_exports = {};
-__export(isomorphic_exports, {
- CSharpLocatorFactory: () => CSharpLocatorFactory,
- DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT: () => DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT,
- DEFAULT_PLAYWRIGHT_TIMEOUT: () => DEFAULT_PLAYWRIGHT_TIMEOUT,
- InvalidSelectorError: () => InvalidSelectorError,
- JavaLocatorFactory: () => JavaLocatorFactory,
- JavaScriptLocatorFactory: () => JavaScriptLocatorFactory,
- JsonlLocatorFactory: () => JsonlLocatorFactory,
- KeyParser: () => KeyParser,
- LongStandingScope: () => LongStandingScope,
- ManualPromise: () => ManualPromise,
- MultiMap: () => MultiMap,
- ParserError: () => ParserError,
- PythonLocatorFactory: () => PythonLocatorFactory,
- Semaphore: () => Semaphore,
- SnapshotServer: () => SnapshotServer,
- SnapshotStorage: () => SnapshotStorage,
- TraceLoader: () => TraceLoader,
- TraceModel: () => TraceModel,
- ansiRegex: () => ansiRegex,
- ariaNodesEqual: () => ariaNodesEqual,
- asLocator: () => asLocator,
- asLocatorDescription: () => asLocatorDescription,
- asLocators: () => asLocators,
- assert: () => assert,
- base64ByteLength: () => base64ByteLength,
- buildActionTree: () => buildActionTree,
- bytesToString: () => bytesToString,
- cacheNormalizedWhitespaces: () => cacheNormalizedWhitespaces,
- captureRawStack: () => captureRawStack,
- constructURLBasedOnBaseURL: () => constructURLBasedOnBaseURL,
- context: () => context,
- customCSSNames: () => customCSSNames,
- deserializeURLMatch: () => deserializeURLMatch,
- escapeForAttributeSelector: () => escapeForAttributeSelector,
- escapeForTextSelector: () => escapeForTextSelector,
- escapeHTML: () => escapeHTML,
- escapeHTMLAttribute: () => escapeHTMLAttribute,
- escapeRegExp: () => escapeRegExp,
- escapeTemplateString: () => escapeTemplateString,
- escapeWithQuotes: () => escapeWithQuotes,
- eventsForAction: () => eventsForAction,
- findNewNode: () => findNewNode,
- formatObject: () => formatObject,
- formatObjectOrVoid: () => formatObjectOrVoid,
- formatProtocolParam: () => formatProtocolParam,
- getActionGroup: () => getActionGroup,
- getExtensionForMimeType: () => getExtensionForMimeType,
- getMetainfo: () => getMetainfo,
- getMimeTypeForPath: () => getMimeTypeForPath,
- globToRegexPattern: () => globToRegexPattern,
- hasPointerCursor: () => hasPointerCursor,
- headersArrayToObject: () => headersArrayToObject,
- headersObjectToArray: () => headersObjectToArray,
- isError: () => isError,
- isHttpUrl: () => isHttpUrl,
- isInvalidSelectorError: () => isInvalidSelectorError,
- isJsonMimeType: () => isJsonMimeType,
- isObject: () => isObject,
- isRegExp: () => isRegExp,
- isRegexString: () => isRegexString,
- isString: () => isString,
- isTextualMimeType: () => isTextualMimeType,
- isURLPattern: () => isURLPattern,
- isXmlMimeType: () => isXmlMimeType,
- locatorCustomDescription: () => locatorCustomDescription,
- locatorOrSelectorAsSelector: () => locatorOrSelectorAsSelector,
- longestCommonSubstring: () => longestCommonSubstring,
- methodMetainfo: () => methodMetainfo,
- monotonicTime: () => monotonicTime,
- msToString: () => msToString,
- nextActionByStartTime: () => nextActionByStartTime,
- noColors: () => noColors,
- normalizeEscapedRegexQuotes: () => normalizeEscapedRegexQuotes,
- normalizeWhiteSpace: () => normalizeWhiteSpace,
- padImageToSize: () => padImageToSize,
- parseAriaSnapshot: () => parseAriaSnapshot,
- parseAriaSnapshotUnsafe: () => parseAriaSnapshotUnsafe,
- parseAttributeSelector: () => parseAttributeSelector,
- parseCSS: () => parseCSS,
- parseClientSideCallMetadata: () => parseClientSideCallMetadata,
- parseErrorStack: () => parseErrorStack,
- parseRegex: () => parseRegex,
- parseSelector: () => parseSelector,
- parseStackFrame: () => parseStackFrame,
- pollAgainstDeadline: () => pollAgainstDeadline,
- previousActionByEndTime: () => previousActionByEndTime,
- quoteCSSAttributeValue: () => quoteCSSAttributeValue,
- raceAgainstDeadline: () => raceAgainstDeadline,
- renderTitleForCall: () => renderTitleForCall,
- resolveGlobToRegexPattern: () => resolveGlobToRegexPattern,
- rewriteErrorMessage: () => rewriteErrorMessage,
- scaleImageToSize: () => scaleImageToSize,
- serializeClientSideCallMetadata: () => serializeClientSideCallMetadata,
- serializeExpectedTextValues: () => serializeExpectedTextValues,
- serializeSelector: () => serializeSelector,
- serializeURLMatch: () => serializeURLMatch,
- serializeURLPattern: () => serializeURLPattern,
- setTimeOrigin: () => setTimeOrigin,
- signalToPromise: () => signalToPromise,
- splitErrorMessage: () => splitErrorMessage,
- splitSelectorByFrame: () => splitSelectorByFrame,
- stats: () => stats,
- stringifySelector: () => stringifySelector,
- stringifyStackFrames: () => stringifyStackFrames,
- stripAnsiEscapes: () => stripAnsiEscapes,
- textValue: () => textValue,
- timeOrigin: () => timeOrigin,
- toSnakeCase: () => toSnakeCase,
- toTitleCase: () => toTitleCase,
- tomlArray: () => tomlArray,
- tomlBasicString: () => tomlBasicString,
- tomlMultilineBasicString: () => tomlMultilineBasicString,
- trimString: () => trimString,
- trimStringWithEllipsis: () => trimStringWithEllipsis,
- unsafeLocatorOrSelectorAsSelector: () => unsafeLocatorOrSelectorAsSelector,
- urlMatches: () => urlMatches,
- urlMatchesEqual: () => urlMatchesEqual,
- validate: () => validate,
- visitAllSelectorParts: () => visitAllSelectorParts,
- webColors: () => webColors,
- yamlEscapeKeyIfNeeded: () => yamlEscapeKeyIfNeeded,
- yamlEscapeValueIfNeeded: () => yamlEscapeValueIfNeeded
-});
-var init_isomorphic = __esm({
- "packages/isomorphic/index.ts"() {
- "use strict";
- init_ariaSnapshot();
- init_expectUtils();
- init_assert();
- init_base64();
- init_colors();
- init_headers();
- init_imageUtils();
- init_jsonSchema();
- init_locatorGenerators();
- init_manualPromise();
- init_mimeType();
- init_multimap();
- init_protocolFormatter();
- init_protocolMetainfo();
- init_rtti();
- init_semaphore();
- init_stackTrace();
- init_stringUtils();
- init_formatUtils();
- init_time();
- init_timeoutRunner();
- init_snapshotServer();
- init_urlMatch();
- init_cssParser();
- init_locatorParser();
- init_selectorParser();
- init_snapshotStorage();
- init_traceLoader();
- init_traceModel();
- init_traceUtils();
- init_yaml();
- }
-});
-
-// packages/utils/ascii.ts
-function wrapInASCIIBox(text2, padding = 0) {
- const lines = text2.split("\n");
- const maxLength = Math.max(...lines.map((line) => line.length));
- return [
- "\u2554" + "\u2550".repeat(maxLength + padding * 2) + "\u2557",
- ...lines.map((line) => "\u2551" + " ".repeat(padding) + line + " ".repeat(maxLength - line.length + padding) + "\u2551"),
- "\u255A" + "\u2550".repeat(maxLength + padding * 2) + "\u255D"
- ].join("\n");
-}
-function jsonStringifyForceASCII(object) {
- return JSON.stringify(object).replace(
- /[\u007f-\uffff]/g,
- (c) => "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4)
- );
-}
-var init_ascii = __esm({
- "packages/utils/ascii.ts"() {
- "use strict";
- }
-});
-
-// packages/utils/chromiumChannels.ts
-function defaultUserDataDirForChannel(channel) {
- return channelToDefaultUserDataDir.get(channel)?.[process.platform];
-}
-function isChromiumChannelName(channel) {
- return channelToDefaultUserDataDir.has(channel);
-}
-var import_os, import_path, channelToDefaultUserDataDir;
-var init_chromiumChannels = __esm({
- "packages/utils/chromiumChannels.ts"() {
- "use strict";
- import_os = __toESM(require("os"));
- import_path = __toESM(require("path"));
- channelToDefaultUserDataDir = /* @__PURE__ */ new Map([
- ["chrome", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome", "User Data")
- }],
- ["chrome-beta", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-beta"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Beta"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Beta", "User Data")
- }],
- ["chrome-dev", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-unstable"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Dev"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Dev", "User Data")
- }],
- ["chrome-canary", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "google-chrome-canary"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Canary"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome SxS", "User Data")
- }],
- ["msedge", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge", "User Data")
- }],
- ["msedge-beta", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-beta"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Beta"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Beta", "User Data")
- }],
- ["msedge-dev", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-dev"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Dev"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Dev", "User Data")
- }],
- ["msedge-canary", {
- "linux": import_path.default.join(import_os.default.homedir(), ".config", "microsoft-edge-canary"),
- "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Canary"),
- "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge SxS", "User Data")
- }]
- ]);
- }
-});
-
-// packages/utils/third_party/pixelmatch.js
-var require_pixelmatch = __commonJS({
- "packages/utils/third_party/pixelmatch.js"(exports2, module2) {
- "use strict";
- module2.exports = pixelmatch2;
- var defaultOptions = {
- threshold: 0.1,
- // matching threshold (0 to 1); smaller is more sensitive
- includeAA: false,
- // whether to skip anti-aliasing detection
- alpha: 0.1,
- // opacity of original image in diff output
- aaColor: [255, 255, 0],
- // color of anti-aliased pixels in diff output
- diffColor: [255, 0, 0],
- // color of different pixels in diff output
- diffColorAlt: null,
- // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two
- diffMask: false
- // draw the diff over a transparent background (a mask)
- };
- function pixelmatch2(img1, img2, output, width, height, options) {
- if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output))
- throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");
- if (img1.length !== img2.length || output && output.length !== img1.length)
- throw new Error("Image sizes do not match.");
- if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height.");
- options = Object.assign({}, defaultOptions, options);
- const len = width * height;
- const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len);
- const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len);
- let identical = true;
- for (let i = 0; i < len; i++) {
- if (a32[i] !== b32[i]) {
- identical = false;
- break;
- }
- }
- if (identical) {
- if (output && !options.diffMask) {
- for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output);
- }
- return 0;
- }
- const maxDelta = 35215 * options.threshold * options.threshold;
- let diff2 = 0;
- for (let y = 0; y < height; y++) {
- for (let x = 0; x < width; x++) {
- const pos = (y * width + x) * 4;
- const delta = colorDelta(img1, img2, pos, pos);
- if (Math.abs(delta) > maxDelta) {
- if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) {
- if (output && !options.diffMask) drawPixel2(output, pos, ...options.aaColor);
- } else {
- if (output) {
- drawPixel2(output, pos, ...delta < 0 && options.diffColorAlt || options.diffColor);
- }
- diff2++;
- }
- } else if (output) {
- if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output);
- }
- }
- }
- return diff2;
- }
- function isPixelData(arr) {
- return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1;
- }
- function antialiased(img, x1, y1, width, height, img2) {
- const x0 = Math.max(x1 - 1, 0);
- const y0 = Math.max(y1 - 1, 0);
- const x2 = Math.min(x1 + 1, width - 1);
- const y2 = Math.min(y1 + 1, height - 1);
- const pos = (y1 * width + x1) * 4;
- let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
- let min = 0;
- let max = 0;
- let minX, minY, maxX, maxY;
- for (let x = x0; x <= x2; x++) {
- for (let y = y0; y <= y2; y++) {
- if (x === x1 && y === y1) continue;
- const delta = colorDelta(img, img, pos, (y * width + x) * 4, true);
- if (delta === 0) {
- zeroes++;
- if (zeroes > 2) return false;
- } else if (delta < min) {
- min = delta;
- minX = x;
- minY = y;
- } else if (delta > max) {
- max = delta;
- maxX = x;
- maxY = y;
- }
- }
- }
- if (min === 0 || max === 0) return false;
- return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height);
- }
- function hasManySiblings(img, x1, y1, width, height) {
- const x0 = Math.max(x1 - 1, 0);
- const y0 = Math.max(y1 - 1, 0);
- const x2 = Math.min(x1 + 1, width - 1);
- const y2 = Math.min(y1 + 1, height - 1);
- const pos = (y1 * width + x1) * 4;
- let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
- for (let x = x0; x <= x2; x++) {
- for (let y = y0; y <= y2; y++) {
- if (x === x1 && y === y1) continue;
- const pos2 = (y * width + x) * 4;
- if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++;
- if (zeroes > 2) return true;
- }
- }
- return false;
- }
- function colorDelta(img1, img2, k, m, yOnly) {
- let r1 = img1[k + 0];
- let g1 = img1[k + 1];
- let b1 = img1[k + 2];
- let a1 = img1[k + 3];
- let r2 = img2[m + 0];
- let g2 = img2[m + 1];
- let b2 = img2[m + 2];
- let a2 = img2[m + 3];
- if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0;
- if (a1 < 255) {
- a1 /= 255;
- r1 = blend(r1, a1);
- g1 = blend(g1, a1);
- b1 = blend(b1, a1);
- }
- if (a2 < 255) {
- a2 /= 255;
- r2 = blend(r2, a2);
- g2 = blend(g2, a2);
- b2 = blend(b2, a2);
- }
- const y1 = rgb2y(r1, g1, b1);
- const y2 = rgb2y(r2, g2, b2);
- const y = y1 - y2;
- if (yOnly) return y;
- const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2);
- const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);
- const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
- return y1 > y2 ? -delta : delta;
- }
- function rgb2y(r, g, b) {
- return r * 0.29889531 + g * 0.58662247 + b * 0.11448223;
- }
- function rgb2i(r, g, b) {
- return r * 0.59597799 - g * 0.2741761 - b * 0.32180189;
- }
- function rgb2q(r, g, b) {
- return r * 0.21147017 - g * 0.52261711 + b * 0.31114694;
- }
- function blend(c, a) {
- return 255 + (c - 255) * a;
- }
- function drawPixel2(output, pos, r, g, b) {
- output[pos + 0] = r;
- output[pos + 1] = g;
- output[pos + 2] = b;
- output[pos + 3] = 255;
- }
- function drawGrayPixel(img, i, alpha, output) {
- const r = img[i + 0];
- const g = img[i + 1];
- const b = img[i + 2];
- const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255);
- drawPixel2(output, i, val, val, val);
- }
- }
-});
-
-// packages/utils/image_tools/colorUtils.ts
-function blendWithWhite(c, a) {
- return 255 + (c - 255) * a;
-}
-function rgb2gray(r, g, b) {
- return 77 * r + 150 * g + 29 * b + 128 >> 8;
-}
-function colorDeltaE94(rgb1, rgb2) {
- const [l1, a1, b1] = xyz2lab(srgb2xyz(rgb1));
- const [l2, a2, b2] = xyz2lab(srgb2xyz(rgb2));
- const deltaL = l1 - l2;
- const deltaA = a1 - a2;
- const deltaB = b1 - b2;
- const c1 = Math.sqrt(a1 ** 2 + b1 ** 2);
- const c2 = Math.sqrt(a2 ** 2 + b2 ** 2);
- const deltaC = c1 - c2;
- let deltaH = deltaA ** 2 + deltaB ** 2 - deltaC ** 2;
- deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH);
- const k1 = 0.045;
- const k2 = 0.015;
- const kL = 1;
- const kC = 1;
- const kH = 1;
- const sC = 1 + k1 * c1;
- const sH = 1 + k2 * c1;
- const sL = 1;
- return Math.sqrt((deltaL / sL / kL) ** 2 + (deltaC / sC / kC) ** 2 + (deltaH / sH / kH) ** 2);
-}
-function srgb2xyz(rgb) {
- let r = rgb[0] / 255;
- let g = rgb[1] / 255;
- let b = rgb[2] / 255;
- r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
- g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
- b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
- return [
- r * 0.4124 + g * 0.3576 + b * 0.1805,
- r * 0.2126 + g * 0.7152 + b * 0.0722,
- r * 0.0193 + g * 0.1192 + b * 0.9505
- ];
-}
-function xyz2lab(xyz) {
- const x = xyz[0] / 0.950489;
- const y = xyz[1];
- const z31 = xyz[2] / 1.08884;
- const fx = x > sigma_pow3 ? x ** (1 / 3) : x / 3 / sigma_pow2 + 4 / 29;
- const fy = y > sigma_pow3 ? y ** (1 / 3) : y / 3 / sigma_pow2 + 4 / 29;
- const fz = z31 > sigma_pow3 ? z31 ** (1 / 3) : z31 / 3 / sigma_pow2 + 4 / 29;
- const l = 116 * fy - 16;
- const a = 500 * (fx - fy);
- const b = 200 * (fy - fz);
- return [l, a, b];
-}
-var sigma_pow2, sigma_pow3;
-var init_colorUtils = __esm({
- "packages/utils/image_tools/colorUtils.ts"() {
- "use strict";
- sigma_pow2 = 6 * 6 / 29 / 29;
- sigma_pow3 = 6 * 6 * 6 / 29 / 29 / 29;
- }
-});
-
-// packages/utils/image_tools/imageChannel.ts
-var ImageChannel;
-var init_imageChannel = __esm({
- "packages/utils/image_tools/imageChannel.ts"() {
- "use strict";
- init_colorUtils();
- ImageChannel = class _ImageChannel {
- static intoRGB(width, height, data, options = {}) {
- const {
- paddingSize = 0,
- paddingColorOdd = [255, 0, 255],
- paddingColorEven = [0, 255, 0]
- } = options;
- const newWidth = width + 2 * paddingSize;
- const newHeight = height + 2 * paddingSize;
- const r = new Uint8Array(newWidth * newHeight);
- const g = new Uint8Array(newWidth * newHeight);
- const b = new Uint8Array(newWidth * newHeight);
- for (let y = 0; y < newHeight; ++y) {
- for (let x = 0; x < newWidth; ++x) {
- const index = y * newWidth + x;
- if (y >= paddingSize && y < newHeight - paddingSize && x >= paddingSize && x < newWidth - paddingSize) {
- const offset = ((y - paddingSize) * width + (x - paddingSize)) * 4;
- const alpha = data[offset + 3] === 255 ? 1 : data[offset + 3] / 255;
- r[index] = blendWithWhite(data[offset], alpha);
- g[index] = blendWithWhite(data[offset + 1], alpha);
- b[index] = blendWithWhite(data[offset + 2], alpha);
- } else {
- const color = (y + x) % 2 === 0 ? paddingColorEven : paddingColorOdd;
- r[index] = color[0];
- g[index] = color[1];
- b[index] = color[2];
- }
- }
- }
- return [
- new _ImageChannel(newWidth, newHeight, r),
- new _ImageChannel(newWidth, newHeight, g),
- new _ImageChannel(newWidth, newHeight, b)
- ];
- }
- constructor(width, height, data) {
- this.data = data;
- this.width = width;
- this.height = height;
- }
- get(x, y) {
- return this.data[y * this.width + x];
- }
- boundXY(x, y) {
- return [
- Math.min(Math.max(x, 0), this.width - 1),
- Math.min(Math.max(y, 0), this.height - 1)
- ];
- }
- };
- }
-});
-
-// packages/utils/image_tools/stats.ts
-function ssim(stats2, x1, y1, x2, y2) {
- const mean1 = stats2.meanC1(x1, y1, x2, y2);
- const mean2 = stats2.meanC2(x1, y1, x2, y2);
- const var1 = stats2.varianceC1(x1, y1, x2, y2);
- const var2 = stats2.varianceC2(x1, y1, x2, y2);
- const cov = stats2.covariance(x1, y1, x2, y2);
- const c1 = (0.01 * DYNAMIC_RANGE) ** 2;
- const c2 = (0.03 * DYNAMIC_RANGE) ** 2;
- return (2 * mean1 * mean2 + c1) * (2 * cov + c2) / (mean1 ** 2 + mean2 ** 2 + c1) / (var1 + var2 + c2);
-}
-var DYNAMIC_RANGE, FastStats;
-var init_stats = __esm({
- "packages/utils/image_tools/stats.ts"() {
- "use strict";
- DYNAMIC_RANGE = 2 ** 8 - 1;
- FastStats = class {
- constructor(c1, c2) {
- this.c1 = c1;
- this.c2 = c2;
- const { width, height } = c1;
- this._partialSumC1 = new Array(width * height);
- this._partialSumC2 = new Array(width * height);
- this._partialSumSq1 = new Array(width * height);
- this._partialSumSq2 = new Array(width * height);
- this._partialSumMult = new Array(width * height);
- const recalc = (mx, idx, initial, x, y) => {
- mx[idx] = initial;
- if (y > 0)
- mx[idx] += mx[(y - 1) * width + x];
- if (x > 0)
- mx[idx] += mx[y * width + x - 1];
- if (x > 0 && y > 0)
- mx[idx] -= mx[(y - 1) * width + x - 1];
- };
- for (let y = 0; y < height; ++y) {
- for (let x = 0; x < width; ++x) {
- const idx = y * width + x;
- recalc(this._partialSumC1, idx, this.c1.data[idx], x, y);
- recalc(this._partialSumC2, idx, this.c2.data[idx], x, y);
- recalc(this._partialSumSq1, idx, this.c1.data[idx] * this.c1.data[idx], x, y);
- recalc(this._partialSumSq2, idx, this.c2.data[idx] * this.c2.data[idx], x, y);
- recalc(this._partialSumMult, idx, this.c1.data[idx] * this.c2.data[idx], x, y);
- }
- }
- }
- _sum(partialSum, x1, y1, x2, y2) {
- const width = this.c1.width;
- let result2 = partialSum[y2 * width + x2];
- if (y1 > 0)
- result2 -= partialSum[(y1 - 1) * width + x2];
- if (x1 > 0)
- result2 -= partialSum[y2 * width + x1 - 1];
- if (x1 > 0 && y1 > 0)
- result2 += partialSum[(y1 - 1) * width + x1 - 1];
- return result2;
- }
- meanC1(x1, y1, x2, y2) {
- const N = (y2 - y1 + 1) * (x2 - x1 + 1);
- return this._sum(this._partialSumC1, x1, y1, x2, y2) / N;
- }
- meanC2(x1, y1, x2, y2) {
- const N = (y2 - y1 + 1) * (x2 - x1 + 1);
- return this._sum(this._partialSumC2, x1, y1, x2, y2) / N;
- }
- varianceC1(x1, y1, x2, y2) {
- const N = (y2 - y1 + 1) * (x2 - x1 + 1);
- return (this._sum(this._partialSumSq1, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) ** 2 / N) / N;
- }
- varianceC2(x1, y1, x2, y2) {
- const N = (y2 - y1 + 1) * (x2 - x1 + 1);
- return (this._sum(this._partialSumSq2, x1, y1, x2, y2) - this._sum(this._partialSumC2, x1, y1, x2, y2) ** 2 / N) / N;
- }
- covariance(x1, y1, x2, y2) {
- const N = (y2 - y1 + 1) * (x2 - x1 + 1);
- return (this._sum(this._partialSumMult, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) * this._sum(this._partialSumC2, x1, y1, x2, y2) / N) / N;
- }
- };
- }
-});
-
-// packages/utils/image_tools/compare.ts
-function drawPixel(width, data, x, y, r, g, b) {
- const idx = (y * width + x) * 4;
- data[idx + 0] = r;
- data[idx + 1] = g;
- data[idx + 2] = b;
- data[idx + 3] = 255;
-}
-function compare(actual, expected, diff2, width, height, options = {}) {
- const {
- maxColorDeltaE94 = 1
- } = options;
- const paddingSize = Math.max(VARIANCE_WINDOW_RADIUS, SSIM_WINDOW_RADIUS);
- const paddingColorEven = [255, 0, 255];
- const paddingColorOdd = [0, 255, 0];
- const [r1, g1, b1] = ImageChannel.intoRGB(width, height, expected, {
- paddingSize,
- paddingColorEven,
- paddingColorOdd
- });
- const [r2, g2, b2] = ImageChannel.intoRGB(width, height, actual, {
- paddingSize,
- paddingColorEven,
- paddingColorOdd
- });
- const noop = (x, y) => {
- };
- const drawRedPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 0, 0) : noop;
- const drawYellowPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 255, 0) : noop;
- const drawGrayPixel = diff2 ? (x, y) => {
- const gray = rgb2gray(r1.get(x, y), g1.get(x, y), b1.get(x, y));
- const value2 = blendWithWhite(gray, 0.1);
- drawPixel(width, diff2, x - paddingSize, y - paddingSize, value2, value2, value2);
- } : noop;
- let fastR;
- let fastG;
- let fastB;
- let diffCount = 0;
- for (let y = paddingSize; y < r1.height - paddingSize; ++y) {
- for (let x = paddingSize; x < r1.width - paddingSize; ++x) {
- if (r1.get(x, y) === r2.get(x, y) && g1.get(x, y) === g2.get(x, y) && b1.get(x, y) === b2.get(x, y)) {
- drawGrayPixel(x, y);
- continue;
- }
- const delta = colorDeltaE94(
- [r1.get(x, y), g1.get(x, y), b1.get(x, y)],
- [r2.get(x, y), g2.get(x, y), b2.get(x, y)]
- );
- if (delta <= maxColorDeltaE94) {
- drawGrayPixel(x, y);
- continue;
- }
- if (!fastR || !fastG || !fastB) {
- fastR = new FastStats(r1, r2);
- fastG = new FastStats(g1, g2);
- fastB = new FastStats(b1, b2);
- }
- const [varX1, varY1] = r1.boundXY(x - VARIANCE_WINDOW_RADIUS, y - VARIANCE_WINDOW_RADIUS);
- const [varX2, varY2] = r1.boundXY(x + VARIANCE_WINDOW_RADIUS, y + VARIANCE_WINDOW_RADIUS);
- const var1 = fastR.varianceC1(varX1, varY1, varX2, varY2) + fastG.varianceC1(varX1, varY1, varX2, varY2) + fastB.varianceC1(varX1, varY1, varX2, varY2);
- const var2 = fastR.varianceC2(varX1, varY1, varX2, varY2) + fastG.varianceC2(varX1, varY1, varX2, varY2) + fastB.varianceC2(varX1, varY1, varX2, varY2);
- if (var1 === 0 || var2 === 0) {
- drawRedPixel(x, y);
- ++diffCount;
- continue;
- }
- const [ssimX1, ssimY1] = r1.boundXY(x - SSIM_WINDOW_RADIUS, y - SSIM_WINDOW_RADIUS);
- const [ssimX2, ssimY2] = r1.boundXY(x + SSIM_WINDOW_RADIUS, y + SSIM_WINDOW_RADIUS);
- const ssimRGB = (ssim(fastR, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastG, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastB, ssimX1, ssimY1, ssimX2, ssimY2)) / 3;
- const isAntialiased = ssimRGB >= 0.99;
- if (isAntialiased) {
- drawYellowPixel(x, y);
- } else {
- drawRedPixel(x, y);
- ++diffCount;
- }
- }
- }
- return diffCount;
-}
-var SSIM_WINDOW_RADIUS, VARIANCE_WINDOW_RADIUS;
-var init_compare = __esm({
- "packages/utils/image_tools/compare.ts"() {
- "use strict";
- init_colorUtils();
- init_imageChannel();
- init_stats();
- SSIM_WINDOW_RADIUS = 15;
- VARIANCE_WINDOW_RADIUS = 1;
- }
-});
-
-// packages/utils/comparators.ts
-function getComparator(mimeType) {
- if (mimeType === "image/png")
- return compareImages.bind(null, "image/png");
- if (mimeType === "image/jpeg")
- return compareImages.bind(null, "image/jpeg");
- if (mimeType === "text/plain")
- return compareText;
- return compareBuffersOrStrings;
-}
-function compareBuffersOrStrings(actualBuffer, expectedBuffer) {
- if (typeof actualBuffer === "string")
- return compareText(actualBuffer, expectedBuffer);
- if (!actualBuffer || !(actualBuffer instanceof Buffer))
- return { errorMessage: "Actual result should be a Buffer or a string." };
- if (Buffer.compare(actualBuffer, expectedBuffer))
- return { errorMessage: "Buffers differ" };
- return null;
-}
-function compareImages(mimeType, actualBuffer, expectedBuffer, options = {}) {
- if (!actualBuffer || !(actualBuffer instanceof Buffer))
- return { errorMessage: "Actual result should be a Buffer." };
- validateBuffer(expectedBuffer, mimeType);
- let actual = mimeType === "image/png" ? PNG.sync.read(actualBuffer) : jpegjs.decode(actualBuffer, { maxMemoryUsageInMB: JPEG_JS_MAX_BUFFER_SIZE_IN_MB });
- let expected = mimeType === "image/png" ? PNG.sync.read(expectedBuffer) : jpegjs.decode(expectedBuffer, { maxMemoryUsageInMB: JPEG_JS_MAX_BUFFER_SIZE_IN_MB });
- const size = { width: Math.max(expected.width, actual.width), height: Math.max(expected.height, actual.height) };
- let sizesMismatchError = "";
- if (expected.width !== actual.width || expected.height !== actual.height) {
- sizesMismatchError = `Expected an image ${expected.width}px by ${expected.height}px, received ${actual.width}px by ${actual.height}px. `;
- actual = padImageToSize(actual, size);
- expected = padImageToSize(expected, size);
- }
- const diff2 = new PNG({ width: size.width, height: size.height });
- let count;
- if (options.comparator === "ssim-cie94") {
- count = compare(expected.data, actual.data, diff2.data, size.width, size.height, {
- // All ΔE* formulae are originally designed to have the difference of 1.0 stand for a "just noticeable difference" (JND).
- // See https://en.wikipedia.org/wiki/Color_difference#CIELAB_%CE%94E*
- maxColorDeltaE94: 1
- });
- } else if ((options.comparator ?? "pixelmatch") === "pixelmatch") {
- count = (0, import_pixelmatch.default)(expected.data, actual.data, diff2.data, size.width, size.height, {
- threshold: options.threshold ?? 0.2
- });
- } else {
- throw new Error(`Configuration specifies unknown comparator "${options.comparator}"`);
- }
- const maxDiffPixels1 = options.maxDiffPixels;
- const maxDiffPixels2 = options.maxDiffPixelRatio !== void 0 ? expected.width * expected.height * options.maxDiffPixelRatio : void 0;
- let maxDiffPixels;
- if (maxDiffPixels1 !== void 0 && maxDiffPixels2 !== void 0)
- maxDiffPixels = Math.min(maxDiffPixels1, maxDiffPixels2);
- else
- maxDiffPixels = maxDiffPixels1 ?? maxDiffPixels2 ?? 0;
- const ratio = Math.ceil(count / (expected.width * expected.height) * 100) / 100;
- const pixelsMismatchError = count > maxDiffPixels ? `${count} pixels (ratio ${ratio.toFixed(2)} of all image pixels) are different.` : "";
- if (pixelsMismatchError || sizesMismatchError)
- return { errorMessage: sizesMismatchError + pixelsMismatchError, diff: PNG.sync.write(diff2) };
- return null;
-}
-function validateBuffer(buffer, mimeType) {
- if (mimeType === "image/png") {
- const pngMagicNumber = [137, 80, 78, 71, 13, 10, 26, 10];
- if (buffer.length < pngMagicNumber.length || !pngMagicNumber.every((byte, index) => buffer[index] === byte))
- throw new Error("Could not decode expected image as PNG.");
- } else if (mimeType === "image/jpeg") {
- const jpegMagicNumber = [255, 216];
- if (buffer.length < jpegMagicNumber.length || !jpegMagicNumber.every((byte, index) => buffer[index] === byte))
- throw new Error("Could not decode expected image as JPEG.");
- }
-}
-function compareText(actual, expectedBuffer) {
- if (typeof actual !== "string")
- return { errorMessage: "Actual result should be a string" };
- let expected = expectedBuffer.toString("utf-8");
- if (expected === actual)
- return null;
- if (!actual.endsWith("\n"))
- actual += "\n";
- if (!expected.endsWith("\n"))
- expected += "\n";
- const lines = diff.createPatch("file", expected, actual, void 0, void 0, { context: 5 }).split("\n");
- const coloredLines = lines.slice(4).map((line) => {
- if (line.startsWith("-"))
- return colors.green(line);
- if (line.startsWith("+"))
- return colors.red(line);
- if (line.startsWith("@@"))
- return colors.dim(line);
- return line;
- });
- const errorMessage = coloredLines.join("\n");
- return { errorMessage };
-}
-var import_pixelmatch, jpegjs, colors, diff, PNG, JPEG_JS_MAX_BUFFER_SIZE_IN_MB;
-var init_comparators = __esm({
- "packages/utils/comparators.ts"() {
- "use strict";
- init_imageUtils();
- import_pixelmatch = __toESM(require_pixelmatch());
- init_compare();
- jpegjs = require("./utilsBundle").jpegjs;
- colors = require("./utilsBundle").colors;
- diff = require("./utilsBundle").diff;
- ({ PNG } = require("./utilsBundle"));
- JPEG_JS_MAX_BUFFER_SIZE_IN_MB = 5 * 1024;
- }
-});
-
-// packages/utils/crypto.ts
-function createGuid() {
- return import_crypto.default.randomBytes(16).toString("hex");
-}
-function calculateSha1(buffer) {
- const hash = import_crypto.default.createHash("sha1");
- hash.update(buffer);
- return hash.digest("hex");
-}
-function encodeBase128(value2) {
- const bytes = [];
- do {
- let byte = value2 & 127;
- value2 >>>= 7;
- if (bytes.length > 0)
- byte |= 128;
- bytes.push(byte);
- } while (value2 > 0);
- return Buffer.from(bytes.reverse());
-}
-function generateSelfSignedCertificate() {
- const { privateKey, publicKey } = import_crypto.default.generateKeyPairSync("rsa", { modulusLength: 2048 });
- const publicKeyDer = publicKey.export({ type: "pkcs1", format: "der" });
- const oneYearInMilliseconds = 365 * 24 * 60 * 60 * 1e3;
- const notBefore = new Date((/* @__PURE__ */ new Date()).getTime() - oneYearInMilliseconds);
- const notAfter = new Date((/* @__PURE__ */ new Date()).getTime() + oneYearInMilliseconds);
- const tbsCertificate = DER.encodeSequence([
- DER.encodeExplicitContextDependent(0, DER.encodeInteger(1)),
- // version
- DER.encodeInteger(1),
- // serialNumber
- DER.encodeSequence([
- DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"),
- // sha256WithRSAEncryption PKCS #1
- DER.encodeNull()
- ]),
- // signature
- DER.encodeSequence([
- DER.encodeSet([
- DER.encodeSequence([
- DER.encodeObjectIdentifier("2.5.4.3"),
- // commonName X.520 DN component
- DER.encodePrintableString("localhost")
- ])
- ]),
- DER.encodeSet([
- DER.encodeSequence([
- DER.encodeObjectIdentifier("2.5.4.10"),
- // organizationName X.520 DN component
- DER.encodePrintableString("Playwright Client Certificate Support")
- ])
- ])
- ]),
- // issuer
- DER.encodeSequence([
- DER.encodeDate(notBefore),
- // notBefore
- DER.encodeDate(notAfter)
- // notAfter
- ]),
- // validity
- DER.encodeSequence([
- DER.encodeSet([
- DER.encodeSequence([
- DER.encodeObjectIdentifier("2.5.4.3"),
- // commonName X.520 DN component
- DER.encodePrintableString("localhost")
- ])
- ]),
- DER.encodeSet([
- DER.encodeSequence([
- DER.encodeObjectIdentifier("2.5.4.10"),
- // organizationName X.520 DN component
- DER.encodePrintableString("Playwright Client Certificate Support")
- ])
- ])
- ]),
- // subject
- DER.encodeSequence([
- DER.encodeSequence([
- DER.encodeObjectIdentifier("1.2.840.113549.1.1.1"),
- // rsaEncryption PKCS #1
- DER.encodeNull()
- ]),
- DER.encodeBitString(publicKeyDer)
- ])
- // SubjectPublicKeyInfo
- ]);
- const signature = import_crypto.default.sign("sha256", tbsCertificate, privateKey);
- const certificate = DER.encodeSequence([
- tbsCertificate,
- DER.encodeSequence([
- DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"),
- // sha256WithRSAEncryption PKCS #1
- DER.encodeNull()
- ]),
- DER.encodeBitString(signature)
- ]);
- const certPem = [
- "-----BEGIN CERTIFICATE-----",
- // Split the base64 string into lines of 64 characters
- certificate.toString("base64").match(/.{1,64}/g).join("\n"),
- "-----END CERTIFICATE-----"
- ].join("\n");
- return {
- cert: certPem,
- key: privateKey.export({ type: "pkcs1", format: "pem" })
- };
-}
-var import_crypto, DER;
-var init_crypto = __esm({
- "packages/utils/crypto.ts"() {
- "use strict";
- import_crypto = __toESM(require("crypto"));
- init_assert();
- DER = class {
- static encodeSequence(data) {
- return this._encode(48, Buffer.concat(data));
- }
- static encodeInteger(data) {
- assert(data >= -128 && data <= 127);
- return this._encode(2, Buffer.from([data]));
- }
- static encodeObjectIdentifier(oid) {
- const parts = oid.split(".").map((v) => Number(v));
- const output = [encodeBase128(40 * parts[0] + parts[1])];
- for (let i = 2; i < parts.length; i++)
- output.push(encodeBase128(parts[i]));
- return this._encode(6, Buffer.concat(output));
- }
- static encodeNull() {
- return Buffer.from([5, 0]);
- }
- static encodeSet(data) {
- assert(data.length === 1, "Only one item in the set is supported. We'd need to sort the data to support more.");
- return this._encode(49, Buffer.concat(data));
- }
- static encodeExplicitContextDependent(tag, data) {
- return this._encode(160 + tag, data);
- }
- static encodePrintableString(data) {
- return this._encode(19, Buffer.from(data));
- }
- static encodeBitString(data) {
- const unusedBits = 0;
- const content = Buffer.concat([Buffer.from([unusedBits]), data]);
- return this._encode(3, content);
- }
- static encodeDate(date) {
- const year = date.getUTCFullYear();
- const isGeneralizedTime = year >= 2050;
- const parts = [
- isGeneralizedTime ? year.toString() : year.toString().slice(-2),
- (date.getUTCMonth() + 1).toString().padStart(2, "0"),
- date.getUTCDate().toString().padStart(2, "0"),
- date.getUTCHours().toString().padStart(2, "0"),
- date.getUTCMinutes().toString().padStart(2, "0"),
- date.getUTCSeconds().toString().padStart(2, "0")
- ];
- const encodedDate = parts.join("") + "Z";
- const tag = isGeneralizedTime ? 24 : 23;
- return this._encode(tag, Buffer.from(encodedDate));
- }
- static _encode(tag, data) {
- const lengthBytes = this._encodeLength(data.length);
- return Buffer.concat([Buffer.from([tag]), lengthBytes, data]);
- }
- static _encodeLength(length) {
- if (length < 128) {
- return Buffer.from([length]);
- } else {
- const lengthBytes = [];
- while (length > 0) {
- lengthBytes.unshift(length & 255);
- length >>= 8;
- }
- return Buffer.from([128 | lengthBytes.length, ...lengthBytes]);
- }
- }
- };
- }
-});
-
-// packages/utils/env.ts
-function getFromENV(name) {
- let value2 = process.env[name];
- value2 = value2 === void 0 ? process.env[`npm_config_${name.toLowerCase()}`] : value2;
- value2 = value2 === void 0 ? process.env[`npm_package_config_${name.toLowerCase()}`] : value2;
- return value2;
-}
-function getAsBooleanFromENV(name, defaultValue) {
- const value2 = getFromENV(name);
- if (value2 === "false" || value2 === "0")
- return false;
- if (value2)
- return true;
- return !!defaultValue;
-}
-function getPackageManager() {
- const env = process.env.npm_config_user_agent || "";
- if (env.includes("yarn"))
- return "yarn";
- if (env.includes("pnpm"))
- return "pnpm";
- return "npm";
-}
-function getPackageManagerExecCommand() {
- const packageManager = getPackageManager();
- if (packageManager === "yarn")
- return "yarn";
- if (packageManager === "pnpm")
- return "pnpm exec";
- return "npx";
-}
-function isLikelyNpxGlobal() {
- return process.argv.length >= 2 && process.argv[1].includes("_npx");
-}
-function setPlaywrightTestProcessEnv() {
- return process.env["PLAYWRIGHT_TEST"] = "1";
-}
-function guessClientName() {
- if (process.env.CLAUDECODE)
- return "Claude Code";
- if (process.env.COPILOT_CLI)
- return "GitHub Copilot";
- return "playwright-cli";
-}
-function isCodingAgent() {
- return !!process.env.CLAUDECODE || !!process.env.COPILOT_CLI;
-}
-var init_env = __esm({
- "packages/utils/env.ts"() {
- "use strict";
- }
-});
-
-// packages/utils/debug.ts
-function debugMode() {
- if (_debugMode === "console")
- return "console";
- if (_debugMode === "0" || _debugMode === "false")
- return "";
- return _debugMode ? "inspector" : "";
-}
-function isUnderTest() {
- return _isUnderTest;
-}
-var _debugMode, _isUnderTest;
-var init_debug = __esm({
- "packages/utils/debug.ts"() {
- "use strict";
- init_env();
- _debugMode = getFromENV("PWDEBUG") || "";
- _isUnderTest = getAsBooleanFromENV("PWTEST_UNDER_TEST");
- }
-});
-
-// packages/utils/debugLogger.ts
-var import_fs, debug, debugLoggerColorMap, DebugLogger, debugLogger, kLogCount, RecentLogsCollector;
-var init_debugLogger = __esm({
- "packages/utils/debugLogger.ts"() {
- "use strict";
- import_fs = __toESM(require("fs"));
- debug = require("./utilsBundle").debug;
- debugLoggerColorMap = {
- "api": 45,
- // cyan
- "protocol": 34,
- // green
- "install": 34,
- // green
- "download": 34,
- // green
- "browser": 0,
- // reset
- "socks": 92,
- // purple
- "client-certificates": 92,
- // purple
- "error": 160,
- // red,
- "channel": 33,
- // blue
- "server": 45,
- // cyan
- "server:channel": 34,
- // green
- "server:metadata": 33,
- // blue,
- "recorder": 45
- // cyan
- };
- DebugLogger = class {
- constructor() {
- this._debuggers = /* @__PURE__ */ new Map();
- if (process.env.DEBUG_FILE) {
- const ansiRegex2 = new RegExp([
- "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
- "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
- ].join("|"), "g");
- const stream3 = import_fs.default.createWriteStream(process.env.DEBUG_FILE);
- debug.log = (data) => {
- stream3.write(data.replace(ansiRegex2, ""));
- stream3.write("\n");
- };
- }
- }
- log(name, message) {
- let cachedDebugger = this._debuggers.get(name);
- if (!cachedDebugger) {
- cachedDebugger = debug(`pw:${name}`);
- this._debuggers.set(name, cachedDebugger);
- cachedDebugger.color = debugLoggerColorMap[name] || 0;
- }
- cachedDebugger(message);
- }
- isEnabled(name) {
- return debug.enabled(`pw:${name}`);
- }
- };
- debugLogger = new DebugLogger();
- kLogCount = 150;
- RecentLogsCollector = class {
- constructor() {
- this._logs = [];
- this._listeners = [];
- }
- log(message) {
- this._logs.push(message);
- if (this._logs.length === kLogCount * 2)
- this._logs.splice(0, kLogCount);
- for (const listener of this._listeners)
- listener(message);
- }
- recentLogs() {
- if (this._logs.length > kLogCount)
- return this._logs.slice(-kLogCount);
- return this._logs;
- }
- onMessage(listener) {
- for (const message of this._logs)
- listener(message);
- this._listeners.push(listener);
- }
- };
- }
-});
-
-// packages/utils/eventsHelper.ts
-var EventsHelper, eventsHelper;
-var init_eventsHelper = __esm({
- "packages/utils/eventsHelper.ts"() {
- "use strict";
- EventsHelper = class {
- static addEventListener(emitter, eventName, handler) {
- emitter.on(eventName, handler);
- return { emitter, eventName, handler, dispose: async () => {
- emitter.removeListener(eventName, handler);
- } };
- }
- static removeEventListeners(listeners) {
- for (const listener of listeners)
- listener.emitter.removeListener(listener.eventName, listener.handler);
- listeners.splice(0, listeners.length);
- }
- };
- eventsHelper = EventsHelper;
- }
-});
-
-// packages/utils/fileUtils.ts
-async function mkdirIfNeeded(filePath) {
- await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true }).catch(() => {
- });
-}
-async function removeFolders(dirs) {
- return await Promise.all(dirs.map(
- (dir) => import_fs2.default.promises.rm(dir, { recursive: true, force: true, maxRetries: 10 }).catch((e) => e)
- ));
-}
-function canAccessFile(file) {
- if (!file)
- return false;
- try {
- import_fs2.default.accessSync(file);
- return true;
- } catch (e) {
- return false;
- }
-}
-function isWritable(file) {
- try {
- import_fs2.default.accessSync(file, import_fs2.default.constants.W_OK);
- return true;
- } catch {
- return false;
- }
-}
-function isSystemDirectory(dir) {
- const resolved = import_path2.default.resolve(dir);
- if (process.platform === "win32") {
- const systemRoot = import_path2.default.resolve(process.env.SystemRoot || "C:\\Windows");
- return isPathInside(systemRoot.toLowerCase(), resolved.toLowerCase());
- }
- return resolved === "/";
-}
-async function copyFileAndMakeWritable(from, to) {
- await import_fs2.default.promises.copyFile(from, to);
- await import_fs2.default.promises.chmod(to, 436);
-}
-function addSuffixToFilePath(filePath, suffix) {
- const ext = import_path2.default.extname(filePath);
- const base = filePath.substring(0, filePath.length - ext.length);
- return base + suffix + ext;
-}
-function sanitizeForFilePath(s) {
- return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-");
-}
-function trimLongString(s, length = 100) {
- if (s.length <= length)
- return s;
- const hash = calculateSha1(s);
- const middle = `-${hash.substring(0, 5)}-`;
- const start3 = Math.floor((length - middle.length) / 2);
- const end = length - middle.length - start3;
- return s.substring(0, start3) + middle + s.slice(-end);
-}
-function isPathInside(root, candidate) {
- const resolvedRoot = import_path2.default.resolve(root);
- const resolvedCandidate = import_path2.default.resolve(candidate);
- if (resolvedCandidate === resolvedRoot)
- return true;
- return resolvedCandidate.startsWith(resolvedRoot + import_path2.default.sep);
-}
-function resolveWithinRoot(root, fileName) {
- if (import_path2.default.isAbsolute(fileName))
- return null;
- const resolvedFile = import_path2.default.resolve(root, fileName);
- return isPathInside(root, resolvedFile) ? resolvedFile : null;
-}
-function throwingResolveWithinRoot(root, fileName) {
- const resolved = resolveWithinRoot(root, fileName);
- if (!resolved)
- throw new Error(`Path '${fileName}' escapes root directory`);
- return resolved;
-}
-function toPosixPath(aPath) {
- return aPath.split(import_path2.default.sep).join(import_path2.default.posix.sep);
-}
-function makeSocketPath(domain, name) {
- const userNameHash = calculateSha1(process.env.USERNAME || process.env.USER || "default").slice(0, 8);
- if (process.platform === "win32") {
- const socketsDir = process.env.PWTEST_SOCKETS_DIR;
- const suffix2 = socketsDir ? `-${calculateSha1(socketsDir).slice(0, 8)}` : "";
- return `\\\\.\\pipe\\pw-${userNameHash}-${domain}-${name}${suffix2}`;
- }
- const baseDir = process.env.PWTEST_SOCKETS_DIR || import_path2.default.join(import_os2.default.tmpdir(), `pw-${userNameHash}`);
- const dir = import_path2.default.join(baseDir, domain);
- const suffix = ".sock";
- const maxNameLength = UNIX_SOCKET_PATH_MAX - dir.length - import_path2.default.sep.length - suffix.length;
- if (maxNameLength < 1)
- throw new Error(`Socket directory path is too long (${dir.length} chars); set PWTEST_SOCKETS_DIR to a shorter location.`);
- const fsFriendlyName = trimLongString(sanitizeForFilePath(name), maxNameLength);
- const result2 = import_path2.default.join(dir, `${fsFriendlyName}${suffix}`);
- import_fs2.default.mkdirSync(dir, { recursive: true });
- return result2;
-}
-var import_fs2, import_os2, import_path2, existsAsync, UNIX_SOCKET_PATH_MAX;
-var init_fileUtils = __esm({
- "packages/utils/fileUtils.ts"() {
- "use strict";
- import_fs2 = __toESM(require("fs"));
- import_os2 = __toESM(require("os"));
- import_path2 = __toESM(require("path"));
- init_crypto();
- existsAsync = (path59) => new Promise((resolve) => import_fs2.default.stat(path59, (err) => resolve(!err)));
- UNIX_SOCKET_PATH_MAX = 103;
- }
-});
-
-// packages/utils/linuxUtils.ts
-function getLinuxDistributionInfoSync() {
- if (process.platform !== "linux")
- return void 0;
- if (!osRelease && !didFailToReadOSRelease) {
- try {
- const osReleaseText = import_fs3.default.readFileSync("/etc/os-release", "utf8");
- const fields = parseOSReleaseText(osReleaseText);
- osRelease = {
- id: fields.get("id") ?? "",
- version: fields.get("version_id") ?? ""
- };
- } catch (e) {
- didFailToReadOSRelease = true;
- }
- }
- return osRelease;
-}
-function parseOSReleaseText(osReleaseText) {
- const fields = /* @__PURE__ */ new Map();
- for (const line of osReleaseText.split("\n")) {
- const tokens = line.split("=");
- const name = tokens.shift();
- let value2 = tokens.join("=").trim();
- if (value2.startsWith('"') && value2.endsWith('"'))
- value2 = value2.substring(1, value2.length - 1);
- if (!name)
- continue;
- fields.set(name.toLowerCase(), value2);
- }
- return fields;
-}
-var import_fs3, didFailToReadOSRelease, osRelease;
-var init_linuxUtils = __esm({
- "packages/utils/linuxUtils.ts"() {
- "use strict";
- import_fs3 = __toESM(require("fs"));
- didFailToReadOSRelease = false;
- }
-});
-
-// packages/utils/hostPlatform.ts
-function calculatePlatform() {
- if (process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE) {
- return {
- hostPlatform: process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE,
- isOfficiallySupportedPlatform: false
- };
- }
- const platform = import_os3.default.platform();
- if (platform === "darwin") {
- const ver = import_os3.default.release().split(".").map((a) => parseInt(a, 10));
- let macVersion = "";
- if (ver[0] < 18) {
- macVersion = "mac10.13";
- } else if (ver[0] === 18) {
- macVersion = "mac10.14";
- } else if (ver[0] === 19) {
- macVersion = "mac10.15";
- } else if (ver[0] < 25) {
- macVersion = "mac" + (ver[0] - 9);
- if (import_os3.default.cpus().some((cpu) => cpu.model.includes("Apple")))
- macVersion += "-arm64";
- } else {
- const LAST_STABLE_MACOS_MAJOR_VERSION = 26;
- macVersion = "mac" + Math.min(ver[0] + 1, LAST_STABLE_MACOS_MAJOR_VERSION);
- if (import_os3.default.cpus().some((cpu) => cpu.model.includes("Apple")))
- macVersion += "-arm64";
- }
- return { hostPlatform: macVersion, isOfficiallySupportedPlatform: true };
- }
- if (platform === "linux") {
- if (!["x64", "arm64"].includes(import_os3.default.arch()))
- return { hostPlatform: "", isOfficiallySupportedPlatform: false };
- const archSuffix = "-" + import_os3.default.arch();
- const distroInfo = getLinuxDistributionInfoSync();
- if (distroInfo?.id === "ubuntu" || distroInfo?.id === "pop" || distroInfo?.id === "neon" || distroInfo?.id === "tuxedo") {
- const isUbuntu = distroInfo?.id === "ubuntu";
- const version3 = distroInfo?.version;
- const major2 = parseInt(distroInfo.version, 10);
- if (major2 < 20)
- return { hostPlatform: "ubuntu18.04" + archSuffix, isOfficiallySupportedPlatform: false };
- if (major2 < 22)
- return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "20.04" };
- if (major2 < 24)
- return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "22.04" };
- if (major2 < 26)
- return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "24.04" };
- if (major2 < 28)
- return { hostPlatform: "ubuntu26.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "26.04" };
- return { hostPlatform: "ubuntu" + distroInfo.version + archSuffix, isOfficiallySupportedPlatform: false };
- }
- if (distroInfo?.id === "linuxmint") {
- const mintMajor = parseInt(distroInfo.version, 10);
- if (mintMajor <= 20)
- return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false };
- if (mintMajor === 21)
- return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: false };
- return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false };
- }
- if (distroInfo?.id === "debian" || distroInfo?.id === "raspbian") {
- const isOfficiallySupportedPlatform2 = distroInfo?.id === "debian";
- if (distroInfo?.version === "11")
- return { hostPlatform: "debian11" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 };
- if (distroInfo?.version === "12")
- return { hostPlatform: "debian12" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 };
- if (distroInfo?.version === "13")
- return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 };
- if (distroInfo?.version === "")
- return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 };
- }
- return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false };
- }
- if (platform === "win32")
- return { hostPlatform: "win64", isOfficiallySupportedPlatform: true };
- return { hostPlatform: "", isOfficiallySupportedPlatform: false };
-}
-function toShortPlatform(hostPlatform2) {
- if (hostPlatform2 === "")
- return "";
- if (hostPlatform2 === "win64")
- return "win-x64";
- if (hostPlatform2.startsWith("mac"))
- return hostPlatform2.endsWith("arm64") ? "mac-arm64" : "mac-x64";
- return hostPlatform2.endsWith("arm64") ? "linux-arm64" : "linux-x64";
-}
-var import_os3, hostPlatform, isOfficiallySupportedPlatform, shortPlatform;
-var init_hostPlatform = __esm({
- "packages/utils/hostPlatform.ts"() {
- "use strict";
- import_os3 = __toESM(require("os"));
- init_linuxUtils();
- ({ hostPlatform, isOfficiallySupportedPlatform } = calculatePlatform());
- shortPlatform = toShortPlatform(hostPlatform);
- }
-});
-
-// packages/utils/happyEyeballs.ts
-async function createSocket(host, port) {
- return new Promise((resolve, reject) => {
- if (import_net.default.isIP(host)) {
- const socket = import_net.default.createConnection({ host, port });
- socket.on("connect", () => resolve(socket));
- socket.on("error", (error) => reject(error));
- } else {
- createConnectionAsync(
- { host, port },
- (err, socket) => {
- if (err)
- reject(err);
- if (socket)
- resolve(socket);
- },
- /* useTLS */
- false
- ).catch((err) => reject(err));
- }
- });
-}
-async function createConnectionAsync(options, oncreate, useTLS) {
- const lookup = options.__testHookLookup || lookupAddresses;
- const hostname = clientRequestArgsToHostName(options);
- const addresses = await lookup(hostname);
- const dnsLookupAt = monotonicTime();
- const sockets = /* @__PURE__ */ new Set();
- let firstError;
- let errorCount = 0;
- const handleError = (socket, err) => {
- if (!sockets.delete(socket))
- return;
- ++errorCount;
- firstError ??= err;
- if (errorCount === addresses.length)
- oncreate?.(firstError);
- };
- const connected = new ManualPromise();
- for (const { address } of addresses) {
- const socket = useTLS ? import_tls.default.connect({
- ...options,
- port: options.port,
- host: address,
- servername: hostname
- }) : import_net.default.createConnection({
- ...options,
- port: options.port,
- host: address
- });
- socket[kDNSLookupAt] = dnsLookupAt;
- socket.on("connect", () => {
- socket[kTCPConnectionAt] = monotonicTime();
- connected.resolve();
- oncreate?.(null, socket);
- sockets.delete(socket);
- for (const s of sockets)
- s.destroy();
- sockets.clear();
- });
- socket.on("timeout", () => {
- socket.destroy();
- handleError(socket, new Error("Connection timeout"));
- });
- socket.on("error", (e) => handleError(socket, e));
- sockets.add(socket);
- await Promise.race([
- connected,
- new Promise((f) => setTimeout(f, connectionAttemptDelayMs))
- ]);
- if (connected.isDone())
- break;
- }
-}
-async function lookupAddresses(hostname) {
- const [v4Result, v6Result] = await Promise.allSettled([
- import_dns.default.promises.lookup(hostname, { all: true, family: 4 }),
- import_dns.default.promises.lookup(hostname, { all: true, family: 6 })
- ]);
- const v4Addresses = v4Result.status === "fulfilled" ? v4Result.value : [];
- const v6Addresses = v6Result.status === "fulfilled" ? v6Result.value : [];
- if (!v4Addresses.length && !v6Addresses.length) {
- if (v4Result.status === "rejected")
- throw v4Result.reason;
- throw v6Result.reason;
- }
- const result2 = [];
- for (let i = 0; i < Math.max(v4Addresses.length, v6Addresses.length); i++) {
- if (v6Addresses[i])
- result2.push(v6Addresses[i]);
- if (v4Addresses[i])
- result2.push(v4Addresses[i]);
- }
- return result2;
-}
-function clientRequestArgsToHostName(options) {
- if (options.hostname)
- return options.hostname;
- if (options.host)
- return options.host;
- throw new Error("Either options.hostname or options.host must be provided");
-}
-function timingForSocket(socket) {
- return {
- dnsLookupAt: socket[kDNSLookupAt],
- tcpConnectionAt: socket[kTCPConnectionAt]
- };
-}
-var import_dns, import_http, import_https, import_net, import_tls, connectionAttemptDelayMs, kDNSLookupAt, kTCPConnectionAt, HttpHappyEyeballsAgent, HttpsHappyEyeballsAgent, httpsHappyEyeballsAgent, httpHappyEyeballsAgent;
-var init_happyEyeballs = __esm({
- "packages/utils/happyEyeballs.ts"() {
- "use strict";
- import_dns = __toESM(require("dns"));
- import_http = __toESM(require("http"));
- import_https = __toESM(require("https"));
- import_net = __toESM(require("net"));
- import_tls = __toESM(require("tls"));
- init_assert();
- init_manualPromise();
- init_time();
- connectionAttemptDelayMs = 300;
- kDNSLookupAt = Symbol("kDNSLookupAt");
- kTCPConnectionAt = Symbol("kTCPConnectionAt");
- HttpHappyEyeballsAgent = class extends import_http.default.Agent {
- createConnection(options, oncreate) {
- if (import_net.default.isIP(clientRequestArgsToHostName(options)))
- return import_net.default.createConnection(options);
- createConnectionAsync(
- options,
- oncreate,
- /* useTLS */
- false
- ).catch((err) => oncreate?.(err));
- }
- };
- HttpsHappyEyeballsAgent = class extends import_https.default.Agent {
- createConnection(options, oncreate) {
- if (import_net.default.isIP(clientRequestArgsToHostName(options)))
- return import_tls.default.connect(options);
- createConnectionAsync(
- options,
- oncreate,
- /* useTLS */
- true
- ).catch((err) => oncreate?.(err));
- }
- };
- httpsHappyEyeballsAgent = new HttpsHappyEyeballsAgent({ keepAlive: true });
- httpHappyEyeballsAgent = new HttpHappyEyeballsAgent({ keepAlive: true });
- }
-});
-
-// packages/utils/network.ts
-function httpRequest(params2, onResponse, onError) {
- let url2 = new URL(params2.url);
- const options = {
- method: params2.method || "GET",
- headers: params2.headers
- };
- if (params2.rejectUnauthorized !== void 0)
- options.rejectUnauthorized = params2.rejectUnauthorized;
- const proxyURL = getProxyForUrl(params2.url);
- if (proxyURL) {
- const parsedProxyURL = normalizeProxyURL(proxyURL);
- if (params2.url.startsWith("http:")) {
- options.path = url2.toString();
- const headers = options.headers || {};
- if (!Object.keys(headers).some((header) => header.toLowerCase() === "host"))
- headers.host = url2.host;
- options.headers = headers;
- url2 = parsedProxyURL;
- } else {
- options.agent = new HttpsProxyAgent(parsedProxyURL);
- }
- }
- options.agent ??= url2.protocol === "https:" ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent;
- let cancelRequest;
- const requestCallback = (res) => {
- const statusCode = res.statusCode || 0;
- if (statusCode >= 300 && statusCode < 400 && res.headers.location) {
- request2.destroy();
- cancelRequest = httpRequest({ ...params2, url: new URL(res.headers.location, params2.url).toString() }, onResponse, onError).cancel;
- } else {
- onResponse(res);
- }
- };
- const request2 = url2.protocol === "https:" ? import_https2.default.request(url2, options, requestCallback) : import_http2.default.request(url2, options, requestCallback);
- request2.on("error", onError);
- if (params2.socketTimeout !== void 0) {
- request2.setTimeout(params2.socketTimeout, () => {
- onError(new Error(`Request to ${params2.url} timed out after ${params2.socketTimeout}ms`));
- request2.abort();
- });
- }
- cancelRequest = (e) => {
- try {
- request2.destroy(e);
- } catch {
- }
- };
- request2.end(params2.data);
- return { cancel: (e) => cancelRequest(e) };
-}
-function shouldBypassProxy(url2, bypass) {
- if (!bypass)
- return false;
- const domains = bypass.split(",").map((s) => {
- s = s.trim();
- if (!s.startsWith("."))
- s = "." + s;
- return s;
- });
- const domain = "." + url2.hostname;
- return domains.some((d) => domain.endsWith(d));
-}
-function normalizeProxyURL(proxy) {
- proxy = proxy.trim();
- if (!/^\w+:\/\//.test(proxy))
- proxy = "http://" + proxy;
- return new URL(proxy);
-}
-function createProxyAgent(proxy, forUrl) {
- if (!proxy)
- return;
- if (forUrl && proxy.bypass && shouldBypassProxy(forUrl, proxy.bypass))
- return;
- const proxyURL = normalizeProxyURL(proxy.server);
- if (proxyURL.protocol?.startsWith("socks")) {
- if (proxyURL.protocol === "socks5:")
- proxyURL.protocol = "socks5h:";
- else if (proxyURL.protocol === "socks4:")
- proxyURL.protocol = "socks4a:";
- return new SocksProxyAgent(proxyURL);
- }
- if (proxy.username) {
- proxyURL.username = proxy.username;
- proxyURL.password = proxy.password || "";
- }
- if (forUrl && ["ws:", "wss:"].includes(forUrl.protocol)) {
- return new HttpsProxyAgent(proxyURL);
- }
- return new HttpsProxyAgent(proxyURL);
-}
-function createHttpServer(...args) {
- const server = import_http2.default.createServer(...args);
- decorateServer(server);
- return server;
-}
-function createHttpsServer(...args) {
- const server = import_https2.default.createServer(...args);
- decorateServer(server);
- return server;
-}
-function createHttp2Server(...args) {
- const server = import_http22.default.createSecureServer(...args);
- decorateServer(server);
- return server;
-}
-async function startHttpServer(server, options) {
- const { host = "localhost", port = 0 } = options;
- const errorPromise = new ManualPromise();
- const errorListener = (error) => errorPromise.reject(error);
- server.on("error", errorListener);
- try {
- server.listen(port, host);
- await Promise.race([
- new Promise((cb) => server.once("listening", cb)),
- errorPromise
- ]);
- } finally {
- server.removeListener("error", errorListener);
- }
-}
-async function isURLAvailable(url2, ignoreHTTPSErrors, onLog, onStdErr) {
- let statusCode = await httpStatusCode(url2, ignoreHTTPSErrors, onLog, onStdErr);
- if (statusCode === 404 && url2.pathname === "/") {
- const indexUrl = new URL(url2);
- indexUrl.pathname = "/index.html";
- statusCode = await httpStatusCode(indexUrl, ignoreHTTPSErrors, onLog, onStdErr);
- }
- return statusCode >= 200 && statusCode < 404;
-}
-async function httpStatusCode(url2, ignoreHTTPSErrors, onLog, onStdErr) {
- return new Promise((resolve) => {
- onLog?.(`HTTP GET: ${url2}`);
- httpRequest({
- url: url2.toString(),
- headers: { Accept: "*/*" },
- rejectUnauthorized: !ignoreHTTPSErrors
- }, (res) => {
- res.resume();
- const statusCode = res.statusCode ?? 0;
- onLog?.(`HTTP Status: ${statusCode}`);
- resolve(statusCode);
- }, (error) => {
- if (error.code === "DEPTH_ZERO_SELF_SIGNED_CERT")
- onStdErr?.(`[WebServer] Self-signed certificate detected. Try adding ignoreHTTPSErrors: true to config.webServer.`);
- onLog?.(`Error while checking if ${url2} is available: ${error.message}`);
- resolve(0);
- });
- });
-}
-function decorateServer(server) {
- const sockets = /* @__PURE__ */ new Set();
- server.on("connection", (socket) => {
- sockets.add(socket);
- socket.once("close", () => sockets.delete(socket));
- });
- const close3 = server.close;
- server.close = (callback) => {
- for (const socket of sockets)
- socket.destroy();
- sockets.clear();
- return close3.call(server, callback);
- };
-}
-var import_http2, import_http22, import_https2, HttpsProxyAgent, SocksProxyAgent, getProxyForUrl, NET_DEFAULT_TIMEOUT;
-var init_network = __esm({
- "packages/utils/network.ts"() {
- "use strict";
- import_http2 = __toESM(require("http"));
- import_http22 = __toESM(require("http2"));
- import_https2 = __toESM(require("https"));
- init_manualPromise();
- init_happyEyeballs();
- ({ HttpsProxyAgent } = require("./utilsBundle"));
- ({ SocksProxyAgent } = require("./utilsBundle"));
- ({ getProxyForUrl } = require("./utilsBundle"));
- NET_DEFAULT_TIMEOUT = 3e4;
- }
-});
-
-// packages/utils/httpServer.ts
-function computeAllowedHosts(requested, bound) {
- const loopback = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "localhost"]);
- const isLoopback = (h) => h !== void 0 && loopback.has(h.toLowerCase());
- if (!isLoopback(requested) && requested !== void 0)
- return null;
- if (!isLoopback(bound) && requested === void 0)
- return null;
- return /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
-}
-function urlHostFromAddress(address) {
- return address.family === "IPv6" ? `[${address.address}]` : address.address;
-}
-function hostnameFromHostHeader(host) {
- if (host.startsWith("[")) {
- const end = host.indexOf("]");
- return end < 0 ? host : host.substring(0, end + 1);
- }
- const colon = host.indexOf(":");
- return colon < 0 ? host : host.substring(0, colon);
-}
-function serveFolder(folder) {
- const server = new HttpServer(folder);
- server.routePrefix("/", (request2, response2) => {
- let relativePath = new URL("http://localhost" + request2.url).pathname;
- if (relativePath.startsWith("/trace/file")) {
- const url2 = new URL("http://localhost" + request2.url);
- const requested = url2.searchParams.get("path");
- if (!requested)
- return false;
- const resolved = import_path3.default.resolve(requested);
- try {
- return server.serveFile(request2, response2, resolved);
- } catch (e) {
- return false;
- }
- }
- if (relativePath === "/")
- relativePath = "/index.html";
- const absolutePath = import_path3.default.join(folder, ...relativePath.split("/"));
- return server.serveFile(request2, response2, absolutePath);
- });
- return server;
-}
-var import_fs4, import_path3, mime, wsServer, HttpServer;
-var init_httpServer = __esm({
- "packages/utils/httpServer.ts"() {
- "use strict";
- import_fs4 = __toESM(require("fs"));
- import_path3 = __toESM(require("path"));
- init_assert();
- init_crypto();
- init_fileUtils();
- init_network();
- mime = require("./utilsBundle").mime;
- ({ wsServer } = require("./utilsBundle"));
- HttpServer = class {
- constructor(staticRoot) {
- this._urlPrefixPrecise = "";
- this._urlPrefixHumanReadable = "";
- this._port = 0;
- this._started = false;
- this._routes = [];
- // Allowed Host headers; null disables the check (host bound to a public address).
- this._allowedHosts = null;
- this._server = createHttpServer(this._onRequest.bind(this));
- this._staticRoot = staticRoot ? import_path3.default.resolve(staticRoot) : void 0;
- }
- server() {
- return this._server;
- }
- routePrefix(prefix, handler) {
- this._routes.push({ prefix, handler });
- }
- routePath(path59, handler) {
- this._routes.push({ exact: path59, handler });
- }
- port() {
- return this._port;
- }
- createWebSocket(transportFactory, guid) {
- assert(!this._wsGuid, "can only create one main websocket transport per server");
- this._wsGuid = guid || createGuid();
- const wsPath = "/" + this._wsGuid;
- const wss = new wsServer({ noServer: true });
- this._server.on("upgrade", (request2, socket, head) => {
- const pathname = new URL(request2.url ?? "/", "http://localhost").pathname;
- if (pathname !== wsPath)
- return;
- wss.handleUpgrade(request2, socket, head, (ws4) => wss.emit("connection", ws4, request2));
- });
- wss.on("connection", (ws4, request2) => {
- const url2 = new URL(request2.url ?? "/", "http://localhost");
- const transport = transportFactory(url2);
- transport.sendEvent = (method, params2) => ws4.send(JSON.stringify({ method, params: params2 }));
- transport.close = () => ws4.close();
- transport.onconnect();
- ws4.on("message", async (message) => {
- const { id, method, params: params2 } = JSON.parse(String(message));
- try {
- const result2 = await transport.dispatch(method, params2);
- ws4.send(JSON.stringify({ id, result: result2 }));
- } catch (e) {
- ws4.send(JSON.stringify({ id, error: String(e) }));
- }
- });
- ws4.on("close", () => transport.onclose());
- ws4.on("error", () => transport.onclose());
- });
- }
- wsGuid() {
- return this._wsGuid;
- }
- async createViteDevServer(options) {
- const loadVite = new Function('return import("vite")');
- const vite = await loadVite();
- return await vite.createServer({
- root: options.root,
- base: options.base,
- server: {
- middlewareMode: true,
- // Dedicated path so Vite's HMR websocket does not collide with any
- // websocket HttpServer owns via createWebSocket().
- hmr: { path: "/__vite_hmr", server: this._server }
- },
- appType: "spa",
- clearScreen: false
- });
- }
- // HMR end
- // Vite's middleware `next` callback for the "no middleware matched" case;
- // emits a 404 only if nothing downstream already responded.
- static notFoundFallback(response2) {
- return () => {
- if (!response2.headersSent) {
- response2.statusCode = 404;
- response2.end();
- }
- };
- }
- async start(options = {}) {
- assert(!this._started, "server already started");
- this._started = true;
- const host = options.host;
- if (options.preferredPort) {
- try {
- await startHttpServer(this._server, { port: options.preferredPort, host });
- } catch (e) {
- if (!e || !e.message || !e.message.includes("EADDRINUSE"))
- throw e;
- await startHttpServer(this._server, { host });
- }
- } else {
- await startHttpServer(this._server, { port: options.port, host });
- }
- const address = this._server.address();
- assert(address, "Could not bind server socket");
- if (typeof address === "string") {
- this._urlPrefixPrecise = address;
- this._urlPrefixHumanReadable = address;
- } else {
- this._port = address.port;
- this._urlPrefixPrecise = `http://${urlHostFromAddress(address)}:${address.port}`;
- this._urlPrefixHumanReadable = `http://${host ?? "localhost"}:${address.port}`;
- this._allowedHosts = computeAllowedHosts(host, address.address);
- }
- }
- async stop() {
- await new Promise((cb) => this._server.close(cb));
- }
- urlPrefix(purpose) {
- return purpose === "human-readable" ? this._urlPrefixHumanReadable : this._urlPrefixPrecise;
- }
- serveFile(request2, response2, absoluteFilePath, headers, options) {
- if (this._staticRoot && !options?.skipRootCheck && !isPathInside(this._staticRoot, absoluteFilePath)) {
- response2.statusCode = 403;
- response2.end();
- return true;
- }
- try {
- for (const [name, value2] of Object.entries(headers || {}))
- response2.setHeader(name, value2);
- if (request2.headers.range)
- this._serveRangeFile(request2, response2, absoluteFilePath);
- else
- this._serveFile(response2, absoluteFilePath);
- return true;
- } catch (e) {
- return false;
- }
- }
- _serveFile(response2, absoluteFilePath) {
- const content = import_fs4.default.readFileSync(absoluteFilePath);
- response2.statusCode = 200;
- const contentType = mime.getType(import_path3.default.extname(absoluteFilePath)) || "application/octet-stream";
- response2.setHeader("Content-Type", contentType);
- response2.setHeader("Content-Length", content.byteLength);
- response2.end(content);
- }
- _serveRangeFile(request2, response2, absoluteFilePath) {
- const range = request2.headers.range;
- if (!range || !range.startsWith("bytes=") || range.includes(", ") || [...range].filter((char) => char === "-").length !== 1) {
- response2.statusCode = 400;
- return response2.end("Bad request");
- }
- const [startStr, endStr] = range.replace(/bytes=/, "").split("-");
- let start3;
- let end;
- const size = import_fs4.default.statSync(absoluteFilePath).size;
- if (startStr !== "" && endStr === "") {
- start3 = +startStr;
- end = size - 1;
- } else if (startStr === "" && endStr !== "") {
- start3 = size - +endStr;
- end = size - 1;
- } else {
- start3 = +startStr;
- end = +endStr;
- }
- if (Number.isNaN(start3) || Number.isNaN(end) || start3 >= size || end >= size || start3 > end) {
- response2.writeHead(416, {
- "Content-Range": `bytes */${size}`
- });
- return response2.end();
- }
- response2.writeHead(206, {
- "Content-Range": `bytes ${start3}-${end}/${size}`,
- "Accept-Ranges": "bytes",
- "Content-Length": end - start3 + 1,
- "Content-Type": mime.getType(import_path3.default.extname(absoluteFilePath))
- });
- const readable = import_fs4.default.createReadStream(absoluteFilePath, { start: start3, end });
- readable.pipe(response2);
- }
- _onRequest(request2, response2) {
- if (request2.method === "OPTIONS") {
- response2.writeHead(200);
- response2.end();
- return;
- }
- if (this._allowedHosts) {
- const host = request2.headers.host?.toLowerCase();
- const hostname = host ? hostnameFromHostHeader(host) : void 0;
- if (!hostname || !this._allowedHosts.has(hostname)) {
- response2.statusCode = 403;
- response2.end();
- return;
- }
- }
- request2.on("error", () => response2.end());
- try {
- if (!request2.url) {
- response2.end();
- return;
- }
- const url2 = new URL("http://localhost" + request2.url);
- for (const route2 of this._routes) {
- if (route2.exact && url2.pathname === route2.exact && route2.handler(request2, response2))
- return;
- if (route2.prefix && url2.pathname.startsWith(route2.prefix) && route2.handler(request2, response2))
- return;
- }
- response2.statusCode = 404;
- response2.end();
- } catch (e) {
- response2.end();
- }
- }
- };
- }
-});
-
-// packages/utils/zones.ts
-function currentZone() {
- return asyncLocalStorage.getStore() ?? emptyZone;
-}
-var import_async_hooks, asyncLocalStorage, Zone, emptyZone;
-var init_zones = __esm({
- "packages/utils/zones.ts"() {
- "use strict";
- import_async_hooks = require("async_hooks");
- asyncLocalStorage = new import_async_hooks.AsyncLocalStorage();
- Zone = class _Zone {
- constructor(asyncLocalStorage2, store) {
- this._asyncLocalStorage = asyncLocalStorage2;
- this._data = store;
- }
- with(type3, data) {
- return new _Zone(this._asyncLocalStorage, new Map(this._data).set(type3, data));
- }
- without(type3) {
- const data = type3 ? new Map(this._data) : /* @__PURE__ */ new Map();
- data.delete(type3);
- return new _Zone(this._asyncLocalStorage, data);
- }
- run(func) {
- return this._asyncLocalStorage.run(this, func);
- }
- data(type3) {
- return this._data.get(type3);
- }
- };
- emptyZone = new Zone(asyncLocalStorage, /* @__PURE__ */ new Map());
- }
-});
-
-// packages/utils/nodePlatform.ts
-function setBoxedStackPrefixes(prefixes) {
- boxedStackPrefixes = prefixes;
-}
-var import_crypto4, import_fs5, import_path4, util, import_stream, import_events, colors2, pipelineAsync, NodeZone, boxedStackPrefixes, nodePlatform, ReadableStreamImpl, WritableStreamImpl;
-var init_nodePlatform = __esm({
- "packages/utils/nodePlatform.ts"() {
- "use strict";
- import_crypto4 = __toESM(require("crypto"));
- import_fs5 = __toESM(require("fs"));
- import_path4 = __toESM(require("path"));
- util = __toESM(require("util"));
- import_stream = require("stream");
- import_events = require("events");
- init_debugLogger();
- init_zones();
- init_debug();
- colors2 = require("./utilsBundle").colors;
- pipelineAsync = util.promisify(import_stream.pipeline);
- NodeZone = class _NodeZone {
- constructor(zone) {
- this._zone = zone;
- }
- push(data) {
- return new _NodeZone(this._zone.with("apiZone", data));
- }
- pop() {
- return new _NodeZone(this._zone.without("apiZone"));
- }
- run(func) {
- return this._zone.run(func);
- }
- data() {
- return this._zone.data("apiZone");
- }
- };
- boxedStackPrefixes = [];
- nodePlatform = (coreDir) => ({
- name: "node",
- boxedStackPrefixes: () => {
- if (process.env.PWDEBUGIMPL)
- return [];
- return [coreDir, ...boxedStackPrefixes];
- },
- calculateSha1: (text2) => {
- const sha1 = import_crypto4.default.createHash("sha1");
- sha1.update(text2);
- return Promise.resolve(sha1.digest("hex"));
- },
- colors: colors2,
- coreDir,
- createGuid: () => import_crypto4.default.randomBytes(16).toString("hex"),
- defaultMaxListeners: () => import_events.EventEmitter.defaultMaxListeners,
- fs: () => import_fs5.default,
- env: process.env,
- inspectCustom: util.inspect.custom,
- isDebugMode: () => debugMode() === "inspector",
- isJSDebuggerAttached: () => !!require("inspector").url(),
- isLogEnabled(name) {
- return debugLogger.isEnabled(name);
- },
- isUnderTest: () => isUnderTest(),
- log(name, message) {
- debugLogger.log(name, message);
- },
- path: () => import_path4.default,
- pathSeparator: import_path4.default.sep,
- showInternalStackFrames: () => !!process.env.PWDEBUGIMPL,
- async streamFile(path59, stream3) {
- await pipelineAsync(import_fs5.default.createReadStream(path59), stream3);
- },
- streamReadable: (channel) => {
- return new ReadableStreamImpl(channel);
- },
- streamWritable: (channel) => {
- return new WritableStreamImpl(channel);
- },
- zones: {
- current: () => new NodeZone(currentZone()),
- empty: new NodeZone(emptyZone)
- }
- });
- ReadableStreamImpl = class extends import_stream.Readable {
- constructor(channel) {
- super();
- this._channel = channel;
- }
- async _read() {
- const result2 = await this._channel.read({ size: 1024 * 1024 });
- if (result2.binary.byteLength)
- this.push(result2.binary);
- else
- this.push(null);
- }
- _destroy(error, callback) {
- this._channel.close().catch((e) => null);
- super._destroy(error, callback);
- }
- };
- WritableStreamImpl = class extends import_stream.Writable {
- constructor(channel) {
- super();
- this._channel = channel;
- }
- async _write(chunk, encoding, callback) {
- const error = await this._channel.write({ binary: typeof chunk === "string" ? Buffer.from(chunk) : chunk }).catch((e) => e);
- callback(error || null);
- }
- async _final(callback) {
- const error = await this._channel.close().catch((e) => e);
- callback(error || null);
- }
- };
- }
-});
-
-// packages/utils/processLauncher.ts
-async function gracefullyCloseAll() {
- await Promise.all(Array.from(gracefullyCloseSet).map((gracefullyClose) => gracefullyClose().catch((e) => {
- })));
-}
-function gracefullyProcessExitDoNotHang(code, onExit2) {
- const beforeExit = onExit2 ? () => onExit2().catch(() => {
- }) : () => Promise.resolve();
- const callback = () => beforeExit().then(() => process.exit(code));
- setTimeout(callback, 3e4);
- gracefullyCloseAll().then(callback);
-}
-function exitHandler() {
- for (const kill of killSet)
- kill();
-}
-function sigintHandler() {
- const exitWithCode130 = () => {
- if (isUnderTest()) {
- setTimeout(() => process.exit(130), 1e3);
- } else {
- process.exit(130);
- }
- };
- if (sigintHandlerCalled) {
- process.off("SIGINT", sigintHandler);
- for (const kill of killSet)
- kill();
- exitWithCode130();
- } else {
- sigintHandlerCalled = true;
- gracefullyCloseAll().then(() => exitWithCode130());
- }
-}
-function sigtermHandler() {
- gracefullyCloseAll();
-}
-function sighupHandler() {
- gracefullyCloseAll();
-}
-function addProcessHandlerIfNeeded(name) {
- if (!installedHandlers.has(name)) {
- installedHandlers.add(name);
- process.on(name, processHandlers[name]);
- }
-}
-function removeProcessHandlersIfNeeded() {
- if (killSet.size)
- return;
- for (const handler of installedHandlers)
- process.off(handler, processHandlers[handler]);
- installedHandlers.clear();
-}
-async function launchProcess(options) {
- const stdio = options.stdio === "pipe" ? ["ignore", "pipe", "pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe"];
- options.log(` ${options.command} ${options.args ? options.args.join(" ") : ""}`);
- const spawnOptions = {
- // On non-windows platforms, `detached: true` makes child process a leader of a new
- // process group, making it possible to kill child process tree with `.kill(-pid)` command.
- // @see https://nodejs.org/api/child_process.html#child_process_options_detached
- detached: process.platform !== "win32",
- env: options.env,
- cwd: options.cwd,
- shell: options.shell,
- stdio
- };
- const spawnedProcess = childProcess.spawn(options.command, options.args || [], spawnOptions);
- const cleanup = async () => {
- options.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`);
- const errors = await removeFolders(options.tempDirectories);
- for (let i = 0; i < options.tempDirectories.length; ++i) {
- if (errors[i])
- options.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${options.tempDirectories[i]}: ${errors[i]}`);
- }
- options.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`);
- };
- spawnedProcess.on("error", () => {
- });
- if (!spawnedProcess.pid) {
- let failed;
- const failedPromise = new Promise((f, r) => failed = f);
- spawnedProcess.once("error", (error) => {
- failed(new Error("Failed to launch: " + error));
- });
- return failedPromise.then(async (error) => {
- await cleanup();
- throw error;
- });
- }
- options.log(` pid=${spawnedProcess.pid}`);
- const stdout = readline.createInterface({ input: spawnedProcess.stdout });
- stdout.on("line", (data) => {
- options.log(`[pid=${spawnedProcess.pid}][out] ` + data);
- });
- const stderr = readline.createInterface({ input: spawnedProcess.stderr });
- stderr.on("line", (data) => {
- options.log(`[pid=${spawnedProcess.pid}][err] ` + data);
- });
- let processClosed = false;
- let fulfillCleanup = () => {
- };
- const waitForCleanup = new Promise((f) => fulfillCleanup = f);
- spawnedProcess.once("close", (exitCode, signal) => {
- options.log(`[pid=${spawnedProcess.pid}] `);
- processClosed = true;
- gracefullyCloseSet.delete(gracefullyClose);
- killSet.delete(killProcessAndCleanup);
- removeProcessHandlersIfNeeded();
- options.onExit(exitCode, signal);
- cleanup().then(fulfillCleanup);
- });
- addProcessHandlerIfNeeded("exit");
- if (options.handleSIGINT)
- addProcessHandlerIfNeeded("SIGINT");
- if (options.handleSIGTERM)
- addProcessHandlerIfNeeded("SIGTERM");
- if (options.handleSIGHUP)
- addProcessHandlerIfNeeded("SIGHUP");
- gracefullyCloseSet.add(gracefullyClose);
- killSet.add(killProcessAndCleanup);
- let gracefullyClosing = false;
- async function gracefullyClose() {
- if (gracefullyClosing) {
- options.log(`[pid=${spawnedProcess.pid}] `);
- killProcess();
- await waitForCleanup;
- return;
- }
- gracefullyClosing = true;
- options.log(`[pid=${spawnedProcess.pid}] `);
- await options.attemptToGracefullyClose().catch(() => killProcess());
- await waitForCleanup;
- options.log(`[pid=${spawnedProcess.pid}] `);
- }
- function killProcess() {
- gracefullyCloseSet.delete(gracefullyClose);
- killSet.delete(killProcessAndCleanup);
- removeProcessHandlersIfNeeded();
- options.log(`[pid=${spawnedProcess.pid}] `);
- if (spawnedProcess.pid && !spawnedProcess.killed && !processClosed) {
- options.log(`[pid=${spawnedProcess.pid}] `);
- try {
- if (process.platform === "win32") {
- const taskkillProcess = childProcess.spawnSync(`taskkill /pid ${spawnedProcess.pid} /T /F`, { shell: true });
- const [stdout2, stderr2] = [taskkillProcess.stdout.toString(), taskkillProcess.stderr.toString()];
- if (stdout2)
- options.log(`[pid=${spawnedProcess.pid}] taskkill stdout: ${stdout2}`);
- if (stderr2)
- options.log(`[pid=${spawnedProcess.pid}] taskkill stderr: ${stderr2}`);
- } else {
- process.kill(-spawnedProcess.pid, "SIGKILL");
- }
- } catch (e) {
- options.log(`[pid=${spawnedProcess.pid}] exception while trying to kill process: ${e}`);
- }
- } else {
- options.log(`[pid=${spawnedProcess.pid}] `);
- }
- }
- function killProcessAndCleanup() {
- killProcess();
- options.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`);
- for (const dir of options.tempDirectories) {
- try {
- import_fs6.default.rmSync(dir, { force: true, recursive: true, maxRetries: 5 });
- } catch (e) {
- options.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${dir}: ${e}`);
- }
- }
- options.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`);
- }
- function killAndWait() {
- killProcess();
- return waitForCleanup;
- }
- return { launchedProcess: spawnedProcess, gracefullyClose, kill: killAndWait };
-}
-function envArrayToObject(env) {
- const result2 = {};
- for (const { name, value: value2 } of env)
- result2[name] = value2;
- return result2;
-}
-var childProcess, import_fs6, readline, gracefullyCloseSet, killSet, sigintHandlerCalled, installedHandlers, processHandlers;
-var init_processLauncher = __esm({
- "packages/utils/processLauncher.ts"() {
- "use strict";
- childProcess = __toESM(require("child_process"));
- import_fs6 = __toESM(require("fs"));
- readline = __toESM(require("readline"));
- init_fileUtils();
- init_debug();
- gracefullyCloseSet = /* @__PURE__ */ new Set();
- killSet = /* @__PURE__ */ new Set();
- sigintHandlerCalled = false;
- installedHandlers = /* @__PURE__ */ new Set();
- processHandlers = {
- exit: exitHandler,
- SIGINT: sigintHandler,
- SIGTERM: sigtermHandler,
- SIGHUP: sighupHandler
- };
- }
-});
-
-// packages/utils/profiler.ts
-async function startProfiling() {
- if (!profileDir)
- return;
- session = new (require("inspector")).Session();
- session.connect();
- await new Promise((f) => {
- session.post("Profiler.enable", () => {
- session.post("Profiler.start", f);
- });
- });
-}
-async function stopProfiling(profileName) {
- if (!profileDir)
- return;
- await new Promise((f) => session.post("Profiler.stop", (err, { profile }) => {
- if (!err) {
- import_fs7.default.mkdirSync(profileDir, { recursive: true });
- import_fs7.default.writeFileSync(import_path5.default.join(profileDir, profileName + ".json"), JSON.stringify(profile));
- }
- f();
- }));
-}
-var import_fs7, import_path5, profileDir, session;
-var init_profiler = __esm({
- "packages/utils/profiler.ts"() {
- "use strict";
- import_fs7 = __toESM(require("fs"));
- import_path5 = __toESM(require("path"));
- profileDir = process.env.PWTEST_PROFILE_DIR || "";
- }
-});
-
-// packages/utils/serializedFS.ts
-var import_fs8, yazl, APPEND_CHUNK_SIZE, SerializedFS;
-var init_serializedFS = __esm({
- "packages/utils/serializedFS.ts"() {
- "use strict";
- import_fs8 = __toESM(require("fs"));
- init_manualPromise();
- yazl = require("./utilsBundle").yazl;
- APPEND_CHUNK_SIZE = 64 * 1024;
- SerializedFS = class {
- constructor() {
- this._buffers = /* @__PURE__ */ new Map();
- this._operations = [];
- this._operationsDone = new ManualPromise();
- this._operationsDone.resolve();
- }
- mkdir(dir) {
- this._appendOperation({ op: "mkdir", dir });
- }
- writeFile(file, content, skipIfExists) {
- this._buffers.delete(file);
- this._appendOperation({ op: "writeFile", file, content, skipIfExists });
- }
- appendFile(file, text2, flush) {
- if (!this._buffers.has(file))
- this._buffers.set(file, []);
- const buffer = this._buffers.get(file);
- buffer.push(text2);
- let size = 0;
- for (const chunk of buffer)
- size += chunk.length;
- if (flush || size >= APPEND_CHUNK_SIZE)
- this._flushFile(file);
- }
- _flushFile(file) {
- const buffer = this._buffers.get(file);
- if (buffer === void 0)
- return;
- const content = buffer.join("");
- this._buffers.delete(file);
- this._appendOperation({ op: "appendFile", file, content });
- }
- copyFile(from, to) {
- this._flushFile(from);
- this._buffers.delete(to);
- this._appendOperation({ op: "copyFile", from, to });
- }
- async syncAndGetError() {
- for (const file of this._buffers.keys())
- this._flushFile(file);
- await this._operationsDone;
- return this._error;
- }
- zip(entries, zipFileName) {
- for (const file of this._buffers.keys())
- this._flushFile(file);
- this._appendOperation({ op: "zip", entries, zipFileName });
- }
- // This method serializes all writes to the trace.
- _appendOperation(op) {
- const last = this._operations[this._operations.length - 1];
- if (last?.op === "appendFile" && op.op === "appendFile" && last.file === op.file && last.content.length < APPEND_CHUNK_SIZE) {
- last.content += op.content;
- return;
- }
- this._operations.push(op);
- if (this._operationsDone.isDone())
- this._performOperations();
- }
- async _performOperations() {
- this._operationsDone = new ManualPromise();
- while (this._operations.length) {
- const op = this._operations.shift();
- if (this._error)
- continue;
- try {
- await this._performOperation(op);
- } catch (e) {
- this._error = e;
- }
- }
- this._operationsDone.resolve();
- }
- async _performOperation(op) {
- switch (op.op) {
- case "mkdir": {
- await import_fs8.default.promises.mkdir(op.dir, { recursive: true });
- return;
- }
- case "writeFile": {
- if (op.skipIfExists)
- await import_fs8.default.promises.writeFile(op.file, op.content, { flag: "wx" }).catch(() => {
- });
- else
- await import_fs8.default.promises.writeFile(op.file, op.content);
- return;
- }
- case "copyFile": {
- await import_fs8.default.promises.copyFile(op.from, op.to);
- return;
- }
- case "appendFile": {
- await import_fs8.default.promises.appendFile(op.file, op.content);
- return;
- }
- case "zip": {
- const zipFile = new yazl.ZipFile();
- const result2 = new ManualPromise();
- zipFile.on("error", (error) => result2.reject(error));
- for (const entry of op.entries)
- zipFile.addFile(entry.value, entry.name);
- zipFile.end();
- zipFile.outputStream.pipe(import_fs8.default.createWriteStream(op.zipFileName)).on("close", () => result2.resolve()).on("error", (error) => result2.reject(error));
- await result2;
- return;
- }
- }
- }
- };
- }
-});
-
-// packages/utils/socksProxy.ts
-function hexToNumber(hex) {
- return [...hex].reduce((value2, digit2) => {
- const code = digit2.charCodeAt(0);
- if (code >= 48 && code <= 57)
- return value2 + code;
- if (code >= 97 && code <= 102)
- return value2 + (code - 97) + 10;
- if (code >= 65 && code <= 70)
- return value2 + (code - 65) + 10;
- throw new Error("Invalid IPv6 token " + hex);
- }, 0);
-}
-function ipToSocksAddress(address) {
- const ipv4Mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
- if (ipv4Mapped)
- address = ipv4Mapped[1];
- if (import_net2.default.isIPv4(address)) {
- return [
- 1,
- // IPv4
- ...address.split(".", 4).map((t) => +t & 255)
- // Address
- ];
- }
- if (import_net2.default.isIPv6(address)) {
- const result2 = [4];
- const tokens = address.split(":", 8);
- while (tokens.length < 8)
- tokens.unshift("");
- for (const token of tokens) {
- const value2 = hexToNumber(token);
- result2.push(value2 >> 8 & 255, value2 & 255);
- }
- return result2;
- }
- throw new Error("Only IPv4 and IPv6 addresses are supported");
-}
-function starMatchToRegex(pattern) {
- const source11 = pattern.split("*").map((s) => {
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- }).join(".*");
- return new RegExp("^" + source11 + "$");
-}
-function parsePattern(pattern) {
- if (!pattern)
- return () => false;
- const matchers = pattern.split(",").map((token) => {
- const match = token.match(/^(.*?)(?::(\d+))?$/);
- if (!match)
- throw new Error(`Unsupported token "${token}" in pattern "${pattern}"`);
- const tokenPort = match[2] ? +match[2] : void 0;
- const portMatches = (port) => tokenPort === void 0 || tokenPort === port;
- let tokenHost = match[1];
- if (tokenHost === "") {
- return (host, port) => {
- if (!portMatches(port))
- return false;
- return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
- };
- }
- if (tokenHost === "*")
- return (host, port) => portMatches(port);
- if (import_net2.default.isIPv4(tokenHost) || import_net2.default.isIPv6(tokenHost))
- return (host, port) => host === tokenHost && portMatches(port);
- if (tokenHost[0] === ".")
- tokenHost = "*" + tokenHost;
- const tokenRegex = starMatchToRegex(tokenHost);
- return (host, port) => {
- if (!portMatches(port))
- return false;
- if (import_net2.default.isIPv4(host) || import_net2.default.isIPv6(host))
- return false;
- return !!host.match(tokenRegex);
- };
- });
- return (host, port) => matchers.some((matcher) => matcher(host, port));
-}
-var import_events2, import_net2, SocksConnection, SocksProxy, SocksProxyHandler;
-var init_socksProxy = __esm({
- "packages/utils/socksProxy.ts"() {
- "use strict";
- import_events2 = __toESM(require("events"));
- import_net2 = __toESM(require("net"));
- init_assert();
- init_crypto();
- init_debugLogger();
- init_happyEyeballs();
- SocksConnection = class {
- constructor(uid, socket, client) {
- this._buffer = Buffer.from([]);
- this._offset = 0;
- this._fence = 0;
- this._uid = uid;
- this._socket = socket;
- this._client = client;
- this._boundOnData = this._onData.bind(this);
- socket.on("data", this._boundOnData);
- socket.on("close", () => this._onClose());
- socket.on("end", () => this._onClose());
- socket.on("error", () => this._onClose());
- this._run().catch(() => this._socket.end());
- }
- async _run() {
- assert(await this._authenticate());
- const { command, host, port } = await this._parseRequest();
- if (command !== 1 /* CONNECT */) {
- this._writeBytes(Buffer.from([
- 5,
- 7 /* CommandNotSupported */,
- 0,
- // RSV
- 1,
- // IPv4
- 0,
- 0,
- 0,
- 0,
- // Address
- 0,
- 0
- // Port
- ]));
- return;
- }
- this._socket.off("data", this._boundOnData);
- this._client.onSocketRequested({ uid: this._uid, host, port });
- }
- async _authenticate() {
- const version3 = await this._readByte();
- assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3);
- const nMethods = await this._readByte();
- assert(nMethods, "No authentication methods specified");
- const methods = await this._readBytes(nMethods);
- for (const method of methods) {
- if (method === 0) {
- this._writeBytes(Buffer.from([version3, method]));
- return true;
- }
- }
- this._writeBytes(Buffer.from([version3, 255 /* NO_ACCEPTABLE_METHODS */]));
- return false;
- }
- async _parseRequest() {
- const version3 = await this._readByte();
- assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3);
- const command = await this._readByte();
- await this._readByte();
- const addressType = await this._readByte();
- let host = "";
- switch (addressType) {
- case 1 /* IPv4 */:
- host = (await this._readBytes(4)).join(".");
- break;
- case 3 /* FqName */:
- const length = await this._readByte();
- host = (await this._readBytes(length)).toString();
- break;
- case 4 /* IPv6 */:
- const bytes = await this._readBytes(16);
- const tokens = [];
- for (let i = 0; i < 8; ++i)
- tokens.push(bytes.readUInt16BE(i * 2).toString(16));
- host = tokens.join(":");
- break;
- }
- const port = (await this._readBytes(2)).readUInt16BE(0);
- this._buffer = Buffer.from([]);
- this._offset = 0;
- this._fence = 0;
- return {
- command,
- host,
- port
- };
- }
- async _readByte() {
- const buffer = await this._readBytes(1);
- return buffer[0];
- }
- async _readBytes(length) {
- this._fence = this._offset + length;
- if (!this._buffer || this._buffer.length < this._fence)
- await new Promise((f) => this._fenceCallback = f);
- this._offset += length;
- return this._buffer.slice(this._offset - length, this._offset);
- }
- _writeBytes(buffer) {
- if (this._socket.writable)
- this._socket.write(buffer);
- }
- _onClose() {
- this._client.onSocketClosed({ uid: this._uid });
- }
- _onData(buffer) {
- this._buffer = Buffer.concat([this._buffer, buffer]);
- if (this._fenceCallback && this._buffer.length >= this._fence) {
- const callback = this._fenceCallback;
- this._fenceCallback = void 0;
- callback();
- }
- }
- socketConnected(host, port) {
- this._writeBytes(Buffer.from([
- 5,
- 0 /* Succeeded */,
- 0,
- // RSV
- ...ipToSocksAddress(host),
- // ATYP, Address
- port >> 8,
- port & 255
- // Port
- ]));
- this._socket.on("data", (data) => this._client.onSocketData({ uid: this._uid, data }));
- }
- socketFailed(errorCode) {
- const buffer = Buffer.from([
- 5,
- 0,
- 0,
- // RSV
- ...ipToSocksAddress("0.0.0.0"),
- // ATYP, Address
- 0,
- 0
- // Port
- ]);
- switch (errorCode) {
- case "ENOENT":
- case "ENOTFOUND":
- case "ETIMEDOUT":
- case "EHOSTUNREACH":
- buffer[1] = 4 /* HostUnreachable */;
- break;
- case "ENETUNREACH":
- buffer[1] = 3 /* NetworkUnreachable */;
- break;
- case "ECONNREFUSED":
- buffer[1] = 5 /* ConnectionRefused */;
- break;
- case "ERULESET":
- buffer[1] = 2 /* NotAllowedByRuleSet */;
- break;
- }
- this._writeBytes(buffer);
- this._socket.end();
- }
- sendData(data) {
- this._socket.write(data);
- }
- end() {
- this._socket.end();
- }
- error(error) {
- this._socket.destroy(new Error(error));
- }
- };
- SocksProxy = class _SocksProxy extends import_events2.default {
- constructor() {
- super();
- this._connections = /* @__PURE__ */ new Map();
- this._sockets = /* @__PURE__ */ new Set();
- this._closed = false;
- this._patternMatcher = () => false;
- this._directSockets = /* @__PURE__ */ new Map();
- this._server = new import_net2.default.Server((socket) => {
- const uid = createGuid();
- const connection = new SocksConnection(uid, socket, this);
- this._connections.set(uid, connection);
- });
- this._server.on("connection", (socket) => {
- if (this._closed) {
- socket.destroy();
- return;
- }
- this._sockets.add(socket);
- socket.once("close", () => this._sockets.delete(socket));
- });
- }
- static {
- this.Events = {
- SocksRequested: "socksRequested",
- SocksData: "socksData",
- SocksClosed: "socksClosed"
- };
- }
- setPattern(pattern) {
- try {
- this._patternMatcher = parsePattern(pattern);
- } catch (e) {
- this._patternMatcher = () => false;
- }
- }
- async _handleDirect(request2) {
- try {
- const socket = await createSocket(request2.host, request2.port);
- socket.on("data", (data) => this._connections.get(request2.uid)?.sendData(data));
- socket.on("error", (error) => {
- this._connections.get(request2.uid)?.error(error.message);
- this._directSockets.delete(request2.uid);
- });
- socket.on("end", () => {
- this._connections.get(request2.uid)?.end();
- this._directSockets.delete(request2.uid);
- });
- const localAddress = socket.localAddress;
- const localPort = socket.localPort;
- this._directSockets.set(request2.uid, socket);
- this._connections.get(request2.uid)?.socketConnected(localAddress, localPort);
- } catch (error) {
- this._connections.get(request2.uid)?.socketFailed(error.code);
- }
- }
- port() {
- return this._port;
- }
- async listen(port, hostname) {
- return new Promise((f) => {
- this._server.listen(port, hostname, () => {
- const port2 = this._server.address().port;
- this._port = port2;
- f(port2);
- });
- });
- }
- async close() {
- if (this._closed)
- return;
- this._closed = true;
- for (const socket of this._sockets)
- socket.destroy();
- this._sockets.clear();
- await new Promise((f) => this._server.close(f));
- }
- onSocketRequested(payload) {
- if (!this._patternMatcher(payload.host, payload.port)) {
- this._handleDirect(payload);
- return;
- }
- this.emit(_SocksProxy.Events.SocksRequested, payload);
- }
- onSocketData(payload) {
- const direct = this._directSockets.get(payload.uid);
- if (direct) {
- direct.write(payload.data);
- return;
- }
- this.emit(_SocksProxy.Events.SocksData, payload);
- }
- onSocketClosed(payload) {
- const direct = this._directSockets.get(payload.uid);
- if (direct) {
- direct.destroy();
- this._directSockets.delete(payload.uid);
- return;
- }
- this.emit(_SocksProxy.Events.SocksClosed, payload);
- }
- socketConnected({ uid, host, port }) {
- this._connections.get(uid)?.socketConnected(host, port);
- }
- socketFailed({ uid, errorCode }) {
- this._connections.get(uid)?.socketFailed(errorCode);
- }
- sendSocketData({ uid, data }) {
- this._connections.get(uid)?.sendData(data);
- }
- sendSocketEnd({ uid }) {
- this._connections.get(uid)?.end();
- }
- sendSocketError({ uid, error }) {
- this._connections.get(uid)?.error(error);
- }
- };
- SocksProxyHandler = class _SocksProxyHandler extends import_events2.default {
- constructor(pattern, redirectPortForTest) {
- super();
- this._sockets = /* @__PURE__ */ new Map();
- this._patternMatcher = () => false;
- this._patternMatcher = parsePattern(pattern);
- this._redirectPortForTest = redirectPortForTest;
- }
- static {
- this.Events = {
- SocksConnected: "socksConnected",
- SocksData: "socksData",
- SocksError: "socksError",
- SocksFailed: "socksFailed",
- SocksEnd: "socksEnd"
- };
- }
- cleanup() {
- for (const uid of this._sockets.keys())
- this.socketClosed({ uid });
- }
- async socketRequested({ uid, host, port }) {
- debugLogger.log("socks", `[${uid}] => request ${host}:${port}`);
- if (!this._patternMatcher(host, port)) {
- const payload = { uid, errorCode: "ERULESET" };
- debugLogger.log("socks", `[${uid}] <= pattern error ${payload.errorCode}`);
- this.emit(_SocksProxyHandler.Events.SocksFailed, payload);
- return;
- }
- if (host === "local.playwright")
- host = "localhost";
- try {
- if (this._redirectPortForTest)
- port = this._redirectPortForTest;
- const socket = await createSocket(host, port);
- socket.on("data", (data) => {
- const payload2 = { uid, data };
- this.emit(_SocksProxyHandler.Events.SocksData, payload2);
- });
- socket.on("error", (error) => {
- const payload2 = { uid, error: error.message };
- debugLogger.log("socks", `[${uid}] <= network socket error ${payload2.error}`);
- this.emit(_SocksProxyHandler.Events.SocksError, payload2);
- this._sockets.delete(uid);
- });
- socket.on("end", () => {
- const payload2 = { uid };
- debugLogger.log("socks", `[${uid}] <= network socket closed`);
- this.emit(_SocksProxyHandler.Events.SocksEnd, payload2);
- this._sockets.delete(uid);
- });
- const localAddress = socket.localAddress;
- const localPort = socket.localPort;
- this._sockets.set(uid, socket);
- const payload = { uid, host: localAddress, port: localPort };
- debugLogger.log("socks", `[${uid}] <= connected to network ${payload.host}:${payload.port}`);
- this.emit(_SocksProxyHandler.Events.SocksConnected, payload);
- } catch (error) {
- const payload = { uid, errorCode: error.code };
- debugLogger.log("socks", `[${uid}] <= connect error ${payload.errorCode}`);
- this.emit(_SocksProxyHandler.Events.SocksFailed, payload);
- }
- }
- sendSocketData({ uid, data }) {
- this._sockets.get(uid)?.write(data);
- }
- socketClosed({ uid }) {
- debugLogger.log("socks", `[${uid}] <= browser socket closed`);
- this._sockets.get(uid)?.destroy();
- this._sockets.delete(uid);
- }
- };
- }
-});
-
-// packages/utils/spawnAsync.ts
-function spawnAsync(cmd, args, options = {}) {
- const process2 = (0, import_child_process.spawn)(cmd, args, Object.assign({ windowsHide: true }, options));
- return new Promise((resolve) => {
- let stdout = "";
- let stderr = "";
- if (process2.stdout)
- process2.stdout.on("data", (data) => stdout += data.toString());
- if (process2.stderr)
- process2.stderr.on("data", (data) => stderr += data.toString());
- process2.on("close", (code) => resolve({ stdout, stderr, code }));
- process2.on("error", (error) => resolve({ stdout, stderr, code: 0, error }));
- });
-}
-var import_child_process;
-var init_spawnAsync = __esm({
- "packages/utils/spawnAsync.ts"() {
- "use strict";
- import_child_process = require("child_process");
- }
-});
-
-// packages/utils/stringWidth.ts
-function characterWidth(c) {
- return getEastAsianWidth.eastAsianWidth(c.codePointAt(0));
-}
-function stringWidth(v) {
- let width = 0;
- for (const { segment } of new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v))
- width += characterWidth(segment);
- return width;
-}
-function suffixOfWidth(v, width) {
- const segments = [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)];
- let suffixBegin = v.length;
- for (const { segment, index } of segments.reverse()) {
- const segmentWidth = stringWidth(segment);
- if (segmentWidth > width)
- break;
- width -= segmentWidth;
- suffixBegin = index;
- }
- return v.substring(suffixBegin);
-}
-function fitToWidth(line, width, prefix) {
- const prefixLength = prefix ? stripAnsiEscapes(prefix).length : 0;
- width -= prefixLength;
- if (stringWidth(line) <= width)
- return line;
- const parts = line.split(ansiRegex);
- const taken = [];
- for (let i = parts.length - 1; i >= 0; i--) {
- if (i % 2) {
- taken.push(parts[i]);
- } else {
- let part = suffixOfWidth(parts[i], width);
- const wasTruncated = part.length < parts[i].length;
- if (wasTruncated && parts[i].length > 0) {
- part = "\u2026" + suffixOfWidth(parts[i], width - 1);
- }
- taken.push(part);
- width -= stringWidth(part);
- }
- }
- return taken.reverse().join("");
-}
-var getEastAsianWidth;
-var init_stringWidth = __esm({
- "packages/utils/stringWidth.ts"() {
- "use strict";
- init_stringUtils();
- getEastAsianWidth = require("./utilsBundle").getEastAsianWidth;
- }
-});
-
-// packages/utils/task.ts
-function makeWaitForNextTask() {
- if (process.versions.electron)
- return (callback) => setTimeout(callback, 0);
- if (parseInt(process.versions.node, 10) >= 11)
- return setImmediate;
- let spinning = false;
- const callbacks = [];
- const loop = () => {
- const callback = callbacks.shift();
- if (!callback) {
- spinning = false;
- return;
- }
- setImmediate(loop);
- callback();
- };
- return (callback) => {
- callbacks.push(callback);
- if (!spinning) {
- spinning = true;
- setImmediate(loop);
- }
- };
-}
-var init_task = __esm({
- "packages/utils/task.ts"() {
- "use strict";
- }
-});
-
-// packages/utils/wsServer.ts
-var wsServer2, lastConnectionId, kConnectionSymbol, perMessageDeflate, WSServer;
-var init_wsServer = __esm({
- "packages/utils/wsServer.ts"() {
- "use strict";
- init_httpServer();
- init_network();
- init_debugLogger();
- ({ wsServer: wsServer2 } = require("./utilsBundle"));
- lastConnectionId = 0;
- kConnectionSymbol = Symbol("kConnection");
- perMessageDeflate = {
- serverNoContextTakeover: true,
- zlibDeflateOptions: {
- level: 3
- },
- zlibInflateOptions: {
- chunkSize: 10 * 1024
- },
- threshold: 10 * 1024
- };
- WSServer = class {
- constructor(delegate) {
- // Allowed Host headers for HTTP requests. null disables the check (server bound to a public address).
- this._allowedHosts = null;
- this._delegate = delegate;
- }
- async listen(port = 0, hostname, path59) {
- debugLogger.log("server", `Server started at ${/* @__PURE__ */ new Date()}`);
- hostname ??= "localhost";
- const server = createHttpServer((request2, response2) => this._onRequest(request2, response2));
- server.on("error", (error) => debugLogger.log("server", String(error)));
- this.server = server;
- const wsEndpoint = await new Promise((resolve, reject) => {
- server.listen(port, hostname, () => {
- const address = server.address();
- if (!address) {
- reject(new Error("Could not bind server socket"));
- return;
- }
- if (typeof address === "string") {
- resolve(`${address}${path59}`);
- return;
- }
- this._allowedHosts = computeAllowedHosts(hostname, address.address);
- resolve(`ws://${urlHostFromAddress(address)}:${address.port}${path59}`);
- }).on("error", reject);
- });
- debugLogger.log("server", "Listening at " + wsEndpoint);
- this._wsServer = new wsServer2({
- noServer: true,
- perMessageDeflate
- });
- this._wsServer.on("headers", (headers) => this._delegate.onHeaders(headers));
- server.on("upgrade", (request2, socket, head) => {
- const pathname = new URL("http://localhost" + request2.url).pathname;
- if (pathname !== path59) {
- socket.write(`HTTP/${request2.httpVersion} 400 Bad Request\r
-\r
-`);
- socket.destroy();
- return;
- }
- if (this._allowedHosts && !this._isAllowedOrigin(request2.headers.origin)) {
- socket.write(`HTTP/${request2.httpVersion} 403 Forbidden\r
-\r
-`);
- socket.destroy();
- return;
- }
- const upgradeResult = this._delegate.onUpgrade(request2, socket);
- if (upgradeResult) {
- socket.write(upgradeResult.error);
- socket.destroy();
- return;
- }
- this._wsServer.handleUpgrade(request2, socket, head, (ws4) => this._wsServer.emit("connection", ws4, request2));
- });
- this._wsServer.on("connection", (ws4, request2) => {
- debugLogger.log("server", "Connected client ws.extension=" + ws4.extensions);
- const url2 = new URL("http://localhost" + (request2.url || ""));
- const id = String(++lastConnectionId);
- debugLogger.log("server", `[${id}] serving connection: ${request2.url}`);
- const connection = this._delegate.onConnection(request2, url2, ws4, id);
- ws4[kConnectionSymbol] = connection;
- });
- return wsEndpoint;
- }
- _onRequest(request2, response2) {
- if (this._allowedHosts) {
- const host = request2.headers.host?.toLowerCase();
- const hostname = host ? hostnameFromHostHeader(host) : void 0;
- if (!hostname || !this._allowedHosts.has(hostname)) {
- response2.statusCode = 403;
- response2.end();
- return;
- }
- }
- this._delegate.onRequest(request2, response2);
- }
- _isAllowedOrigin(origin) {
- if (!origin)
- return true;
- try {
- const hostname = new URL(origin).hostname.toLowerCase();
- const bracketed = hostname.includes(":") ? `[${hostname}]` : hostname;
- return this._allowedHosts.has(hostname) || this._allowedHosts.has(bracketed);
- } catch {
- return false;
- }
- }
- async close() {
- const server = this._wsServer;
- if (!server)
- return;
- debugLogger.log("server", "closing websocket server");
- const waitForClose = new Promise((f) => server.close(f));
- await Promise.all(Array.from(server.clients).map(async (ws4) => {
- const connection = ws4[kConnectionSymbol];
- if (connection)
- await connection.close();
- try {
- ws4.terminate();
- } catch (e) {
- }
- }));
- await waitForClose;
- debugLogger.log("server", "closing http server");
- if (this.server)
- await new Promise((f) => this.server.close(f));
- this._wsServer = void 0;
- this.server = void 0;
- debugLogger.log("server", "closed server");
- }
- };
- }
-});
-
-// packages/utils/zipFile.ts
-var yauzl, ZipFile;
-var init_zipFile = __esm({
- "packages/utils/zipFile.ts"() {
- "use strict";
- yauzl = require("./utilsBundle").yauzl;
- ZipFile = class {
- constructor(fileName) {
- this._entries = /* @__PURE__ */ new Map();
- this._fileName = fileName;
- this._openedPromise = this._open();
- }
- async _open() {
- await new Promise((fulfill, reject) => {
- yauzl.open(this._fileName, { autoClose: false }, (e, z31) => {
- if (e) {
- reject(e);
- return;
- }
- this._zipFile = z31;
- this._zipFile.on("entry", (entry) => {
- this._entries.set(entry.fileName, entry);
- });
- this._zipFile.on("end", fulfill);
- });
- });
- }
- async entries() {
- await this._openedPromise;
- return [...this._entries.keys()];
- }
- async read(entryPath) {
- await this._openedPromise;
- const entry = this._entries.get(entryPath);
- if (!entry)
- throw new Error(`${entryPath} not found in file ${this._fileName}`);
- return new Promise((resolve, reject) => {
- this._zipFile.openReadStream(entry, (error, readStream) => {
- if (error || !readStream) {
- reject(error || "Entry not found");
- return;
- }
- const buffers = [];
- readStream.on("data", (data) => buffers.push(data));
- readStream.on("end", () => resolve(Buffer.concat(buffers)));
- });
- });
- }
- close() {
- this._zipFile?.close();
- }
- };
- }
-});
-
-// packages/utils/third_party/extractZip.ts
-async function extractZip(zipPath, opts) {
- debug2("creating target directory", opts.dir);
- if (!import_path6.default.isAbsolute(opts.dir))
- throw new Error("Target directory is expected to be absolute");
- await import_fs9.promises.mkdir(opts.dir, { recursive: true });
- opts.dir = await import_fs9.promises.realpath(opts.dir);
- return new Extractor(zipPath, opts).extract();
-}
-var import_fs9, import_path6, import_stream2, import_util, debugPkg, getStream, yauzl2, debug2, openZip, pipeline2, Extractor;
-var init_extractZip = __esm({
- "packages/utils/third_party/extractZip.ts"() {
- "use strict";
- import_fs9 = require("fs");
- import_path6 = __toESM(require("path"));
- import_stream2 = __toESM(require("stream"));
- import_util = require("util");
- debugPkg = require("./utilsBundle").debug;
- getStream = require("./utilsBundle").getStream;
- yauzl2 = require("./utilsBundle").yauzl;
- debug2 = debugPkg("extract-zip");
- openZip = (0, import_util.promisify)(yauzl2.open);
- pipeline2 = (0, import_util.promisify)(import_stream2.default.pipeline);
- Extractor = class {
- constructor(zipPath, opts) {
- this.canceled = false;
- this.zipPath = zipPath;
- this.opts = opts;
- }
- async extract() {
- debug2("opening", this.zipPath, "with opts", this.opts);
- this.zipfile = await openZip(this.zipPath, { lazyEntries: true });
- this.canceled = false;
- return new Promise((resolve, reject) => {
- this.zipfile.on("error", (err) => {
- this.canceled = true;
- reject(err);
- });
- this.zipfile.readEntry();
- this.zipfile.on("close", () => {
- if (!this.canceled) {
- debug2("zip extraction complete");
- resolve();
- }
- });
- this.zipfile.on("entry", async (entry) => {
- if (this.canceled) {
- debug2("skipping entry", entry.fileName, { cancelled: this.canceled });
- return;
- }
- debug2("zipfile entry", entry.fileName);
- if (entry.fileName.startsWith("__MACOSX/")) {
- this.zipfile.readEntry();
- return;
- }
- const destDir = import_path6.default.dirname(import_path6.default.join(this.opts.dir, entry.fileName));
- try {
- await import_fs9.promises.mkdir(destDir, { recursive: true });
- const canonicalDestDir = await import_fs9.promises.realpath(destDir);
- const relativeDestDir = import_path6.default.relative(this.opts.dir, canonicalDestDir);
- if (relativeDestDir.split(import_path6.default.sep).includes(".."))
- throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`);
- await this.extractEntry(entry);
- debug2("finished processing", entry.fileName);
- this.zipfile.readEntry();
- } catch (err) {
- this.canceled = true;
- this.zipfile.close();
- reject(err);
- }
- });
- });
- }
- async extractEntry(entry) {
- if (this.canceled) {
- debug2("skipping entry extraction", entry.fileName, { cancelled: this.canceled });
- return;
- }
- if (this.opts.onEntry)
- this.opts.onEntry(entry, this.zipfile);
- const dest = import_path6.default.join(this.opts.dir, entry.fileName);
- const mode = entry.externalFileAttributes >> 16 & 65535;
- const IFMT = 61440;
- const IFDIR = 16384;
- const IFLNK = 40960;
- const symlink = (mode & IFMT) === IFLNK;
- let isDir = (mode & IFMT) === IFDIR;
- if (!isDir && entry.fileName.endsWith("/"))
- isDir = true;
- const madeBy = entry.versionMadeBy >> 8;
- if (!isDir)
- isDir = madeBy === 0 && entry.externalFileAttributes === 16;
- debug2("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink });
- const procMode = this.getExtractedMode(mode, isDir) & 511;
- const destDir = isDir ? dest : import_path6.default.dirname(dest);
- const mkdirOptions = { recursive: true };
- if (isDir)
- mkdirOptions.mode = procMode;
- debug2("mkdir", { dir: destDir, ...mkdirOptions });
- await import_fs9.promises.mkdir(destDir, mkdirOptions);
- if (isDir)
- return;
- debug2("opening read stream", dest);
- const readStream = await (0, import_util.promisify)(this.zipfile.openReadStream.bind(this.zipfile))(entry);
- if (symlink) {
- const link = await getStream(readStream);
- debug2("creating symlink", link, dest);
- await import_fs9.promises.symlink(link, dest);
- } else {
- await pipeline2(readStream, (0, import_fs9.createWriteStream)(dest, { mode: procMode }));
- }
- }
- getExtractedMode(entryMode, isDir) {
- let mode = entryMode;
- if (mode === 0) {
- if (isDir) {
- if (this.opts.defaultDirMode)
- mode = Number(this.opts.defaultDirMode);
- if (!mode)
- mode = 493;
- } else {
- if (this.opts.defaultFileMode)
- mode = Number(this.opts.defaultFileMode);
- if (!mode)
- mode = 420;
- }
- }
- return mode;
- }
- };
- }
-});
-
-// packages/utils/third_party/lockfile.ts
-function probe(file, fs61, callback) {
- const cachedPrecision = fs61[cacheSymbol];
- if (cachedPrecision) {
- return fs61.stat(file, (err, stat) => {
- if (err)
- return callback(err);
- callback(null, stat.mtime, cachedPrecision);
- });
- }
- const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
- fs61.utimes(file, mtime, mtime, (err) => {
- if (err)
- return callback(err);
- fs61.stat(file, (err2, stat) => {
- if (err2)
- return callback(err2);
- const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
- Object.defineProperty(fs61, cacheSymbol, { value: precision });
- callback(null, stat.mtime, precision);
- });
- });
-}
-function getMtime(precision) {
- let now = Date.now();
- if (precision === "s")
- now = Math.ceil(now / 1e3) * 1e3;
- return new Date(now);
-}
-function getLockFile(file, options) {
- return options.lockfilePath || `${file}.lock`;
-}
-function resolveCanonicalPath(file, options, callback) {
- if (!options.realpath)
- return callback(null, import_path7.default.resolve(file));
- options.fs.realpath(file, callback);
-}
-function acquireLock(file, options, callback) {
- const lockfilePath = getLockFile(file, options);
- options.fs.mkdir(lockfilePath, (err) => {
- if (!err) {
- return probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision) => {
- if (err2) {
- options.fs.rmdir(lockfilePath, () => {
- });
- return callback(err2);
- }
- callback(null, mtime, mtimePrecision);
- });
- }
- if (err.code !== "EEXIST")
- return callback(err);
- if (options.stale <= 0)
- return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
- options.fs.stat(lockfilePath, (err2, stat) => {
- if (err2) {
- if (err2.code === "ENOENT")
- return acquireLock(file, { ...options, stale: 0 }, callback);
- return callback(err2);
- }
- if (!isLockStale(stat, options))
- return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
- removeLock(file, options, (err3) => {
- if (err3)
- return callback(err3);
- acquireLock(file, { ...options, stale: 0 }, callback);
- });
- });
- });
-}
-function isLockStale(stat, options) {
- return stat.mtime.getTime() < Date.now() - options.stale;
-}
-function removeLock(file, options, callback) {
- options.fs.rmdir(getLockFile(file, options), (err) => {
- if (err && err.code !== "ENOENT")
- return callback(err);
- callback(null);
- });
-}
-function updateLock(file, options) {
- const lock2 = locks[file];
- if (lock2.updateTimeout)
- return;
- lock2.updateDelay = lock2.updateDelay || options.update;
- lock2.updateTimeout = setTimeout(() => {
- lock2.updateTimeout = null;
- options.fs.stat(lock2.lockfilePath, (err, stat) => {
- const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
- if (err) {
- if (err.code === "ENOENT" || isOverThreshold)
- return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
- lock2.updateDelay = 1e3;
- return updateLock(file, options);
- }
- const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
- if (!isMtimeOurs) {
- return setLockAsCompromised(
- file,
- lock2,
- Object.assign(
- new Error("Unable to update lock within the stale threshold"),
- { code: "ECOMPROMISED" }
- )
- );
- }
- const mtime = getMtime(lock2.mtimePrecision);
- options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
- const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
- if (lock2.released)
- return;
- if (err2) {
- if (err2.code === "ENOENT" || isOverThreshold2)
- return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
- lock2.updateDelay = 1e3;
- return updateLock(file, options);
- }
- lock2.mtime = mtime;
- lock2.lastUpdate = Date.now();
- lock2.updateDelay = null;
- updateLock(file, options);
- });
- });
- }, lock2.updateDelay);
- if (lock2.updateTimeout && lock2.updateTimeout.unref)
- lock2.updateTimeout.unref();
-}
-function setLockAsCompromised(file, lock2, err) {
- lock2.released = true;
- if (lock2.updateTimeout)
- clearTimeout(lock2.updateTimeout);
- if (locks[file] === lock2)
- delete locks[file];
- lock2.options.onCompromised(err);
-}
-function lockImpl(file, options, callback) {
- const resolvedOptions = {
- stale: 1e4,
- update: null,
- realpath: true,
- retries: 0,
- fs: gracefulFs,
- onCompromised: (err) => {
- throw err;
- },
- ...options
- };
- resolvedOptions.retries = resolvedOptions.retries || 0;
- resolvedOptions.retries = typeof resolvedOptions.retries === "number" ? { retries: resolvedOptions.retries } : resolvedOptions.retries;
- resolvedOptions.stale = Math.max(resolvedOptions.stale || 0, 2e3);
- resolvedOptions.update = resolvedOptions.update === null || resolvedOptions.update === void 0 ? resolvedOptions.stale / 2 : resolvedOptions.update || 0;
- resolvedOptions.update = Math.max(Math.min(resolvedOptions.update, resolvedOptions.stale / 2), 1e3);
- resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => {
- if (err)
- return callback(err);
- const canonicalFile = resolvedFile;
- const operation = retry.operation(resolvedOptions.retries);
- operation.attempt(() => {
- acquireLock(canonicalFile, resolvedOptions, (err2, mtime, mtimePrecision) => {
- if (operation.retry(err2 || void 0))
- return;
- if (err2)
- return callback(operation.mainError());
- const lock2 = locks[canonicalFile] = {
- lockfilePath: getLockFile(canonicalFile, resolvedOptions),
- mtime,
- mtimePrecision,
- options: resolvedOptions,
- lastUpdate: Date.now()
- };
- updateLock(canonicalFile, resolvedOptions);
- callback(null, (releasedCallback) => {
- if (lock2.released) {
- return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
- }
- unlock(canonicalFile, { ...resolvedOptions, realpath: false }, releasedCallback || (() => {
- }));
- });
- });
- });
- });
-}
-function unlock(file, options, callback) {
- const resolvedOptions = {
- stale: 1e4,
- update: null,
- realpath: true,
- retries: 0,
- fs: gracefulFs,
- onCompromised: (err) => {
- throw err;
- },
- ...options
- };
- resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => {
- if (err)
- return callback(err);
- const canonicalFile = resolvedFile;
- const lock2 = locks[canonicalFile];
- if (!lock2)
- return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
- if (lock2.updateTimeout)
- clearTimeout(lock2.updateTimeout);
- lock2.released = true;
- delete locks[canonicalFile];
- removeLock(canonicalFile, resolvedOptions, callback);
- });
-}
-function toPromise(method) {
- return (...args) => new Promise((resolve, reject) => {
- args.push((err, result2) => {
- if (err)
- reject(err);
- else
- resolve(result2);
- });
- method(...args);
- });
-}
-function ensureCleanup() {
- if (cleanupInitialized)
- return;
- cleanupInitialized = true;
- onExit(() => {
- for (const file in locks) {
- const options = locks[file].options;
- try {
- options.fs.rmdirSync(getLockFile(file, options));
- } catch (e) {
- }
- }
- });
-}
-async function lock(file, options) {
- ensureCleanup();
- const release = await toPromise(lockImpl)(file, options || {});
- return toPromise(release);
-}
-var import_path7, gracefulFs, retry, onExit, locks, cacheSymbol, cleanupInitialized;
-var init_lockfile = __esm({
- "packages/utils/third_party/lockfile.ts"() {
- "use strict";
- import_path7 = __toESM(require("path"));
- gracefulFs = require("./utilsBundle").gracefulFs;
- retry = require("./utilsBundle").retry;
- onExit = require("./utilsBundle").onExit;
- locks = {};
- cacheSymbol = Symbol();
- cleanupInitialized = false;
- }
-});
-
-// packages/utils/index.ts
-var utils_exports = {};
-__export(utils_exports, {
- FastStats: () => FastStats,
- HttpServer: () => HttpServer,
- ImageChannel: () => ImageChannel,
- NET_DEFAULT_TIMEOUT: () => NET_DEFAULT_TIMEOUT,
- RecentLogsCollector: () => RecentLogsCollector,
- SerializedFS: () => SerializedFS,
- SocksProxy: () => SocksProxy,
- SocksProxyHandler: () => SocksProxyHandler,
- WSServer: () => WSServer,
- ZipFile: () => ZipFile,
- Zone: () => Zone,
- addSuffixToFilePath: () => addSuffixToFilePath,
- blendWithWhite: () => blendWithWhite,
- calculateSha1: () => calculateSha1,
- canAccessFile: () => canAccessFile,
- colorDeltaE94: () => colorDeltaE94,
- compare: () => compare,
- compareBuffersOrStrings: () => compareBuffersOrStrings,
- computeAllowedHosts: () => computeAllowedHosts,
- copyFileAndMakeWritable: () => copyFileAndMakeWritable,
- createGuid: () => createGuid,
- createHttp2Server: () => createHttp2Server,
- createHttpServer: () => createHttpServer,
- createHttpsServer: () => createHttpsServer,
- createProxyAgent: () => createProxyAgent,
- currentZone: () => currentZone,
- debugLogger: () => debugLogger,
- debugMode: () => debugMode,
- decorateServer: () => decorateServer,
- defaultUserDataDirForChannel: () => defaultUserDataDirForChannel,
- emptyZone: () => emptyZone,
- envArrayToObject: () => envArrayToObject,
- eventsHelper: () => eventsHelper,
- existsAsync: () => existsAsync,
- extractZip: () => extractZip,
- fitToWidth: () => fitToWidth,
- generateSelfSignedCertificate: () => generateSelfSignedCertificate,
- getAsBooleanFromENV: () => getAsBooleanFromENV,
- getComparator: () => getComparator,
- getFromENV: () => getFromENV,
- getPackageManager: () => getPackageManager,
- getPackageManagerExecCommand: () => getPackageManagerExecCommand,
- gracefullyCloseAll: () => gracefullyCloseAll,
- gracefullyCloseSet: () => gracefullyCloseSet,
- gracefullyProcessExitDoNotHang: () => gracefullyProcessExitDoNotHang,
- guessClientName: () => guessClientName,
- hostPlatform: () => hostPlatform,
- hostnameFromHostHeader: () => hostnameFromHostHeader,
- httpRequest: () => httpRequest,
- isChromiumChannelName: () => isChromiumChannelName,
- isCodingAgent: () => isCodingAgent,
- isLikelyNpxGlobal: () => isLikelyNpxGlobal,
- isOfficiallySupportedPlatform: () => isOfficiallySupportedPlatform,
- isPathInside: () => isPathInside,
- isSystemDirectory: () => isSystemDirectory,
- isURLAvailable: () => isURLAvailable,
- isUnderTest: () => isUnderTest,
- isWritable: () => isWritable,
- jsonStringifyForceASCII: () => jsonStringifyForceASCII,
- launchProcess: () => launchProcess,
- lock: () => lock,
- makeSocketPath: () => makeSocketPath,
- makeWaitForNextTask: () => makeWaitForNextTask,
- mkdirIfNeeded: () => mkdirIfNeeded,
- nodePlatform: () => nodePlatform,
- parsePattern: () => parsePattern,
- perMessageDeflate: () => perMessageDeflate,
- removeFolders: () => removeFolders,
- resolveWithinRoot: () => resolveWithinRoot,
- rgb2gray: () => rgb2gray,
- sanitizeForFilePath: () => sanitizeForFilePath,
- serveFolder: () => serveFolder,
- setBoxedStackPrefixes: () => setBoxedStackPrefixes,
- setPlaywrightTestProcessEnv: () => setPlaywrightTestProcessEnv,
- shortPlatform: () => shortPlatform,
- spawnAsync: () => spawnAsync,
- srgb2xyz: () => srgb2xyz,
- ssim: () => ssim,
- startHttpServer: () => startHttpServer,
- startProfiling: () => startProfiling,
- stopProfiling: () => stopProfiling,
- stringWidth: () => stringWidth,
- throwingResolveWithinRoot: () => throwingResolveWithinRoot,
- toPosixPath: () => toPosixPath,
- trimLongString: () => trimLongString,
- urlHostFromAddress: () => urlHostFromAddress,
- wrapInASCIIBox: () => wrapInASCIIBox,
- xyz2lab: () => xyz2lab
-});
-var init_utils = __esm({
- "packages/utils/index.ts"() {
- "use strict";
- init_ascii();
- init_chromiumChannels();
- init_comparators();
- init_crypto();
- init_debug();
- init_debugLogger();
- init_env();
- init_eventsHelper();
- init_fileUtils();
- init_hostPlatform();
- init_httpServer();
- init_network();
- init_nodePlatform();
- init_processLauncher();
- init_profiler();
- init_serializedFS();
- init_socksProxy();
- init_spawnAsync();
- init_stringWidth();
- init_task();
- init_wsServer();
- init_zipFile();
- init_zones();
- init_extractZip();
- init_lockfile();
- init_colorUtils();
- init_compare();
- init_imageChannel();
- init_stats();
- }
-});
-
-// packages/playwright-core/src/client/eventEmitter.ts
-function checkListener(listener) {
- if (typeof listener !== "function")
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
-}
-function unwrapListener(l) {
- return wrappedListener(l) ?? l;
-}
-function unwrapListeners(arr) {
- return arr.map((l) => wrappedListener(l) ?? l);
-}
-function wrappedListener(l) {
- return l.listener;
-}
-var EventEmitter3, OnceWrapper;
-var init_eventEmitter = __esm({
- "packages/playwright-core/src/client/eventEmitter.ts"() {
- "use strict";
- EventEmitter3 = class {
- constructor(platform) {
- this._events = void 0;
- this._eventsCount = 0;
- this._maxListeners = void 0;
- this._pendingHandlers = /* @__PURE__ */ new Map();
- this._platform = platform;
- if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
- this._events = /* @__PURE__ */ Object.create(null);
- this._eventsCount = 0;
- }
- this._maxListeners = this._maxListeners || void 0;
- this.on = this.addListener;
- this.off = this.removeListener;
- }
- setMaxListeners(n) {
- if (typeof n !== "number" || n < 0 || Number.isNaN(n))
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
- this._maxListeners = n;
- return this;
- }
- getMaxListeners() {
- return this._maxListeners === void 0 ? this._platform.defaultMaxListeners() : this._maxListeners;
- }
- emit(type3, ...args) {
- const events = this._events;
- if (events === void 0)
- return false;
- const handler = events?.[type3];
- if (handler === void 0)
- return false;
- if (typeof handler === "function") {
- this._callHandler(type3, handler, args);
- } else {
- const len = handler.length;
- const listeners = handler.slice();
- for (let i = 0; i < len; ++i)
- this._callHandler(type3, listeners[i], args);
- }
- return true;
- }
- _callHandler(type3, handler, args) {
- const promise = Reflect.apply(handler, this, args);
- if (!(promise instanceof Promise))
- return;
- let set = this._pendingHandlers.get(type3);
- if (!set) {
- set = /* @__PURE__ */ new Set();
- this._pendingHandlers.set(type3, set);
- }
- set.add(promise);
- promise.catch((e) => {
- if (this._rejectionHandler)
- this._rejectionHandler(e);
- else
- throw e;
- }).finally(() => set.delete(promise));
- }
- addListener(type3, listener) {
- return this._addListener(type3, listener, false);
- }
- on(type3, listener) {
- return this._addListener(type3, listener, false);
- }
- _addListener(type3, listener, prepend) {
- checkListener(listener);
- let events = this._events;
- let existing;
- if (events === void 0) {
- events = this._events = /* @__PURE__ */ Object.create(null);
- this._eventsCount = 0;
- } else {
- if (events.newListener !== void 0) {
- this.emit("newListener", type3, unwrapListener(listener));
- events = this._events;
- }
- existing = events[type3];
- }
- if (existing === void 0) {
- existing = events[type3] = listener;
- ++this._eventsCount;
- } else {
- if (typeof existing === "function") {
- existing = events[type3] = prepend ? [listener, existing] : [existing, listener];
- } else if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- const m = this.getMaxListeners();
- if (m > 0 && existing.length > m && !existing.warned) {
- existing.warned = true;
- const w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type3) + " listeners added. Use emitter.setMaxListeners() to increase limit");
- w.name = "MaxListenersExceededWarning";
- w.emitter = this;
- w.type = type3;
- w.count = existing.length;
- if (!this._platform.isUnderTest()) {
- console.warn(w);
- }
- }
- }
- return this;
- }
- prependListener(type3, listener) {
- return this._addListener(type3, listener, true);
- }
- once(type3, listener) {
- checkListener(listener);
- this.on(type3, new OnceWrapper(this, type3, listener).wrapperFunction);
- return this;
- }
- prependOnceListener(type3, listener) {
- checkListener(listener);
- this.prependListener(type3, new OnceWrapper(this, type3, listener).wrapperFunction);
- return this;
- }
- removeListener(type3, listener) {
- checkListener(listener);
- const events = this._events;
- if (events === void 0)
- return this;
- const list = events[type3];
- if (list === void 0)
- return this;
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0) {
- this._events = /* @__PURE__ */ Object.create(null);
- } else {
- delete events[type3];
- if (events.removeListener)
- this.emit("removeListener", type3, list.listener ?? listener);
- }
- } else if (typeof list !== "function") {
- let position = -1;
- let originalListener;
- for (let i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || wrappedListener(list[i]) === listener) {
- originalListener = wrappedListener(list[i]);
- position = i;
- break;
- }
- }
- if (position < 0)
- return this;
- if (position === 0)
- list.shift();
- else
- list.splice(position, 1);
- if (list.length === 1)
- events[type3] = list[0];
- if (events.removeListener !== void 0)
- this.emit("removeListener", type3, originalListener || listener);
- }
- return this;
- }
- off(type3, listener) {
- return this.removeListener(type3, listener);
- }
- removeAllListeners(type3, options) {
- this._removeAllListeners(type3);
- if (!options)
- return this;
- if (options.behavior === "wait") {
- const errors = [];
- this._rejectionHandler = (error) => errors.push(error);
- return this._waitFor(type3).then(() => {
- if (errors.length)
- throw errors[0];
- });
- }
- if (options.behavior === "ignoreErrors")
- this._rejectionHandler = () => {
- };
- return Promise.resolve();
- }
- _removeAllListeners(type3) {
- const events = this._events;
- if (!events)
- return;
- if (!events.removeListener) {
- if (type3 === void 0) {
- this._events = /* @__PURE__ */ Object.create(null);
- this._eventsCount = 0;
- } else if (events[type3] !== void 0) {
- if (--this._eventsCount === 0)
- this._events = /* @__PURE__ */ Object.create(null);
- else
- delete events[type3];
- }
- return;
- }
- if (type3 === void 0) {
- const keys = Object.keys(events);
- let key;
- for (let i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === "removeListener")
- continue;
- this._removeAllListeners(key);
- }
- this._removeAllListeners("removeListener");
- this._events = /* @__PURE__ */ Object.create(null);
- this._eventsCount = 0;
- return;
- }
- const listeners = events[type3];
- if (typeof listeners === "function") {
- this.removeListener(type3, listeners);
- } else if (listeners !== void 0) {
- for (let i = listeners.length - 1; i >= 0; i--)
- this.removeListener(type3, listeners[i]);
- }
- }
- listeners(type3) {
- return this._listeners(this, type3, true);
- }
- rawListeners(type3) {
- return this._listeners(this, type3, false);
- }
- listenerCount(type3) {
- const events = this._events;
- if (events !== void 0) {
- const listener = events[type3];
- if (typeof listener === "function")
- return 1;
- if (listener !== void 0)
- return listener.length;
- }
- return 0;
- }
- eventNames() {
- return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : [];
- }
- async _waitFor(type3) {
- let promises = [];
- if (type3) {
- promises = [...this._pendingHandlers.get(type3) || []];
- } else {
- promises = [];
- for (const [, pending] of this._pendingHandlers)
- promises.push(...pending);
- }
- await Promise.all(promises);
- }
- _listeners(target, type3, unwrap) {
- const events = target._events;
- if (events === void 0)
- return [];
- const listener = events[type3];
- if (listener === void 0)
- return [];
- if (typeof listener === "function")
- return unwrap ? [unwrapListener(listener)] : [listener];
- return unwrap ? unwrapListeners(listener) : listener.slice();
- }
- };
- OnceWrapper = class {
- constructor(eventEmitter, eventType, listener) {
- this._fired = false;
- this._eventEmitter = eventEmitter;
- this._eventType = eventType;
- this._listener = listener;
- this.wrapperFunction = this._handle.bind(this);
- this.wrapperFunction.listener = listener;
- }
- _handle(...args) {
- if (this._fired)
- return;
- this._fired = true;
- this._eventEmitter.removeListener(this._eventType, this.wrapperFunction);
- return this._listener.apply(this._eventEmitter, args);
- }
- };
- }
-});
-
-// packages/playwright-core/src/bootstrap.ts
-var minimumMajorNodeVersion, currentNodeVersion, major;
-var init_bootstrap = __esm({
- "packages/playwright-core/src/bootstrap.ts"() {
- "use strict";
- minimumMajorNodeVersion = 18;
- currentNodeVersion = process.versions.node;
- major = +currentNodeVersion.split(".")[0];
- if (major < minimumMajorNodeVersion) {
- console.error(
- "You are running Node.js " + currentNodeVersion + `.
-Playwright requires Node.js ${minimumMajorNodeVersion} or higher.
-Please update your version of Node.js.`
- );
- process.exit(1);
- }
- if (process.env.PW_INSTRUMENT_MODULES) {
- const Module = require("module");
- const originalLoad = Module._load;
- const root = { name: "", selfMs: 0, totalMs: 0, childrenMs: 0, children: [] };
- let current = root;
- const stack = [];
- Module._load = function(request2, _parent, _isMain) {
- const node = { name: request2, selfMs: 0, totalMs: 0, childrenMs: 0, children: [] };
- current.children.push(node);
- stack.push(current);
- current = node;
- const start3 = performance.now();
- let result2;
- try {
- result2 = originalLoad.apply(this, arguments);
- } catch (e) {
- current = stack.pop();
- current.children.pop();
- throw e;
- }
- const duration = performance.now() - start3;
- node.totalMs = duration;
- node.selfMs = Math.max(0, duration - node.childrenMs);
- current = stack.pop();
- current.childrenMs += duration;
- return result2;
- };
- process.on("exit", () => {
- function printTree(node, prefix, isLast, lines2, depth) {
- if (node.totalMs < 1 && depth > 0)
- return;
- const connector = depth === 0 ? "" : isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
- const time = `${node.totalMs.toFixed(1).padStart(8)}ms`;
- const self2 = node.children.length ? ` (self: ${node.selfMs.toFixed(1)}ms)` : "";
- lines2.push(`${time} ${prefix}${connector}${node.name}${self2}`);
- const childPrefix = prefix + (depth === 0 ? "" : isLast ? " " : "\u2502 ");
- const sorted2 = node.children.slice().sort((a, b) => b.totalMs - a.totalMs);
- for (let i = 0; i < sorted2.length; i++)
- printTree(sorted2[i], childPrefix, i === sorted2.length - 1, lines2, depth + 1);
- }
- let totalModules = 0;
- function count(n) {
- totalModules++;
- n.children.forEach(count);
- }
- root.children.forEach(count);
- const lines = [];
- const sorted = root.children.slice().sort((a, b) => b.totalMs - a.totalMs);
- for (let i = 0; i < sorted.length; i++)
- printTree(sorted[i], "", i === sorted.length - 1, lines, 0);
- const totalMs = root.children.reduce((s, c) => s + c.totalMs, 0);
- process.stderr.write(`
---- Module load tree: ${totalModules} modules, ${totalMs.toFixed(0)}ms total ---
-` + lines.join("\n") + "\n");
- const flat = /* @__PURE__ */ new Map();
- function gather(n) {
- const existing = flat.get(n.name);
- if (existing) {
- existing.selfMs += n.selfMs;
- existing.totalMs += n.totalMs;
- existing.count++;
- } else {
- flat.set(n.name, { selfMs: n.selfMs, totalMs: n.totalMs, count: 1 });
- }
- n.children.forEach(gather);
- }
- root.children.forEach(gather);
- const top50 = [...flat.entries()].sort((a, b) => b[1].selfMs - a[1].selfMs).slice(0, 50);
- const flatLines = top50.map(
- ([mod, { selfMs, totalMs: totalMs2, count: count2 }]) => `${selfMs.toFixed(1).padStart(8)}ms self ${totalMs2.toFixed(1).padStart(8)}ms total (x${String(count2).padStart(3)}) ${mod}`
- );
- process.stderr.write(`
---- Top 50 modules by self time ---
-` + flatLines.join("\n") + "\n");
- });
- }
- }
-});
-
-// packages/playwright-core/src/package.ts
-function libPath(...parts) {
- return import_path8.default.join(packageRoot, "lib", ...parts);
-}
-var import_path8, packageRoot, packageJSON, binPath;
-var init_package = __esm({
- "packages/playwright-core/src/package.ts"() {
- "use strict";
- import_path8 = __toESM(require("path"));
- packageRoot = import_path8.default.join(__dirname, "..");
- packageJSON = require(import_path8.default.join(packageRoot, "package.json"));
- binPath = import_path8.default.join(packageRoot, "bin");
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceParser.ts
-async function extractTrace(traceFile, outDir) {
- const zipFile = new ZipFile(traceFile);
- try {
- const entries = await zipFile.entries();
- for (const entry of entries) {
- const outPath = resolveWithinRoot(outDir, entry);
- if (!outPath)
- throw new Error(`Trace entry '${entry}' escapes output directory`);
- await import_fs10.default.promises.mkdir(import_path9.default.dirname(outPath), { recursive: true });
- const buffer = await zipFile.read(entry);
- await import_fs10.default.promises.writeFile(outPath, buffer);
- }
- } finally {
- zipFile.close();
- }
-}
-var import_fs10, import_path9, DirTraceLoaderBackend;
-var init_traceParser = __esm({
- "packages/playwright-core/src/tools/trace/traceParser.ts"() {
- "use strict";
- import_fs10 = __toESM(require("fs"));
- import_path9 = __toESM(require("path"));
- init_fileUtils();
- init_zipFile();
- DirTraceLoaderBackend = class {
- constructor(dir) {
- this._dir = dir;
- }
- isLive() {
- return false;
- }
- async entryNames() {
- const entries = [];
- const walk = async (dir, prefix) => {
- const items = await import_fs10.default.promises.readdir(dir, { withFileTypes: true });
- for (const item of items) {
- if (item.isDirectory())
- await walk(import_path9.default.join(dir, item.name), prefix ? `${prefix}/${item.name}` : item.name);
- else
- entries.push(prefix ? `${prefix}/${item.name}` : item.name);
- }
- };
- await walk(this._dir, "");
- return entries;
- }
- async hasEntry(entryName) {
- const resolved = resolveWithinRoot(this._dir, entryName);
- if (!resolved)
- return false;
- try {
- await import_fs10.default.promises.access(resolved);
- return true;
- } catch {
- return false;
- }
- }
- async readText(entryName) {
- const resolved = resolveWithinRoot(this._dir, entryName);
- if (!resolved)
- return;
- try {
- return await import_fs10.default.promises.readFile(resolved, "utf-8");
- } catch {
- }
- }
- async readBlob(entryName) {
- const resolved = resolveWithinRoot(this._dir, entryName);
- if (!resolved)
- return;
- try {
- const buffer = await import_fs10.default.promises.readFile(resolved);
- return new Blob([new Uint8Array(buffer)]);
- } catch {
- }
- }
- };
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceUtils.ts
-function ensureTraceOpen() {
- if (!import_fs11.default.existsSync(traceDir))
- throw new Error(`No trace opened. Run 'npx playwright trace open ' first.`);
- return traceDir;
-}
-async function closeTrace() {
- if (import_fs11.default.existsSync(traceDir))
- await import_fs11.default.promises.rm(traceDir, { recursive: true });
-}
-async function openTrace(traceFile) {
- const filePath = import_path10.default.resolve(traceFile);
- if (!import_fs11.default.existsSync(filePath))
- throw new Error(`Trace file not found: ${filePath}`);
- await closeTrace();
- await import_fs11.default.promises.mkdir(traceDir, { recursive: true });
- if (filePath.endsWith(".zip"))
- await extractTrace(filePath, traceDir);
- else
- await import_fs11.default.promises.writeFile(import_path10.default.join(traceDir, ".link"), filePath, "utf-8");
-}
-async function loadTrace() {
- const dir = ensureTraceOpen();
- const linkFile = import_path10.default.join(dir, ".link");
- let traceDir2;
- let traceFile;
- if (import_fs11.default.existsSync(linkFile)) {
- const tracePath = await import_fs11.default.promises.readFile(linkFile, "utf-8");
- traceDir2 = import_path10.default.dirname(tracePath);
- traceFile = import_path10.default.basename(tracePath);
- } else {
- traceDir2 = dir;
- }
- const backend = new DirTraceLoaderBackend(traceDir2);
- const loader = new TraceLoader();
- await loader.load(backend, traceFile);
- const model = new TraceModel(traceDir2, loader.contextEntries);
- return new LoadedTrace(model, loader, buildOrdinalMap(model));
-}
-function formatTimestamp(ms, base) {
- const relative = ms - base;
- if (relative < 0)
- return "0:00.000";
- const totalMs = Math.floor(relative);
- const minutes = Math.floor(totalMs / 6e4);
- const seconds = Math.floor(totalMs % 6e4 / 1e3);
- const millis = totalMs % 1e3;
- return `${minutes}:${seconds.toString().padStart(2, "0")}.${millis.toString().padStart(3, "0")}`;
-}
-function actionTitle(action) {
- return renderTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`;
-}
-async function saveOutputFile(fileName, content, explicitOutput) {
- let outFile;
- if (explicitOutput) {
- outFile = explicitOutput;
- } else {
- const resolved = resolveWithinRoot(cliOutputDir, fileName);
- if (!resolved)
- throw new Error(`Attachment name '${fileName}' escapes output directory`);
- await import_fs11.default.promises.mkdir(import_path10.default.dirname(resolved), { recursive: true });
- outFile = resolved;
- }
- await import_fs11.default.promises.writeFile(outFile, content);
- return outFile;
-}
-function buildOrdinalMap(model) {
- const actions = model.actions.filter((a) => a.group !== "configuration");
- const { rootItem } = buildActionTree(actions);
- const ordinalToCallId = /* @__PURE__ */ new Map();
- const callIdToOrdinal = /* @__PURE__ */ new Map();
- let ordinal = 1;
- const visit = (item) => {
- ordinalToCallId.set(ordinal, item.action.callId);
- callIdToOrdinal.set(item.action.callId, ordinal);
- ordinal++;
- for (const child of item.children)
- visit(child);
- };
- for (const child of rootItem.children)
- visit(child);
- return { ordinalToCallId, callIdToOrdinal };
-}
-var import_fs11, import_path10, traceDir, cliOutputDir, LoadedTrace;
-var init_traceUtils2 = __esm({
- "packages/playwright-core/src/tools/trace/traceUtils.ts"() {
- "use strict";
- import_fs11 = __toESM(require("fs"));
- import_path10 = __toESM(require("path"));
- init_traceModel();
- init_traceLoader();
- init_protocolFormatter();
- init_fileUtils();
- init_traceParser();
- traceDir = import_path10.default.join(".playwright-cli", "trace");
- cliOutputDir = ".playwright-cli";
- LoadedTrace = class {
- constructor(model, loader, ordinals) {
- this.model = model;
- this.loader = loader;
- this.ordinalToCallId = ordinals.ordinalToCallId;
- this.callIdToOrdinal = ordinals.callIdToOrdinal;
- }
- resolveActionId(actionId) {
- const ordinal = parseInt(actionId, 10);
- if (!isNaN(ordinal)) {
- const callId = this.ordinalToCallId.get(ordinal);
- if (callId)
- return this.model.actions.find((a) => a.callId === callId);
- }
- return this.model.actions.find((a) => a.callId === actionId);
- }
- };
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceOpen.ts
-async function traceOpen(traceFile) {
- await openTrace(traceFile);
- await traceInfo();
-}
-async function traceInfo() {
- const trace = await loadTrace();
- const model = trace.model;
- const info = {
- browser: model.browserName || "unknown",
- platform: model.platform || "unknown",
- playwrightVersion: model.playwrightVersion || "unknown",
- title: model.title || "",
- duration: msToString(model.endTime - model.startTime),
- durationMs: model.endTime - model.startTime,
- startTime: model.wallTime ? new Date(model.wallTime).toISOString() : "unknown",
- viewport: model.options.viewport ? `${model.options.viewport.width}x${model.options.viewport.height}` : "default",
- actions: model.actions.length,
- pages: model.pages.length,
- network: model.resources.length,
- errors: model.errorDescriptors.length,
- attachments: model.attachments.length,
- consoleMessages: model.events.filter((e) => e.type === "console").length
- };
- console.log("");
- console.log(` Browser: ${info.browser}`);
- console.log(` Platform: ${info.platform}`);
- console.log(` Playwright: ${info.playwrightVersion}`);
- if (info.title)
- console.log(` Title: ${info.title}`);
- console.log(` Duration: ${info.duration}`);
- console.log(` Start time: ${info.startTime}`);
- console.log(` Viewport: ${info.viewport}`);
- console.log(` Actions: ${info.actions}`);
- console.log(` Pages: ${info.pages}`);
- console.log(` Network: ${info.network} requests`);
- console.log(` Errors: ${info.errors}`);
- console.log(` Attachments: ${info.attachments}`);
- console.log(` Console: ${info.consoleMessages} messages`);
- console.log("");
-}
-var init_traceOpen = __esm({
- "packages/playwright-core/src/tools/trace/traceOpen.ts"() {
- "use strict";
- init_formatUtils();
- init_traceUtils2();
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceActions.ts
-async function traceActions(options) {
- const trace = await loadTrace();
- const actions = filterActions(trace.model.actions, options);
- const { rootItem } = buildActionTree(actions);
- console.log(` ${"#".padStart(4)} ${"Time".padEnd(9)} ${"Action".padEnd(55)} ${"Duration".padStart(8)}`);
- console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(9)} ${"\u2500".repeat(55)} ${"\u2500".repeat(8)}`);
- const visit = (item, indent) => {
- const action = item.action;
- const ordinal = trace.callIdToOrdinal.get(action.callId) ?? "?";
- const ts = formatTimestamp(action.startTime, trace.model.startTime);
- const duration = action.endTime ? msToString(action.endTime - action.startTime) : "running";
- const title = actionTitle(action);
- const locator2 = actionLocator(action);
- const error = action.error ? " \u2717" : "";
- const prefix = ` ${(ordinal + ".").padStart(4)} ${ts} ${indent}`;
- console.log(`${prefix}${title.padEnd(Math.max(1, 55 - indent.length))} ${duration.padStart(8)}${error}`);
- if (locator2)
- console.log(`${" ".repeat(prefix.length)}${locator2}`);
- for (const child of item.children)
- visit(child, indent + " ");
- };
- for (const child of rootItem.children)
- visit(child, "");
-}
-function filterActions(actions, options) {
- let result2 = actions.filter((a) => a.group !== "configuration");
- if (options.grep) {
- const pattern = new RegExp(options.grep, "i");
- result2 = result2.filter((a) => pattern.test(actionTitle(a)) || pattern.test(actionLocator(a) || ""));
- }
- if (options.errorsOnly)
- result2 = result2.filter((a) => !!a.error);
- return result2;
-}
-function actionLocator(action, sdkLanguage) {
- return action.params.selector ? asLocatorDescription(sdkLanguage || "javascript", action.params.selector) : void 0;
-}
-async function traceAction(actionId) {
- const trace = await loadTrace();
- const action = trace.resolveActionId(actionId);
- if (!action) {
- console.error(`Action '${actionId}' not found. Use 'trace actions' to see available action IDs.`);
- process.exitCode = 1;
- return;
- }
- const title = actionTitle(action);
- console.log(`
- ${title}
-`);
- console.log(" Time");
- console.log(` start: ${formatTimestamp(action.startTime, trace.model.startTime)}`);
- const duration = action.endTime ? msToString(action.endTime - action.startTime) : action.error ? "Timed Out" : "Running";
- console.log(` duration: ${duration}`);
- const paramKeys = Object.keys(action.params).filter((name) => name !== "info");
- if (paramKeys.length) {
- console.log("\n Parameters");
- for (const key of paramKeys) {
- const value2 = formatParamValue(action.params[key]);
- console.log(` ${key}: ${value2}`);
- }
- }
- if (action.result) {
- console.log("\n Return value");
- for (const [key, value2] of Object.entries(action.result))
- console.log(` ${key}: ${formatParamValue(value2)}`);
- }
- if (action.error) {
- console.log("\n Error");
- console.log(` ${action.error.message}`);
- }
- if (action.log.length) {
- console.log("\n Log");
- for (const entry of action.log) {
- const time = entry.time !== -1 ? formatTimestamp(entry.time, trace.model.startTime) : "";
- console.log(` ${time.padEnd(12)} ${entry.message}`);
- }
- }
- if (action.stack?.length) {
- console.log("\n Source");
- for (const frame of action.stack.slice(0, 5)) {
- const file = frame.file.replace(/.*[/\\](.*)/, "$1");
- console.log(` ${file}:${frame.line}:${frame.column}`);
- }
- }
- const snapshots = [];
- if (action.beforeSnapshot)
- snapshots.push("before");
- if (action.inputSnapshot)
- snapshots.push("input");
- if (action.afterSnapshot)
- snapshots.push("after");
- if (snapshots.length) {
- console.log("\n Snapshots");
- console.log(` available: ${snapshots.join(", ")}`);
- console.log(` usage: npx playwright trace snapshot ${actionId} --name <${snapshots.join("|")}>`);
- }
- console.log("");
-}
-function formatParamValue(value2) {
- if (value2 === void 0 || value2 === null)
- return String(value2);
- if (typeof value2 === "string")
- return `"${value2}"`;
- if (typeof value2 !== "object")
- return String(value2);
- if (value2.guid)
- return "";
- return JSON.stringify(value2).slice(0, 1e3);
-}
-var init_traceActions = __esm({
- "packages/playwright-core/src/tools/trace/traceActions.ts"() {
- "use strict";
- init_traceModel();
- init_locatorGenerators();
- init_formatUtils();
- init_traceUtils2();
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceRequests.ts
-async function traceRequests(options) {
- const trace = await loadTrace();
- const model = trace.model;
- let indexed = model.resources.map((r, i) => ({ resource: r, ordinal: i + 1 }));
- if (options.grep) {
- const pattern = new RegExp(options.grep, "i");
- indexed = indexed.filter(({ resource: r }) => pattern.test(r.request.url));
- }
- if (options.method)
- indexed = indexed.filter(({ resource: r }) => r.request.method.toLowerCase() === options.method.toLowerCase());
- if (options.status) {
- const code = parseInt(options.status, 10);
- indexed = indexed.filter(({ resource: r }) => r.response.status === code);
- }
- if (options.failed)
- indexed = indexed.filter(({ resource: r }) => r.response.status >= 400 || r.response.status === -1);
- if (!indexed.length) {
- console.log(" No network requests");
- return;
- }
- console.log(` ${"#".padStart(4)} ${"Method".padEnd(8)} ${"Status".padEnd(8)} ${"Name".padEnd(45)} ${"Duration".padStart(10)} ${"Size".padStart(8)} ${"Route".padEnd(10)}`);
- console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(8)} ${"\u2500".repeat(8)} ${"\u2500".repeat(45)} ${"\u2500".repeat(10)} ${"\u2500".repeat(8)} ${"\u2500".repeat(10)}`);
- for (const { resource: r, ordinal } of indexed) {
- let name;
- try {
- const url2 = new URL(r.request.url);
- name = url2.pathname.substring(url2.pathname.lastIndexOf("/") + 1);
- if (!name)
- name = url2.host;
- if (url2.search)
- name += url2.search;
- } catch {
- name = r.request.url;
- }
- if (name.length > 45)
- name = name.substring(0, 42) + "...";
- const status = r.response.status > 0 ? String(r.response.status) : "ERR";
- const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize;
- const route2 = formatRouteStatus(r);
- console.log(` ${(ordinal + ".").padStart(4)} ${r.request.method.padEnd(8)} ${status.padEnd(8)} ${name.padEnd(45)} ${msToString(r.time).padStart(10)} ${bytesToString2(size).padStart(8)} ${route2.padEnd(10)}`);
- }
-}
-async function traceRequest(requestId) {
- const trace = await loadTrace();
- const model = trace.model;
- const ordinal = parseInt(requestId, 10);
- const resource = !isNaN(ordinal) && ordinal >= 1 && ordinal <= model.resources.length ? model.resources[ordinal - 1] : void 0;
- if (!resource) {
- console.error(`Request '${requestId}' not found. Use 'trace requests' to see available request IDs.`);
- process.exitCode = 1;
- return;
- }
- const r = resource;
- const status = r.response.status > 0 ? `${r.response.status} ${r.response.statusText}` : "ERR";
- const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize;
- console.log(`
- ${r.request.method} ${r.request.url}
-`);
- console.log(" General");
- console.log(` status: ${status}`);
- console.log(` duration: ${msToString(r.time)}`);
- console.log(` size: ${bytesToString2(size)}`);
- if (r.response.content.mimeType)
- console.log(` type: ${r.response.content.mimeType}`);
- const route2 = formatRouteStatus(r);
- if (route2)
- console.log(` route: ${route2}`);
- if (r.serverIPAddress)
- console.log(` server: ${r.serverIPAddress}${r._serverPort ? ":" + r._serverPort : ""}`);
- if (r.response._failureText)
- console.log(` error: ${r.response._failureText}`);
- if (r.request.headers.length) {
- console.log("\n Request headers");
- for (const h of r.request.headers)
- console.log(` ${h.name}: ${h.value}`);
- }
- if (r.request.postData) {
- console.log("\n Request body");
- const resource2 = r.request.postData._sha1 ?? r.request.postData._file;
- if (resource2) {
- console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, "resources", resource2))}`);
- } else {
- const text2 = r.request.postData.text.length > 2e3 ? r.request.postData.text.substring(0, 2e3) + "..." : r.request.postData.text;
- console.log(` ${text2}`);
- }
- }
- if (r.response.headers.length) {
- console.log("\n Response headers");
- for (const h of r.response.headers)
- console.log(` ${h.name}: ${h.value}`);
- }
- if (r.response.bodySize > 0) {
- const resource2 = r.response.content._sha1 ?? r.response.content._file;
- if (resource2) {
- console.log("\n Response body");
- console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, "resources", resource2))}`);
- } else if (r.response.content.text) {
- const text2 = r.response.content.text.length > 2e3 ? r.response.content.text.substring(0, 2e3) + "..." : r.response.content.text;
- console.log("\n Response body");
- console.log(` ${text2}`);
- }
- }
- if (r._securityDetails) {
- console.log("\n Security");
- if (r._securityDetails.protocol)
- console.log(` protocol: ${r._securityDetails.protocol}`);
- if (r._securityDetails.subjectName)
- console.log(` subject: ${r._securityDetails.subjectName}`);
- if (r._securityDetails.issuer)
- console.log(` issuer: ${r._securityDetails.issuer}`);
- }
- console.log("");
-}
-function bytesToString2(bytes) {
- if (bytes < 0 || !isFinite(bytes))
- return "-";
- if (bytes === 0)
- return "0";
- if (bytes < 1e3)
- return bytes.toFixed(0);
- const kb = bytes / 1024;
- if (kb < 1e3)
- return kb.toFixed(1) + "K";
- const mb = kb / 1024;
- if (mb < 1e3)
- return mb.toFixed(1) + "M";
- const gb = mb / 1024;
- return gb.toFixed(1) + "G";
-}
-function formatRouteStatus(r) {
- if (r._wasAborted)
- return "aborted";
- if (r._wasContinued)
- return "continued";
- if (r._wasFulfilled)
- return "fulfilled";
- if (r._apiRequest)
- return "api";
- return "";
-}
-var import_path11;
-var init_traceRequests = __esm({
- "packages/playwright-core/src/tools/trace/traceRequests.ts"() {
- "use strict";
- import_path11 = __toESM(require("path"));
- init_formatUtils();
- init_traceUtils2();
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceConsole.ts
-async function traceConsole(options) {
- const trace = await loadTrace();
- const model = trace.model;
- const items = [];
- for (const event of model.events) {
- if (event.type === "console") {
- if (options.stdio)
- continue;
- const level = event.messageType;
- if (options.errorsOnly && level !== "error")
- continue;
- if (options.warnings && level !== "error" && level !== "warning")
- continue;
- const url2 = event.location.url;
- const filename = url2 ? url2.substring(url2.lastIndexOf("/") + 1) : "";
- items.push({
- type: "browser",
- level,
- text: event.text,
- location: `${filename}:${event.location.lineNumber}`,
- timestamp: event.time
- });
- }
- if (event.type === "event" && event.method === "pageError") {
- if (options.stdio)
- continue;
- const error = event.params.error;
- items.push({
- type: "browser",
- level: "error",
- text: error?.error?.message || String(error?.value || ""),
- timestamp: event.time
- });
- }
- }
- for (const event of model.stdio) {
- if (options.browser)
- continue;
- if (options.errorsOnly && event.type !== "stderr")
- continue;
- if (options.warnings && event.type !== "stderr")
- continue;
- let text2 = "";
- if (event.text)
- text2 = event.text.trim();
- if (event.base64)
- text2 = Buffer.from(event.base64, "base64").toString("utf-8").trim();
- if (!text2)
- continue;
- items.push({
- type: event.type,
- level: event.type === "stderr" ? "error" : "info",
- text: text2,
- timestamp: event.timestamp
- });
- }
- items.sort((a, b) => a.timestamp - b.timestamp);
- if (!items.length) {
- console.log(" No console entries");
- return;
- }
- for (const item of items) {
- const ts = formatTimestamp(item.timestamp, model.startTime);
- const source11 = item.type === "browser" ? "[browser]" : `[${item.type}]`;
- const level = item.level.padEnd(8);
- const location2 = item.location ? ` ${item.location}` : "";
- console.log(` ${ts} ${source11.padEnd(10)} ${level} ${item.text}${location2}`);
- }
-}
-var init_traceConsole = __esm({
- "packages/playwright-core/src/tools/trace/traceConsole.ts"() {
- "use strict";
- init_traceUtils2();
- }
-});
-
-// packages/playwright-core/src/tools/trace/traceErrors.ts
-async function traceErrors() {
- const trace = await loadTrace();
- const model = trace.model;
- if (!model.errorDescriptors.length) {
- console.log(" No errors");
- return;
- }
- for (const error of model.errorDescriptors) {
- if (error.action) {
- const title = actionTitle(error.action);
- console.log(`
- \u2717 ${title}`);
- } else {
- console.log(`
- \u2717 Error`);
- }
- if (error.stack?.length) {
- const frame = error.stack[0];
- const file = frame.file.replace(/.*[/\\](.*)/, "$1");
- console.log(` at ${file}:${frame.line}:${frame.column}`);
- }
- console.log("");
- const indented = error.message.split("\n").map((l) => ` ${l}`).join("\n");
- console.log(indented);
- }
- console.log("");
-}
-var init_traceErrors = __esm({
- "packages/playwright-core/src/tools/trace/traceErrors.ts"() {
- "use strict";
- init_traceUtils2();
- }
-});
-
-// packages/isomorphic/disposable.ts
-async function disposeAll(disposables) {
- const copy = [...disposables];
- disposables.length = 0;
- await Promise.all(copy.map((d) => d.dispose()));
-}
-var init_disposable = __esm({
- "packages/isomorphic/disposable.ts"() {
- "use strict";
- }
-});
-
-// packages/playwright-core/src/server/userAgent.ts
-function getUserAgent() {
- if (cachedUserAgent)
- return cachedUserAgent;
- try {
- cachedUserAgent = determineUserAgent();
- } catch (e) {
- cachedUserAgent = "Playwright/unknown";
- }
- return cachedUserAgent;
-}
-function determineUserAgent() {
- let osIdentifier = "unknown";
- let osVersion = "unknown";
- if (process.platform === "win32") {
- const version3 = import_os4.default.release().split(".");
- osIdentifier = "windows";
- osVersion = `${version3[0]}.${version3[1]}`;
- } else if (process.platform === "darwin") {
- const version3 = (0, import_child_process2.execSync)("sw_vers -productVersion", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split(".");
- osIdentifier = "macOS";
- osVersion = `${version3[0]}.${version3[1]}`;
- } else if (process.platform === "linux") {
- const distroInfo = getLinuxDistributionInfoSync();
- if (distroInfo) {
- osIdentifier = distroInfo.id || "linux";
- osVersion = distroInfo.version || "unknown";
- } else {
- osIdentifier = "linux";
- }
- }
- const additionalTokens = [];
- if (process.env.CI)
- additionalTokens.push("CI/1");
- const serializedTokens = additionalTokens.length ? " " + additionalTokens.join(" ") : "";
- const { embedderName, embedderVersion } = getEmbedderName();
- return `Playwright/${getPlaywrightVersion()} (${import_os4.default.arch()}; ${osIdentifier} ${osVersion}) ${embedderName}/${embedderVersion}${serializedTokens}`;
-}
-function getEmbedderName() {
- let embedderName = "unknown";
- let embedderVersion = "unknown";
- if (!process.env.PW_LANG_NAME) {
- embedderName = "node";
- embedderVersion = process.version.substring(1).split(".").slice(0, 2).join(".");
- } else if (["node", "python", "java", "csharp"].includes(process.env.PW_LANG_NAME)) {
- embedderName = process.env.PW_LANG_NAME;
- embedderVersion = process.env.PW_LANG_NAME_VERSION ?? "unknown";
- }
- return { embedderName, embedderVersion };
-}
-function getPlaywrightVersion(majorMinorOnly = false) {
- const version3 = process.env.PW_VERSION_OVERRIDE || packageJSON.version;
- return majorMinorOnly ? version3.split(".").slice(0, 2).join(".") : version3;
-}
-var import_child_process2, import_os4, cachedUserAgent;
-var init_userAgent = __esm({
- "packages/playwright-core/src/server/userAgent.ts"() {
- "use strict";
- import_child_process2 = require("child_process");
- import_os4 = __toESM(require("os"));
- init_linuxUtils();
- init_package();
- }
-});
-
-// packages/playwright-core/src/generated/clockSource.ts
-var source;
-var init_clockSource = __esm({
- "packages/playwright-core/src/generated/clockSource.ts"() {
- "use strict";
- source = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/clock.ts\nvar clock_exports = {};\n__export(clock_exports, {\n ClockController: () => ClockController,\n createClock: () => createClock,\n inject: () => inject,\n install: () => install\n});\nmodule.exports = __toCommonJS(clock_exports);\nvar ClockController = class {\n constructor(embedder) {\n this._duringTick = false;\n this._uniqueTimerId = idCounterStart;\n this.disposables = [];\n this._log = [];\n this._timers = /* @__PURE__ */ new Map();\n this._now = { time: asWallTime(0), isFixedTime: false, ticks: 0, origin: asWallTime(-1) };\n this._embedder = embedder;\n }\n uninstall() {\n this.disposables.forEach((dispose) => dispose());\n this.disposables.length = 0;\n }\n now() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.time;\n }\n install(time) {\n this._replayLogOnce();\n this._innerInstall(asWallTime(time));\n }\n setSystemTime(time) {\n this._replayLogOnce();\n this._innerSetTime(asWallTime(time));\n }\n setFixedTime(time) {\n this._replayLogOnce();\n this._innerSetFixedTime(asWallTime(time));\n }\n performanceNow() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.ticks;\n }\n _syncRealTime() {\n if (!this._realTime)\n return;\n const now = this._embedder.performanceNow();\n const sinceLastSync = now - this._realTime.lastSyncTicks;\n if (sinceLastSync > 0) {\n this._advanceNow(shiftTicks(this._now.ticks, sinceLastSync));\n this._realTime.lastSyncTicks = now;\n }\n }\n _innerSetTime(time) {\n this._now.time = time;\n this._now.isFixedTime = false;\n if (this._now.origin < 0)\n this._now.origin = this._now.time;\n }\n _innerInstall(time) {\n if (this._now.origin < 0)\n this._now.ticks = 0;\n this._innerSetTime(time);\n }\n _innerSetFixedTime(time) {\n this._innerSetTime(time);\n this._now.isFixedTime = true;\n }\n _advanceNow(to) {\n if (this._now.ticks > to) {\n return;\n }\n if (!this._now.isFixedTime)\n this._now.time = asWallTime(this._now.time + to - this._now.ticks);\n this._now.ticks = to;\n }\n async log(type, time, param) {\n this._log.push({ type, time, param });\n }\n async runFor(ticks) {\n this._replayLogOnce();\n if (ticks < 0)\n throw new TypeError("Negative ticks are not supported");\n await this._runWithDisabledRealTimeSync(async () => {\n await this._runTo(shiftTicks(this._now.ticks, ticks));\n });\n }\n async _runTo(to) {\n to = Math.ceil(to);\n if (this._now.ticks > to)\n return;\n let firstException;\n while (true) {\n const result = await this._callFirstTimer(to);\n if (!result.timerFound)\n break;\n firstException = firstException || result.error;\n }\n this._advanceNow(to);\n if (firstException)\n throw firstException;\n }\n async pauseAt(time) {\n this._replayLogOnce();\n await this._innerPause();\n const toConsume = time - this._now.time;\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, toConsume));\n return toConsume;\n }\n async _innerPause() {\n var _a;\n this._realTime = void 0;\n await ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.dispose());\n this._currentRealTimeTimer = void 0;\n }\n resume() {\n this._replayLogOnce();\n this._innerResume();\n }\n _innerResume() {\n const now = this._embedder.performanceNow();\n this._realTime = { startTicks: now, lastSyncTicks: now };\n this._updateRealTimeTimer();\n }\n _updateRealTimeTimer() {\n var _a;\n if ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.promise) {\n return;\n }\n const firstTimer = this._firstTimer();\n const nextTick = Math.min(firstTimer ? firstTimer.callAt : this._now.ticks + maxTimeout, this._now.ticks + 100);\n const callAt = this._currentRealTimeTimer ? Math.min(this._currentRealTimeTimer.callAt, nextTick) : nextTick;\n if (this._currentRealTimeTimer) {\n this._currentRealTimeTimer.cancel();\n this._currentRealTimeTimer = void 0;\n }\n const realTimeTimer = {\n callAt,\n promise: void 0,\n cancel: this._embedder.setTimeout(() => {\n this._syncRealTime();\n realTimeTimer.promise = this._runTo(this._now.ticks).catch((e) => console.error(e));\n void realTimeTimer.promise.then(() => {\n this._currentRealTimeTimer = void 0;\n if (this._realTime)\n this._updateRealTimeTimer();\n });\n }, callAt - this._now.ticks),\n dispose: async () => {\n realTimeTimer.cancel();\n await realTimeTimer.promise;\n }\n };\n this._currentRealTimeTimer = realTimeTimer;\n }\n async _runWithDisabledRealTimeSync(fn) {\n if (!this._realTime) {\n await fn();\n return;\n }\n await this._innerPause();\n try {\n await fn();\n } finally {\n this._innerResume();\n }\n }\n async fastForward(ticks) {\n this._replayLogOnce();\n await this._runWithDisabledRealTimeSync(async () => {\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, ticks | 0));\n });\n }\n async _innerFastForwardTo(to) {\n if (to < this._now.ticks)\n throw new Error("Cannot fast-forward to the past");\n for (const timer of this._timers.values()) {\n if (to > timer.callAt)\n timer.callAt = to;\n }\n await this._runTo(to);\n }\n addTimer(options) {\n this._replayLogOnce();\n if (options.type === "AnimationFrame" /* AnimationFrame */ && !options.func)\n throw new Error("Callback must be provided to requestAnimationFrame calls");\n if (options.type === "IdleCallback" /* IdleCallback */ && !options.func)\n throw new Error("Callback must be provided to requestIdleCallback calls");\n if (["Timeout" /* Timeout */, "Interval" /* Interval */].includes(options.type) && !options.func && options.delay === void 0)\n throw new Error("Callback must be provided to timer calls");\n let delay = options.delay ? +options.delay : 0;\n if (!Number.isFinite(delay))\n delay = 0;\n delay = delay > maxTimeout ? 1 : delay;\n delay = Math.max(0, delay);\n const timer = {\n type: options.type,\n func: options.func,\n args: options.args || [],\n delay,\n callAt: shiftTicks(this._now.ticks, delay || (this._duringTick ? 1 : 0)),\n createdAt: this._now.ticks,\n id: this._uniqueTimerId++,\n error: new Error()\n };\n this._timers.set(timer.id, timer);\n if (this._realTime)\n this._updateRealTimeTimer();\n return timer.id;\n }\n countTimers() {\n return this._timers.size;\n }\n _firstTimer(beforeTick) {\n let firstTimer = null;\n for (const timer of this._timers.values()) {\n const isInRange = beforeTick === void 0 || timer.callAt <= beforeTick;\n if (isInRange && (!firstTimer || compareTimers(firstTimer, timer) === 1))\n firstTimer = timer;\n }\n return firstTimer;\n }\n _takeFirstTimer(beforeTick) {\n const timer = this._firstTimer(beforeTick);\n if (!timer)\n return null;\n this._advanceNow(timer.callAt);\n if (timer.type === "Interval" /* Interval */)\n timer.callAt = shiftTicks(timer.callAt, timer.delay);\n else\n this._timers.delete(timer.id);\n return timer;\n }\n async _callFirstTimer(beforeTick) {\n const timer = this._takeFirstTimer(beforeTick);\n if (!timer)\n return { timerFound: false };\n this._duringTick = true;\n try {\n if (typeof timer.func !== "function") {\n let error2;\n try {\n (() => {\n globalThis.eval(timer.func);\n })();\n } catch (e) {\n error2 = e;\n }\n await new Promise((f) => this._embedder.setTimeout(f));\n return { timerFound: true, error: error2 };\n }\n let args = timer.args;\n if (timer.type === "AnimationFrame" /* AnimationFrame */)\n args = [this._now.ticks];\n else if (timer.type === "IdleCallback" /* IdleCallback */)\n args = [{ didTimeout: false, timeRemaining: () => 0 }];\n let error;\n try {\n timer.func.apply(null, args);\n } catch (e) {\n error = e;\n }\n await new Promise((f) => this._embedder.setTimeout(f));\n return { timerFound: true, error };\n } finally {\n this._duringTick = false;\n }\n }\n getTimeToNextFrame() {\n this._replayLogOnce();\n return 16 - this._now.ticks % 16;\n }\n clearTimer(timerId, type) {\n this._replayLogOnce();\n if (!timerId) {\n return;\n }\n const id = Number(timerId);\n if (Number.isNaN(id) || id < idCounterStart) {\n const handlerName = getClearHandler(type);\n new Error(`Clock: ${handlerName} was invoked to clear a native timer instead of one created by the clock library.`);\n }\n const timer = this._timers.get(id);\n if (timer) {\n if (timer.type === type || timer.type === "Timeout" && type === "Interval" || timer.type === "Interval" && type === "Timeout") {\n this._timers.delete(id);\n } else {\n const clear = getClearHandler(type);\n const schedule = getScheduleHandler(timer.type);\n throw new Error(\n `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`\n );\n }\n }\n }\n _replayLogOnce() {\n if (!this._log.length)\n return;\n let lastLogTime = -1;\n let isPaused = false;\n for (const { type, time, param } of this._log) {\n if (!isPaused && lastLogTime !== -1)\n this._advanceNow(shiftTicks(this._now.ticks, time - lastLogTime));\n lastLogTime = time;\n if (type === "install") {\n this._innerInstall(asWallTime(param));\n } else if (type === "fastForward" || type === "runFor") {\n this._advanceNow(shiftTicks(this._now.ticks, param));\n } else if (type === "pauseAt") {\n isPaused = true;\n this._innerSetTime(asWallTime(param));\n } else if (type === "resume") {\n isPaused = false;\n } else if (type === "setFixedTime") {\n this._innerSetFixedTime(asWallTime(param));\n } else if (type === "setSystemTime") {\n this._innerSetTime(asWallTime(param));\n }\n }\n if (!isPaused) {\n if (lastLogTime > 0)\n this._advanceNow(shiftTicks(this._now.ticks, this._embedder.dateNow() - lastLogTime));\n this._innerResume();\n } else {\n this._realTime = void 0;\n }\n this._log.length = 0;\n }\n};\nfunction mirrorDateProperties(target, source) {\n for (const prop in source) {\n if (source.hasOwnProperty(prop))\n target[prop] = source[prop];\n }\n target.toString = () => source.toString();\n target.prototype = source.prototype;\n target.parse = source.parse;\n target.UTC = source.UTC;\n target.prototype.toUTCString = source.prototype.toUTCString;\n target.isFake = true;\n return target;\n}\nfunction createDate(clock, NativeDate) {\n function ClockDate(year, month, date, hour, minute, second, ms) {\n if (!(this instanceof ClockDate))\n return new NativeDate(clock.now()).toString();\n switch (arguments.length) {\n case 0:\n return new NativeDate(clock.now());\n case 1:\n return new NativeDate(year);\n case 2:\n return new NativeDate(year, month);\n case 3:\n return new NativeDate(year, month, date);\n case 4:\n return new NativeDate(year, month, date, hour);\n case 5:\n return new NativeDate(year, month, date, hour, minute);\n case 6:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second\n );\n default:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second,\n ms\n );\n }\n }\n ClockDate.now = () => clock.now();\n return mirrorDateProperties(ClockDate, NativeDate);\n}\nfunction createIntl(clock, NativeIntl) {\n const ClockIntl = {};\n for (const key of Object.getOwnPropertyNames(NativeIntl))\n ClockIntl[key] = NativeIntl[key];\n ClockIntl.DateTimeFormat = function(...args) {\n const realFormatter = new NativeIntl.DateTimeFormat(...args);\n const formatter = {\n formatRange: realFormatter.formatRange.bind(realFormatter),\n formatRangeToParts: realFormatter.formatRangeToParts.bind(realFormatter),\n resolvedOptions: realFormatter.resolvedOptions.bind(realFormatter),\n format: (date) => realFormatter.format(date || clock.now()),\n formatToParts: (date) => realFormatter.formatToParts(date || clock.now())\n };\n return formatter;\n };\n ClockIntl.DateTimeFormat.prototype = Object.create(\n NativeIntl.DateTimeFormat.prototype\n );\n ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;\n return ClockIntl;\n}\nfunction compareTimers(a, b) {\n if (a.callAt < b.callAt)\n return -1;\n if (a.callAt > b.callAt)\n return 1;\n if (a.type === "Immediate" /* Immediate */ && b.type !== "Immediate" /* Immediate */)\n return -1;\n if (a.type !== "Immediate" /* Immediate */ && b.type === "Immediate" /* Immediate */)\n return 1;\n if (a.createdAt < b.createdAt)\n return -1;\n if (a.createdAt > b.createdAt)\n return 1;\n if (a.id < b.id)\n return -1;\n if (a.id > b.id)\n return 1;\n}\nvar maxTimeout = Math.pow(2, 31) - 1;\nvar idCounterStart = 1e12;\nfunction platformOriginals(globalObject) {\n const raw = {\n setTimeout: globalObject.setTimeout,\n clearTimeout: globalObject.clearTimeout,\n setInterval: globalObject.setInterval,\n clearInterval: globalObject.clearInterval,\n requestAnimationFrame: globalObject.requestAnimationFrame ? globalObject.requestAnimationFrame : void 0,\n cancelAnimationFrame: globalObject.cancelAnimationFrame ? globalObject.cancelAnimationFrame : void 0,\n requestIdleCallback: globalObject.requestIdleCallback ? globalObject.requestIdleCallback : void 0,\n cancelIdleCallback: globalObject.cancelIdleCallback ? globalObject.cancelIdleCallback : void 0,\n Date: globalObject.Date,\n performance: globalObject.performance,\n Intl: globalObject.Intl,\n AbortSignal: globalObject.AbortSignal\n };\n const bound = { ...raw };\n for (const key of Object.keys(bound)) {\n if (key !== "Date" && key !== "AbortSignal" && typeof bound[key] === "function")\n bound[key] = bound[key].bind(globalObject);\n }\n return { raw, bound };\n}\nfunction getScheduleHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `request${type}`;\n return `set${type}`;\n}\nfunction createApi(clock, originals, browserName) {\n return {\n setTimeout: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Timeout" /* Timeout */,\n func,\n args,\n delay\n });\n },\n clearTimeout: (timerId) => {\n if (timerId)\n clock.clearTimer(timerId, "Timeout" /* Timeout */);\n },\n setInterval: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Interval" /* Interval */,\n func,\n args,\n delay\n });\n },\n clearInterval: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "Interval" /* Interval */);\n },\n requestAnimationFrame: (callback) => {\n return clock.addTimer({\n type: "AnimationFrame" /* AnimationFrame */,\n func: callback,\n delay: clock.getTimeToNextFrame()\n });\n },\n cancelAnimationFrame: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "AnimationFrame" /* AnimationFrame */);\n },\n requestIdleCallback: (callback, options) => {\n let timeToNextIdlePeriod = 0;\n if (clock.countTimers() > 0)\n timeToNextIdlePeriod = 50;\n return clock.addTimer({\n type: "IdleCallback" /* IdleCallback */,\n func: callback,\n delay: (options == null ? void 0 : options.timeout) ? Math.min(options == null ? void 0 : options.timeout, timeToNextIdlePeriod) : timeToNextIdlePeriod\n });\n },\n cancelIdleCallback: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "IdleCallback" /* IdleCallback */);\n },\n Intl: originals.Intl ? createIntl(clock, originals.Intl) : void 0,\n Date: createDate(clock, originals.Date),\n performance: originals.performance ? fakePerformance(clock, originals.performance) : void 0,\n AbortSignal: originals.AbortSignal ? fakeAbortSignal(clock, originals.AbortSignal, browserName) : void 0\n };\n}\nfunction getClearHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `cancel${type}`;\n return `clear${type}`;\n}\nvar FakePerformanceEntry = class {\n constructor(name, entryType, startTime, duration) {\n this.name = name;\n this.entryType = entryType;\n this.startTime = startTime;\n this.duration = duration;\n }\n toJSON() {\n return JSON.stringify({ ...this });\n }\n};\nfunction fakePerformance(clock, performance) {\n const result = {\n now: () => clock.performanceNow()\n };\n result.__defineGetter__("timeOrigin", () => clock._now.origin || 0);\n for (const key of Object.keys(performance.__proto__)) {\n if (key === "now" || key === "timeOrigin")\n continue;\n if (key === "getEntries" || key === "getEntriesByName" || key === "getEntriesByType")\n result[key] = () => [];\n else if (key === "mark")\n result[key] = (name) => new FakePerformanceEntry(name, "mark", 0, 0);\n else if (key === "measure")\n result[key] = (name) => new FakePerformanceEntry(name, "measure", 0, 50);\n else\n result[key] = () => {\n };\n }\n return result;\n}\nfunction fakeAbortSignal(clock, abortSignal, browserName) {\n Object.defineProperty(abortSignal, "timeout", {\n value(ms) {\n const controller = new AbortController();\n clock.addTimer({\n delay: ms,\n type: "Timeout" /* Timeout */,\n func: () => controller.abort(\n new DOMException(\n browserName === "chromium" ? "signal timed out" : "The operation timed out.",\n "TimeoutError"\n )\n )\n });\n return controller.signal;\n }\n });\n return abortSignal;\n}\nfunction createClock(globalObject, config = {}) {\n const originals = platformOriginals(globalObject);\n const embedder = {\n dateNow: () => originals.raw.Date.now(),\n performanceNow: () => Math.ceil(originals.raw.performance.now()),\n setTimeout: (task, timeout) => {\n const timerId = originals.bound.setTimeout(task, timeout);\n return () => originals.bound.clearTimeout(timerId);\n },\n setInterval: (task, delay) => {\n const intervalId = originals.bound.setInterval(task, delay);\n return () => originals.bound.clearInterval(intervalId);\n }\n };\n const clock = new ClockController(embedder);\n const api = createApi(clock, originals.bound, config.browserName);\n return { clock, api, originals: originals.raw };\n}\nfunction install(globalObject, config = {}) {\n var _a, _b;\n if ((_a = globalObject.Date) == null ? void 0 : _a.isFake) {\n throw new TypeError(`Can\'t install fake timers twice on the same global object.`);\n }\n const { clock, api, originals } = createClock(globalObject, config);\n const toFake = ((_b = config.toFake) == null ? void 0 : _b.length) ? config.toFake : Object.keys(originals);\n for (const method of toFake) {\n if (method === "Date") {\n globalObject.Date = mirrorDateProperties(api.Date, globalObject.Date);\n } else if (method === "Intl") {\n globalObject.Intl = api[method];\n } else if (method === "AbortSignal") {\n globalObject.AbortSignal = api[method];\n } else if (method === "performance") {\n globalObject.performance = api[method];\n const kEventTimeStamp = Symbol("playwrightEventTimeStamp");\n Object.defineProperty(Event.prototype, "timeStamp", {\n get() {\n var _a2;\n if (!this[kEventTimeStamp])\n this[kEventTimeStamp] = (_a2 = api.performance) == null ? void 0 : _a2.now();\n return this[kEventTimeStamp];\n }\n });\n } else {\n globalObject[method] = (...args) => {\n return api[method].apply(api, args);\n };\n }\n clock.disposables.push(() => {\n globalObject[method] = originals[method];\n });\n }\n return { clock, api, originals };\n}\nfunction inject(globalObject, browserName) {\n const builtins = platformOriginals(globalObject).bound;\n const { clock: controller } = install(globalObject, { browserName });\n controller.resume();\n return {\n controller,\n builtins\n };\n}\nfunction asWallTime(n) {\n return n;\n}\nfunction shiftTicks(ticks, ms) {\n return ticks + ms;\n}\n';
- }
-});
-
-// packages/playwright-core/src/protocol/serializers.ts
-function parseSerializedValue(value2, handles) {
- return innerParseSerializedValue(value2, handles, /* @__PURE__ */ new Map(), []);
-}
-function innerParseSerializedValue(value2, handles, refs, accessChain) {
- if (value2.ref !== void 0)
- return refs.get(value2.ref);
- if (value2.n !== void 0)
- return value2.n;
- if (value2.s !== void 0)
- return value2.s;
- if (value2.b !== void 0)
- return value2.b;
- if (value2.v !== void 0) {
- if (value2.v === "undefined")
- return void 0;
- if (value2.v === "null")
- return null;
- if (value2.v === "NaN")
- return NaN;
- if (value2.v === "Infinity")
- return Infinity;
- if (value2.v === "-Infinity")
- return -Infinity;
- if (value2.v === "-0")
- return -0;
- }
- if (value2.d !== void 0)
- return new Date(value2.d);
- if (value2.u !== void 0)
- return new URL(value2.u);
- if (value2.bi !== void 0)
- return BigInt(value2.bi);
- if (value2.e !== void 0) {
- const error = new Error(value2.e.m);
- error.name = value2.e.n;
- error.stack = value2.e.s;
- return error;
- }
- if (value2.r !== void 0)
- return new RegExp(value2.r.p, value2.r.f);
- if (value2.ta !== void 0) {
- const ctor = typedArrayKindToConstructor[value2.ta.k];
- return new ctor(value2.ta.b.buffer, value2.ta.b.byteOffset, value2.ta.b.length / ctor.BYTES_PER_ELEMENT);
- }
- if (value2.a !== void 0) {
- const result2 = [];
- refs.set(value2.id, result2);
- for (let i = 0; i < value2.a.length; i++)
- result2.push(innerParseSerializedValue(value2.a[i], handles, refs, [...accessChain, i]));
- return result2;
- }
- if (value2.o !== void 0) {
- const result2 = {};
- refs.set(value2.id, result2);
- for (const { k, v } of value2.o)
- result2[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]);
- return result2;
- }
- if (value2.h !== void 0) {
- if (handles === void 0)
- throw new Error("Unexpected handle");
- return handles[value2.h];
- }
- throw new Error(`Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`);
-}
-function serializeValue(value2, handleSerializer) {
- return innerSerializeValue(value2, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []);
-}
-function innerSerializeValue(value2, handleSerializer, visitorInfo, accessChain) {
- const handle = handleSerializer(value2);
- if ("fallThrough" in handle)
- value2 = handle.fallThrough;
- else
- return handle;
- if (typeof value2 === "symbol")
- return { v: "undefined" };
- if (Object.is(value2, void 0))
- return { v: "undefined" };
- if (Object.is(value2, null))
- return { v: "null" };
- if (Object.is(value2, NaN))
- return { v: "NaN" };
- if (Object.is(value2, Infinity))
- return { v: "Infinity" };
- if (Object.is(value2, -Infinity))
- return { v: "-Infinity" };
- if (Object.is(value2, -0))
- return { v: "-0" };
- if (typeof value2 === "boolean")
- return { b: value2 };
- if (typeof value2 === "number")
- return { n: value2 };
- if (typeof value2 === "string")
- return { s: value2 };
- if (typeof value2 === "bigint")
- return { bi: value2.toString() };
- if (isError2(value2))
- return { e: { n: value2.name, m: value2.message, s: value2.stack || "" } };
- if (isDate(value2))
- return { d: value2.toJSON() };
- if (isURL(value2))
- return { u: value2.toJSON() };
- if (isRegExp4(value2))
- return { r: { p: value2.source, f: value2.flags } };
- const typedArrayKind = constructorToTypedArrayKind.get(value2.constructor);
- if (typedArrayKind)
- return { ta: { b: Buffer.from(value2.buffer, value2.byteOffset, value2.byteLength), k: typedArrayKind } };
- const id = visitorInfo.visited.get(value2);
- if (id)
- return { ref: id };
- if (Array.isArray(value2)) {
- const a = [];
- const id2 = ++visitorInfo.lastId;
- visitorInfo.visited.set(value2, id2);
- for (let i = 0; i < value2.length; ++i)
- a.push(innerSerializeValue(value2[i], handleSerializer, visitorInfo, [...accessChain, i]));
- return { a, id: id2 };
- }
- if (typeof value2 === "object") {
- const o = [];
- const id2 = ++visitorInfo.lastId;
- visitorInfo.visited.set(value2, id2);
- for (const name of Object.keys(value2))
- o.push({ k: name, v: innerSerializeValue(value2[name], handleSerializer, visitorInfo, [...accessChain, name]) });
- return { o, id: id2 };
- }
- throw new Error(`Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`);
-}
-function accessChainToDisplayString(accessChain) {
- const chainString = accessChain.map((accessor, i) => {
- if (typeof accessor === "string")
- return i ? `.${accessor}` : accessor;
- return `[${accessor}]`;
- }).join("");
- return chainString.length > 0 ? ` at position "${chainString}"` : "";
-}
-function isRegExp4(obj) {
- return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";
-}
-function isDate(obj) {
- return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";
-}
-function isURL(obj) {
- return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";
-}
-function isError2(obj) {
- const proto = obj ? Object.getPrototypeOf(obj) : null;
- return obj instanceof Error || proto?.name === "Error" || proto && isError2(proto);
-}
-var typedArrayKindToConstructor, constructorToTypedArrayKind;
-var init_serializers = __esm({
- "packages/playwright-core/src/protocol/serializers.ts"() {
- "use strict";
- typedArrayKindToConstructor = {
- i8: Int8Array,
- ui8: Uint8Array,
- ui8c: Uint8ClampedArray,
- i16: Int16Array,
- ui16: Uint16Array,
- i32: Int32Array,
- ui32: Uint32Array,
- f32: Float32Array,
- f64: Float64Array,
- bi64: BigInt64Array,
- bui64: BigUint64Array
- };
- constructorToTypedArrayKind = new Map(Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k]));
- }
-});
-
-// packages/playwright-core/src/server/errors.ts
-function isTargetClosedError(error) {
- return error instanceof TargetClosedError || error.name === "TargetClosedError";
-}
-function serializeError(e) {
- if (isError(e))
- return { error: { message: e.message, stack: e.stack, name: e.name } };
- return { value: serializeValue(e, (value2) => ({ fallThrough: value2 })) };
-}
-function parseError(error) {
- if (!error.error) {
- if (error.value === void 0)
- throw new Error("Serialized error must have either an error or a value");
- return parseSerializedValue(error.value, void 0);
- }
- const e = new Error(error.error.message);
- e.stack = error.error.stack || "";
- e.name = error.error.name;
- return e;
-}
-var CustomError, TimeoutError, TargetClosedError;
-var init_errors = __esm({
- "packages/playwright-core/src/server/errors.ts"() {
- "use strict";
- init_rtti();
- init_serializers();
- CustomError = class extends Error {
- constructor(message) {
- super(message);
- this.name = this.constructor.name;
- }
- };
- TimeoutError = class extends CustomError {
- };
- TargetClosedError = class extends CustomError {
- constructor(cause, logs) {
- super((cause || "Target page, context or browser has been closed") + (logs || ""));
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/progress.ts
-function isAbortError(error) {
- return error instanceof TimeoutError || !!error[kAbortErrorSymbol];
-}
-async function raceUncancellableOperationWithCleanup(progress2, run, cleanup) {
- let aborted = false;
- try {
- return await progress2.race(run().then(async (t) => {
- if (aborted)
- await cleanup(t);
- return t;
- }));
- } catch (error) {
- aborted = true;
- throw error;
- }
-}
-var ProgressController, kAbortErrorSymbol, nullProgress;
-var init_progress = __esm({
- "packages/playwright-core/src/server/progress.ts"() {
- "use strict";
- init_manualPromise();
- init_assert();
- init_time();
- init_debugLogger();
- init_errors();
- ProgressController = class _ProgressController {
- constructor(metadata, onCallLog) {
- this._forceAbortPromise = new ManualPromise();
- this._donePromise = new ManualPromise();
- this._state = "before";
- this.metadata = metadata || { id: "", startTime: 0, endTime: 0, type: "Internal", method: "", params: {}, log: [], internal: true };
- this._onCallLog = onCallLog;
- this._forceAbortPromise.catch((e) => null);
- this._controller = new AbortController();
- }
- static createForSdkObject(sdkObject, callMetadata) {
- const logName = sdkObject.logName || "api";
- return new _ProgressController(callMetadata, (message) => {
- if (logName === "api" && sdkObject.attribution.playwright?.options.isInternalPlaywright)
- return;
- debugLogger.log(logName, message);
- sdkObject.instrumentation.onCallLog(sdkObject, callMetadata, logName, message);
- });
- }
- async abort(error) {
- if (this._state === "running") {
- error[kAbortErrorSymbol] = true;
- this._state = { error };
- this._forceAbortPromise.reject(error);
- this._controller.abort(error);
- }
- await this._donePromise;
- }
- async run(task, timeout) {
- const deadline = timeout ? monotonicTime() + timeout : 0;
- assert(this._state === "before");
- this._state = "running";
- let timer;
- let outerProgress;
- let allowConcurrent = false;
- const progress2 = {
- timeout: timeout ?? 0,
- deadline,
- disableTimeout: () => {
- clearTimeout(timer);
- },
- log: (message) => {
- if (this._state === "running")
- this.metadata.log.push(message);
- this._onCallLog?.(message);
- },
- metadata: this.metadata,
- setAllowConcurrentOrNestedRaces: (allow) => {
- allowConcurrent = allow;
- },
- race: (promise) => {
- if (process.env.PW_DETECT_NESTED_PROGRESS) {
- const innerProgress = new Error().stack;
- if (outerProgress && !allowConcurrent && outerProgress !== innerProgress) {
- console.error("Cannot call race() inside another race()");
- console.error("<<<<>>>>:", outerProgress);
- console.error("<<<<>>>>:", innerProgress);
- }
- outerProgress = innerProgress;
- }
- const promises = Array.isArray(promise) ? promise : [promise];
- if (!promises.length)
- return Promise.resolve();
- return Promise.race([...promises, this._forceAbortPromise]).finally(() => outerProgress = void 0);
- },
- wait: async (timeout2) => {
- let timer2;
- const promise = new Promise((f) => timer2 = setTimeout(f, timeout2));
- return progress2.race(promise).finally(() => clearTimeout(timer2));
- },
- signal: this._controller.signal
- };
- if (deadline) {
- const timeoutError = new TimeoutError(`Timeout ${timeout}ms exceeded.`);
- timer = setTimeout(() => {
- if (this.metadata.pauseStartTime && !this.metadata.pauseEndTime)
- return;
- if (this._state === "running") {
- this._state = { error: timeoutError };
- this._forceAbortPromise.reject(timeoutError);
- this._controller.abort(timeoutError);
- }
- }, deadline - monotonicTime());
- }
- try {
- const result2 = await task(progress2);
- this._state = "finished";
- return result2;
- } catch (error) {
- this._state = { error };
- throw error;
- } finally {
- clearTimeout(timer);
- this._donePromise.resolve();
- }
- }
- };
- kAbortErrorSymbol = Symbol("kAbortError");
- nullProgress = {
- timeout: 0,
- deadline: 0,
- disableTimeout() {
- },
- log() {
- },
- race(promise) {
- const promises = Array.isArray(promise) ? promise : [promise];
- return Promise.race(promises);
- },
- wait: async (timeout) => await new Promise((f) => setTimeout(f, timeout)),
- signal: new AbortController().signal,
- metadata: {
- id: "",
- startTime: 0,
- endTime: 0,
- type: "",
- method: "",
- params: {},
- log: [],
- internal: true
- },
- setAllowConcurrentOrNestedRaces() {
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/clock.ts
-function parseTicks(value2) {
- if (typeof value2 === "number")
- return value2;
- if (!value2)
- return 0;
- const str = value2;
- const strings = str.split(":");
- const l = strings.length;
- let i = l;
- let ms = 0;
- let parsed;
- if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
- throw new Error(
- `Clock only understands numbers, 'mm:ss' and 'hh:mm:ss'`
- );
- }
- while (i--) {
- parsed = parseInt(strings[i], 10);
- if (parsed >= 60)
- throw new Error(`Invalid time ${str}`);
- ms += parsed * Math.pow(60, l - i - 1);
- }
- return ms * 1e3;
-}
-function parseTime(epoch) {
- if (!epoch)
- return 0;
- if (typeof epoch === "number")
- return epoch;
- const parsed = new Date(epoch);
- if (!isFinite(parsed.getTime()))
- throw new Error(`Invalid date: ${epoch}`);
- return parsed.getTime();
-}
-var Clock;
-var init_clock = __esm({
- "packages/playwright-core/src/server/clock.ts"() {
- "use strict";
- init_clockSource();
- init_progress();
- Clock = class {
- constructor(browserContext) {
- this._initScripts = [];
- this._browserContext = browserContext;
- }
- async uninstall(progress2) {
- await progress2.race(Promise.all(this._initScripts.map((script) => script.dispose())));
- this._initScripts = [];
- }
- async fastForward(ticks) {
- await this._installIfNeeded();
- const ticksMillis = parseTicks(ticks);
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('fastForward', ${Date.now()}, ${ticksMillis})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.fastForward(${ticksMillis})`);
- }
- async install(time) {
- await this._installIfNeeded();
- const timeMillis = time !== void 0 ? parseTime(time) : Date.now();
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('install', ${Date.now()}, ${timeMillis})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.install(${timeMillis})`);
- }
- async pauseAt(ticks) {
- await this._installIfNeeded();
- const timeMillis = parseTime(ticks);
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.pauseAt(${timeMillis})`);
- }
- resumeNoReply() {
- if (!this._initScripts.length)
- return;
- const doResume = async () => {
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`);
- };
- doResume().catch(() => {
- });
- }
- async resume(progress2) {
- await progress2.race(this._installIfNeeded());
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`));
- await progress2.race(this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`));
- }
- async setFixedTime(time) {
- await this._installIfNeeded();
- const timeMillis = parseTime(time);
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setFixedTime', ${Date.now()}, ${timeMillis})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.setFixedTime(${timeMillis})`);
- }
- async setSystemTime(time) {
- await this._installIfNeeded();
- const timeMillis = parseTime(time);
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setSystemTime', ${Date.now()}, ${timeMillis})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.setSystemTime(${timeMillis})`);
- }
- async runFor(ticks) {
- await this._installIfNeeded();
- const ticksMillis = parseTicks(ticks);
- this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('runFor', ${Date.now()}, ${ticksMillis})`));
- await this._evaluateInFrames(`globalThis.__pwClock.controller.runFor(${ticksMillis})`);
- }
- async _installIfNeeded() {
- if (this._initScripts.length)
- return;
- const script = `(() => {
- const module = {};
- ${source}
- if (!globalThis.__pwClock)
- globalThis.__pwClock = (module.exports.inject())(globalThis, ${JSON.stringify(this._browserContext._browser.options.name)});
- })();`;
- const initScript = await this._browserContext.addInitScript(nullProgress, script);
- await this._evaluateInFrames(script);
- this._initScripts.push(initScript);
- }
- async _evaluateInFrames(script) {
- await this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: true });
- }
- };
- }
-});
-
-// packages/playwright-core/src/generated/webAuthnSource.ts
-var source2;
-var init_webAuthnSource = __esm({
- "packages/playwright-core/src/generated/webAuthnSource.ts"() {
- "use strict";
- source2 = `
-var __commonJS = obj => {
- let required = false;
- let result;
- return function __require() {
- if (!required) {
- required = true;
- let fn;
- for (const name in obj) { fn = obj[name]; break; }
- const module = { exports: {} };
- fn(module.exports, module);
- result = module.exports;
- }
- return result;
- }
-};
-var __export = (target, all) => {for (var name in all) target[name] = all[name];};
-var __toESM = mod => ({ ...mod, 'default': mod });
-var __toCommonJS = mod => ({ ...mod, __esModule: true });
-
-
-// packages/injected/src/webAuthn.ts
-var webAuthn_exports = {};
-__export(webAuthn_exports, {
- inject: () => inject
-});
-module.exports = __toCommonJS(webAuthn_exports);
-function inject(globalThis) {
- if (globalThis.__pwWebAuthnInstalled)
- return;
- globalThis.__pwWebAuthnInstalled = true;
- const binding = globalThis.__pwWebAuthnBinding;
- if (!binding || !globalThis.navigator)
- return;
- if (!globalThis.navigator.credentials) {
- Object.defineProperty(globalThis.navigator, "credentials", {
- value: { create: async () => null, get: async () => null },
- writable: true,
- configurable: true
- });
- }
- function toBase64Url(buf) {
- const bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
- let s = "";
- for (let i = 0; i < bytes.length; i++)
- s += String.fromCharCode(bytes[i]);
- return globalThis.btoa(s).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
- }
- function fromBase64Url(s) {
- let str = s.replaceAll("-", "+").replaceAll("_", "/");
- while (str.length % 4)
- str += "=";
- const bin = globalThis.atob(str);
- const out = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++)
- out[i] = bin.charCodeAt(i);
- return out.buffer;
- }
- const PublicKeyCredentialCtor = globalThis.PublicKeyCredential;
- const AuthAttestationResponseCtor = globalThis.AuthenticatorAttestationResponse;
- const AuthAssertionResponseCtor = globalThis.AuthenticatorAssertionResponse;
- function defineReadonly(target, props) {
- for (const k of Object.keys(props))
- Object.defineProperty(target, k, { value: props[k], enumerable: true, configurable: true });
- }
- function makeAttestationResponse(clientDataJSON, attestationObject) {
- const proto = (AuthAttestationResponseCtor == null ? void 0 : AuthAttestationResponseCtor.prototype) || Object.prototype;
- const r = Object.create(proto);
- defineReadonly(r, { clientDataJSON, attestationObject });
- r.getTransports = () => ["internal"];
- r.getAuthenticatorData = () => {
- return attestationObject;
- };
- r.getPublicKey = () => null;
- r.getPublicKeyAlgorithm = () => -7;
- return r;
- }
- function makeAssertionResponse(clientDataJSON, authenticatorData, signature, userHandle) {
- const proto = (AuthAssertionResponseCtor == null ? void 0 : AuthAssertionResponseCtor.prototype) || Object.prototype;
- const r = Object.create(proto);
- defineReadonly(r, { clientDataJSON, authenticatorData, signature, userHandle });
- return r;
- }
- function makePublicKeyCredential(id, response) {
- const proto = (PublicKeyCredentialCtor == null ? void 0 : PublicKeyCredentialCtor.prototype) || Object.prototype;
- const cred = Object.create(proto);
- defineReadonly(cred, {
- id,
- rawId: fromBase64Url(id),
- type: "public-key",
- authenticatorAttachment: "platform",
- response
- });
- cred.getClientExtensionResults = () => ({});
- cred.toJSON = () => ({ id, rawId: id, type: "public-key", response: {} });
- return cred;
- }
- function toBuf(x) {
- if (!x)
- return new ArrayBuffer(0);
- if (x instanceof ArrayBuffer)
- return x;
- const v = x;
- const out = new Uint8Array(v.byteLength);
- out.set(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
- return out.buffer;
- }
- function failure(name, message) {
- const Ctor = globalThis.DOMException || Error;
- throw new Ctor(message, name);
- }
- const origCreate = globalThis.navigator.credentials.create.bind(globalThis.navigator.credentials);
- const origGet = globalThis.navigator.credentials.get.bind(globalThis.navigator.credentials);
- globalThis.navigator.credentials.create = async function(options) {
- var _a, _b, _c, _d, _e, _f, _g;
- if (!options || !options.publicKey)
- return origCreate(options);
- const pk = options.publicKey;
- const req = {
- type: "create",
- origin: globalThis.location.origin,
- challenge: toBase64Url(toBuf(pk.challenge)),
- rp: { id: (_a = pk.rp) == null ? void 0 : _a.id, name: ((_b = pk.rp) == null ? void 0 : _b.name) || "" },
- user: {
- id: toBase64Url(toBuf((_c = pk.user) == null ? void 0 : _c.id)),
- name: ((_d = pk.user) == null ? void 0 : _d.name) || "",
- displayName: ((_e = pk.user) == null ? void 0 : _e.displayName) || ""
- },
- pubKeyCredParams: (pk.pubKeyCredParams || []).map((p) => ({ type: p.type, alg: p.alg })),
- excludeCredentials: (pk.excludeCredentials || []).map((c) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })),
- userVerification: (_f = pk.authenticatorSelection) == null ? void 0 : _f.userVerification,
- residentKey: (_g = pk.authenticatorSelection) == null ? void 0 : _g.residentKey
- };
- const result = await binding(req);
- if (!result.ok)
- failure(result.name, result.message);
- const resp = makeAttestationResponse(fromBase64Url(result.clientDataJSON), fromBase64Url(result.attestationObject));
- return makePublicKeyCredential(result.id, resp);
- };
- globalThis.navigator.credentials.get = async function(options) {
- if (!options || !options.publicKey)
- return origGet(options);
- const pk = options.publicKey;
- const req = {
- type: "get",
- origin: globalThis.location.origin,
- challenge: toBase64Url(toBuf(pk.challenge)),
- rpId: pk.rpId || new URL(globalThis.location.origin).hostname,
- allowCredentials: (pk.allowCredentials || []).map((c) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })),
- userVerification: pk.userVerification
- };
- const result = await binding(req);
- if (!result.ok)
- failure(result.name, result.message);
- const resp = makeAssertionResponse(
- fromBase64Url(result.clientDataJSON),
- fromBase64Url(result.authenticatorData),
- fromBase64Url(result.signature),
- result.userHandle ? fromBase64Url(result.userHandle) : null
- );
- return makePublicKeyCredential(result.id, resp);
- };
- if (PublicKeyCredentialCtor) {
- PublicKeyCredentialCtor.isUserVerifyingPlatformAuthenticatorAvailable = async () => true;
- PublicKeyCredentialCtor.isConditionalMediationAvailable = async () => true;
- }
-}
-`;
- }
-});
-
-// packages/playwright-core/src/server/credentials.ts
-function toPublic(r) {
- return { id: r.id, rpId: r.rpId, userHandle: r.userHandle, privateKey: r.privateKey, publicKey: r.publicKey };
-}
-function randomBase64Url(bytes) {
- return bufToB64Url(import_crypto6.default.randomBytes(bytes));
-}
-function bufToB64Url(b) {
- return b.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
-}
-function b64UrlToBuf(s) {
- return Buffer.from(s, "base64url");
-}
-function u32ToBytes(n) {
- const b = Buffer.alloc(4);
- b.writeUInt32BE(n >>> 0, 0);
- return b;
-}
-function cborHead(major2, value2) {
- const m = major2 << 5;
- if (value2 < 24)
- return Buffer.from([m | value2]);
- if (value2 < 256)
- return Buffer.from([m | 24, value2]);
- if (value2 < 65536)
- return Buffer.from([m | 25, value2 >> 8 & 255, value2 & 255]);
- return Buffer.from([m | 26, value2 >>> 24 & 255, value2 >> 16 & 255, value2 >> 8 & 255, value2 & 255]);
-}
-function cborUint(v) {
- return cborHead(0, v);
-}
-function cborNint(v) {
- return cborHead(1, -1 - v);
-}
-function cborBytes(b) {
- return Buffer.concat([cborHead(2, b.length), b]);
-}
-function cborText(s) {
- const b = Buffer.from(s, "utf8");
- return Buffer.concat([cborHead(3, b.length), b]);
-}
-function cborMap(entries) {
- return Buffer.concat([cborHead(5, entries.length), ...entries.flatMap(([k, v]) => [k, v])]);
-}
-function encodeCoseEs256PublicKey(publicKey) {
- const jwk = publicKey.export({ format: "jwk" });
- const x = Buffer.from(jwk.x, "base64url");
- const y = Buffer.from(jwk.y, "base64url");
- return cborMap([
- [cborUint(1), cborUint(2)],
- // kty = EC2
- [cborUint(3), cborNint(-7)],
- // alg = ES256
- [cborNint(-1), cborUint(1)],
- // crv = P-256
- [cborNint(-2), cborBytes(x)],
- [cborNint(-3), cborBytes(y)]
- ]);
-}
-function encodeAttestationObjectNone(authData) {
- return cborMap([
- [cborText("fmt"), cborText("none")],
- [cborText("attStmt"), cborMap([])],
- [cborText("authData"), cborBytes(authData)]
- ]);
-}
-var import_crypto6, kBindingName, kAuthenticatorAAGUID, Credentials;
-var init_credentials = __esm({
- "packages/playwright-core/src/server/credentials.ts"() {
- "use strict";
- import_crypto6 = __toESM(require("crypto"));
- init_webAuthnSource();
- init_progress();
- kBindingName = "__pwWebAuthnBinding";
- kAuthenticatorAAGUID = Buffer.alloc(16);
- Credentials = class {
- constructor(browserContext) {
- this._initScripts = [];
- this._installed = false;
- this._registry = /* @__PURE__ */ new Map();
- this._browserContext = browserContext;
- }
- async create(options) {
- let privateKey = options.privateKey;
- let publicKey = options.publicKey;
- if (!privateKey || !publicKey) {
- const pair = import_crypto6.default.generateKeyPairSync("ec", { namedCurve: "P-256" });
- privateKey = bufToB64Url(pair.privateKey.export({ format: "der", type: "pkcs8" }));
- publicKey = bufToB64Url(pair.publicKey.export({ format: "der", type: "spki" }));
- }
- const record = {
- id: options.id || randomBase64Url(16),
- rpId: options.rpId,
- userHandle: options.userHandle || randomBase64Url(16),
- privateKey,
- publicKey,
- signCount: 0,
- isResident: true
- };
- this._registry.set(record.id, record);
- return toPublic(record);
- }
- async get(filter) {
- return [...this._registry.values()].filter((c) => {
- if (filter?.rpId && c.rpId !== filter.rpId)
- return false;
- if (filter?.id && c.id !== filter.id)
- return false;
- return true;
- }).map(toPublic);
- }
- async delete(id) {
- this._registry.delete(id);
- }
- async dispose(progress2) {
- await progress2.race(Promise.all(this._initScripts.map((s) => s.dispose())));
- this._initScripts = [];
- this._installed = false;
- this._registry.clear();
- }
- async install(progress2) {
- if (this._installed)
- return;
- this._installed = true;
- await this._browserContext.exposeBinding(progress2, kBindingName, async (_source, payload) => {
- try {
- if (payload?.type === "create")
- return await this._handleCreate(payload);
- if (payload?.type === "get")
- return this._handleGet(payload);
- } catch (e) {
- return { ok: false, name: "NotAllowedError", message: e.message };
- }
- return { ok: false, name: "NotAllowedError", message: "Unknown WebAuthn request" };
- });
- const script = `(() => {
- const module = {};
- ${source2}
- module.exports.inject()(globalThis);
- })();`;
- const initScript = await this._browserContext.addInitScript(nullProgress, script);
- this._initScripts.push(initScript);
- await progress2.race(this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: false }));
- }
- async _handleCreate(req) {
- const rpId = req.rp?.id || new URL(req.origin).hostname;
- const userHandle = req.user.id;
- if (req.excludeCredentials?.length) {
- for (const desc of req.excludeCredentials) {
- if (this._registry.has(desc.id))
- return { ok: false, name: "InvalidStateError", message: "Credential excluded" };
- }
- }
- const pair = import_crypto6.default.generateKeyPairSync("ec", { namedCurve: "P-256" });
- const privateKey = bufToB64Url(pair.privateKey.export({ format: "der", type: "pkcs8" }));
- const publicKey = bufToB64Url(pair.publicKey.export({ format: "der", type: "spki" }));
- const credentialId = import_crypto6.default.randomBytes(16);
- const credentialIdB64 = bufToB64Url(credentialId);
- const record = {
- id: credentialIdB64,
- rpId,
- userHandle,
- privateKey,
- publicKey,
- signCount: 0,
- isResident: req.residentKey === "required" || req.residentKey === "preferred"
- };
- this._registry.set(credentialIdB64, record);
- const clientDataJSON = Buffer.from(JSON.stringify({
- type: "webauthn.create",
- challenge: req.challenge,
- origin: req.origin,
- crossOrigin: false
- }));
- const rpIdHash = import_crypto6.default.createHash("sha256").update(rpId).digest();
- const flags = 1 | 4 | 64;
- const signCountBuf = u32ToBytes(record.signCount);
- const cosePublicKey = encodeCoseEs256PublicKey(pair.publicKey);
- const credIdLenBuf = Buffer.from([credentialId.length >> 8 & 255, credentialId.length & 255]);
- const attestedCredentialData = Buffer.concat([kAuthenticatorAAGUID, credIdLenBuf, credentialId, cosePublicKey]);
- const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf, attestedCredentialData]);
- const attestationObject = encodeAttestationObjectNone(authData);
- return {
- ok: true,
- id: credentialIdB64,
- clientDataJSON: bufToB64Url(clientDataJSON),
- attestationObject: bufToB64Url(attestationObject)
- };
- }
- _handleGet(req) {
- const rpId = req.rpId || new URL(req.origin).hostname;
- let candidate;
- if (req.allowCredentials?.length) {
- for (const desc of req.allowCredentials) {
- const c = this._registry.get(desc.id);
- if (c && c.rpId === rpId) {
- candidate = c;
- break;
- }
- }
- } else {
- for (const c of this._registry.values()) {
- if (c.rpId === rpId && c.isResident) {
- candidate = c;
- break;
- }
- }
- }
- if (!candidate)
- return { ok: false, name: "NotAllowedError", message: "No matching credential" };
- const clientDataJSON = Buffer.from(JSON.stringify({
- type: "webauthn.get",
- challenge: req.challenge,
- origin: req.origin,
- crossOrigin: false
- }));
- const rpIdHash = import_crypto6.default.createHash("sha256").update(rpId).digest();
- const flags = 1 | 4;
- candidate.signCount += 1;
- const signCountBuf = u32ToBytes(candidate.signCount);
- const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf]);
- const clientDataHash = import_crypto6.default.createHash("sha256").update(clientDataJSON).digest();
- const toSign = Buffer.concat([authData, clientDataHash]);
- const privateKey = import_crypto6.default.createPrivateKey({ key: b64UrlToBuf(candidate.privateKey), format: "der", type: "pkcs8" });
- const signature = import_crypto6.default.sign("sha256", toSign, privateKey);
- return {
- ok: true,
- id: candidate.id,
- clientDataJSON: bufToB64Url(clientDataJSON),
- authenticatorData: bufToB64Url(authData),
- signature: bufToB64Url(signature),
- userHandle: candidate.userHandle || null
- };
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/instrumentation.ts
-function createRootSdkObject() {
- const fakeParent = { attribution: {}, instrumentation: createInstrumentation() };
- const root = new SdkObject(fakeParent);
- root.guid = "";
- return root;
-}
-function createInstrumentation() {
- const listeners = /* @__PURE__ */ new Map();
- const lastListeners = /* @__PURE__ */ new Map();
- return new Proxy({}, {
- get: (obj, prop) => {
- if (typeof prop !== "string")
- return obj[prop];
- if (prop === "addListener") {
- return (listener, context2, options) => {
- if (options?.order === "last")
- lastListeners.set(listener, context2);
- else
- listeners.set(listener, context2);
- };
- }
- if (prop === "removeListener") {
- return (listener) => {
- listeners.delete(listener);
- lastListeners.delete(listener);
- };
- }
- if (!prop.startsWith("on"))
- return obj[prop];
- return async (sdkObject, ...params2) => {
- for (const [listener, context2] of listeners) {
- if (!context2 || sdkObject.attribution.context === context2)
- await listener[prop]?.(sdkObject, ...params2);
- }
- for (const [listener, context2] of lastListeners) {
- if (!context2 || sdkObject.attribution.context === context2)
- await listener[prop]?.(sdkObject, ...params2);
- }
- };
- }
- });
-}
-var import_events3, SdkObject;
-var init_instrumentation = __esm({
- "packages/playwright-core/src/server/instrumentation.ts"() {
- "use strict";
- import_events3 = require("events");
- init_crypto();
- init_debugLogger();
- SdkObject = class extends import_events3.EventEmitter {
- constructor(parent, guidPrefix, guid) {
- super();
- this.guid = guid || `${guidPrefix || ""}@${createGuid()}`;
- this.setMaxListeners(0);
- this.attribution = { ...parent.attribution };
- this.instrumentation = parent.instrumentation;
- }
- apiLog(message) {
- if (!this.attribution.playwright.options.isInternalPlaywright)
- debugLogger.log("api", message);
- }
- closeReason() {
- return this.attribution.worker?._closeReason || this.attribution.page?._closeReason || this.attribution.context?._closeReason || this.attribution.browser?._closeReason;
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/debugger.ts
-function matchesLocation(metadata, location2) {
- return !!metadata.location?.file.includes(location2.file) && (location2.line === void 0 || metadata.location.line === location2.line) && (location2.column === void 0 || metadata.location.column === location2.column);
-}
-var symbol, Debugger;
-var init_debugger = __esm({
- "packages/playwright-core/src/server/debugger.ts"() {
- "use strict";
- init_protocolMetainfo();
- init_time();
- init_instrumentation();
- init_browserContext();
- symbol = Symbol("Debugger");
- Debugger = class _Debugger extends SdkObject {
- constructor(context2) {
- super(context2, "debugger");
- this._pauseAt = {};
- this._enabled = false;
- this._pauseBeforeWaitingActions = false;
- this._muted = false;
- this._context = context2;
- this._context[symbol] = this;
- context2.instrumentation.addListener(this, context2, { order: "last" });
- this._context.once(BrowserContext.Events.Close, () => {
- this._context.instrumentation.removeListener(this);
- });
- }
- static {
- this.Events = {
- PausedStateChanged: "pausedstatechanged"
- };
- }
- requestPause(progress2) {
- if (this.isPaused())
- throw new Error("Debugger is already paused");
- this.setPauseBeforeWaitingActions();
- this.setPauseAt({ next: true });
- }
- doResume(progress2) {
- if (!this.isPaused())
- throw new Error("Debugger is not paused");
- this.resume();
- }
- next(progress2) {
- if (!this.isPaused())
- throw new Error("Debugger is not paused");
- this.setPauseBeforeWaitingActions();
- this.setPauseAt({ next: true });
- this.resume();
- }
- runTo(progress2, location2) {
- if (!this.isPaused())
- throw new Error("Debugger is not paused");
- this.setPauseBeforeWaitingActions();
- this.setPauseAt({ location: location2 });
- this.resume();
- }
- async setMuted(muted) {
- this._muted = muted;
- }
- async onBeforeCall(sdkObject, metadata) {
- if (this._muted || metadata.internal)
- return;
- const metainfo = getMetainfo(metadata);
- const pauseOnPauseCall = this._enabled && metadata.type === "BrowserContext" && metadata.method === "pause";
- const pauseBeforeAction = !!this._pauseAt.next && !!metainfo?.pause && (this._pauseBeforeWaitingActions || !metainfo?.isAutoWaiting);
- const pauseOnLocation = !!this._pauseAt.location && matchesLocation(metadata, this._pauseAt.location);
- if (pauseOnPauseCall || pauseBeforeAction || pauseOnLocation)
- await this._pause(sdkObject, metadata);
- }
- async onBeforeInputAction(sdkObject, metadata) {
- if (this._muted || metadata.internal)
- return;
- const metainfo = getMetainfo(metadata);
- const pauseBeforeInput = !!this._pauseAt.next && !!metainfo?.pause && !!metainfo?.isAutoWaiting && !this._pauseBeforeWaitingActions;
- if (pauseBeforeInput)
- await this._pause(sdkObject, metadata);
- }
- async _pause(sdkObject, metadata) {
- if (this._muted || metadata.internal)
- return;
- if (this._pausedCall)
- return;
- this._pauseAt = {};
- metadata.pauseStartTime = monotonicTime();
- const result2 = new Promise((resolve) => {
- this._pausedCall = { metadata, sdkObject, resolve };
- });
- this.emit(_Debugger.Events.PausedStateChanged);
- return result2;
- }
- resume() {
- if (!this._pausedCall)
- return;
- this._pausedCall.metadata.pauseEndTime = monotonicTime();
- this._pausedCall.resolve();
- this._pausedCall = void 0;
- this.emit(_Debugger.Events.PausedStateChanged);
- }
- setPauseBeforeWaitingActions() {
- this._pauseBeforeWaitingActions = true;
- }
- setPauseAt(at = {}) {
- this._enabled = true;
- this._pauseAt = at;
- }
- isPaused(metadata) {
- if (metadata)
- return this._pausedCall?.metadata === metadata;
- return !!this._pausedCall;
- }
- pausedDetails() {
- return this._pausedCall;
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/dialog.ts
-var Dialog, DialogManager;
-var init_dialog = __esm({
- "packages/playwright-core/src/server/dialog.ts"() {
- "use strict";
- init_assert();
- init_instrumentation();
- Dialog = class extends SdkObject {
- constructor(page, type3, message, onHandle, defaultValue) {
- super(page, "dialog");
- this._handled = false;
- this._page = page;
- this._type = type3;
- this._message = message;
- this._onHandle = onHandle;
- this._defaultValue = defaultValue || "";
- }
- async accept(progress2, promptText) {
- await progress2.race(this._accept(promptText));
- }
- async dismiss(progress2) {
- await progress2.race(this._dismiss());
- }
- page() {
- return this._page;
- }
- type() {
- return this._type;
- }
- message() {
- return this._message;
- }
- defaultValue() {
- return this._defaultValue;
- }
- async _accept(promptText) {
- assert(!this._handled, "Cannot accept dialog which is already handled!");
- this._handled = true;
- this._page.browserContext.dialogManager._dialogWillClose(this);
- await this._onHandle(true, promptText);
- }
- async _dismiss() {
- assert(!this._handled, "Cannot dismiss dialog which is already handled!");
- this._handled = true;
- this._page.browserContext.dialogManager._dialogWillClose(this);
- await this._onHandle(false);
- }
- async _close() {
- if (this._type === "beforeunload")
- await this._accept();
- else
- await this._dismiss();
- }
- };
- DialogManager = class {
- constructor(instrumentation) {
- this._dialogHandlers = /* @__PURE__ */ new Set();
- this._openedDialogs = /* @__PURE__ */ new Set();
- this._instrumentation = instrumentation;
- }
- dialogDidOpen(dialog) {
- for (const frame of dialog.page().frameManager.frames())
- frame.invalidateNonStallingEvaluations("JavaScript dialog interrupted evaluation");
- this._openedDialogs.add(dialog);
- this._instrumentation.onDialog(dialog);
- let hasHandlers = false;
- for (const handler of this._dialogHandlers) {
- if (handler(dialog))
- hasHandlers = true;
- }
- if (!hasHandlers)
- dialog._close().then(() => {
- });
- }
- _dialogWillClose(dialog) {
- this._openedDialogs.delete(dialog);
- }
- addDialogHandler(handler) {
- this._dialogHandlers.add(handler);
- }
- removeDialogHandler(handler) {
- this._dialogHandlers.delete(handler);
- if (!this._dialogHandlers.size) {
- for (const dialog of this._openedDialogs)
- dialog._close().catch(() => {
- });
- }
- }
- hasOpenDialogsForPage(page) {
- return [...this._openedDialogs].some((dialog) => dialog.page() === page);
- }
- async closeBeforeUnloadDialogs() {
- await Promise.all([...this._openedDialogs].map(async (dialog) => {
- if (dialog.type() === "beforeunload")
- await dialog._dismiss();
- }));
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/network.ts
-function filterCookies(cookies, urls) {
- const parsedURLs = urls.map((s) => new URL(s));
- return cookies.filter((c) => {
- if (!parsedURLs.length)
- return true;
- for (const parsedURL of parsedURLs) {
- let domain = c.domain;
- if (!domain.startsWith("."))
- domain = "." + domain;
- if (!("." + parsedURL.hostname).endsWith(domain))
- continue;
- if (!parsedURL.pathname.startsWith(c.path))
- continue;
- if (parsedURL.protocol !== "https:" && !isLocalHostname(parsedURL.hostname) && c.secure)
- continue;
- return true;
- }
- return false;
- });
-}
-function isLocalHostname(hostname) {
- return hostname === "localhost" || hostname.endsWith(".localhost");
-}
-function isForbiddenHeader(name, value2) {
- const lowerName = name.toLowerCase();
- if (FORBIDDEN_HEADER_NAMES.has(lowerName))
- return true;
- if (lowerName.startsWith("proxy-"))
- return true;
- if (lowerName.startsWith("sec-"))
- return true;
- if (lowerName === "x-http-method" || lowerName === "x-http-method-override" || lowerName === "x-method-override") {
- if (value2 && FORBIDDEN_METHODS.has(value2.toUpperCase()))
- return true;
- }
- return false;
-}
-function applyHeadersOverrides(original, overrides) {
- const forbiddenHeaders = original.filter((header) => isForbiddenHeader(header.name, header.value));
- const allowedHeaders = overrides.filter((header) => !isForbiddenHeader(header.name, header.value));
- return mergeHeaders([allowedHeaders, forbiddenHeaders]);
-}
-function rewriteCookies(cookies) {
- return cookies.map((c) => {
- assert(c.url || c.domain && c.path, "Cookie should have a url or a domain/path pair");
- assert(!(c.url && c.domain), "Cookie should have either url or domain");
- assert(!(c.url && c.path), "Cookie should have either url or path");
- assert(!(c.expires && c.expires < 0 && c.expires !== -1), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed");
- assert(!(c.expires && c.expires > 0 && c.expires > kMaxCookieExpiresDateInSeconds), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed");
- const copy = { ...c };
- if (copy.url) {
- assert(copy.url !== "about:blank", `Blank page can not have cookie "${c.name}"`);
- assert(!copy.url.startsWith("data:"), `Data URL page can not have cookie "${c.name}"`);
- const url2 = new URL(copy.url);
- copy.domain = url2.hostname;
- copy.path = url2.pathname.substring(0, url2.pathname.lastIndexOf("/") + 1);
- copy.secure = url2.protocol === "https:";
- }
- return copy;
- });
-}
-function parseURL2(url2) {
- try {
- return new URL(url2);
- } catch (e) {
- return null;
- }
-}
-function stripFragmentFromUrl(url2) {
- if (!url2.includes("#"))
- return url2;
- return url2.substring(0, url2.indexOf("#"));
-}
-function statusText(status) {
- return STATUS_TEXTS[String(status)] || "Unknown";
-}
-function singleHeader(name, value2) {
- return [{ name, value: value2 }];
-}
-function mergeHeaders(headers) {
- const lowerCaseToValue = /* @__PURE__ */ new Map();
- const lowerCaseToOriginalCase = /* @__PURE__ */ new Map();
- for (const h of headers) {
- if (!h)
- continue;
- for (const { name, value: value2 } of h) {
- const lower = name.toLowerCase();
- lowerCaseToOriginalCase.set(lower, name);
- lowerCaseToValue.set(lower, value2);
- }
- }
- const result2 = [];
- for (const [lower, value2] of lowerCaseToValue)
- result2.push({ name: lowerCaseToOriginalCase.get(lower), value: value2 });
- return result2;
-}
-function headersSize(headers) {
- let result2 = 0;
- for (const header of headers)
- result2 += header.name.length + header.value.length + 4;
- return result2;
-}
-function requestHeadersSize(headers, url2, method) {
- let result2 = 4;
- result2 += method.length;
- result2 += new URL(url2).pathname.length;
- result2 += 8;
- result2 += headersSize(headers);
- return result2;
-}
-function responseHeadersSize(headers, statusText2) {
- let result2 = 4;
- result2 += 8;
- result2 += 3;
- result2 += statusText2.length;
- result2 += headersSize(headers);
- result2 += 2;
- return result2;
-}
-var FORBIDDEN_HEADER_NAMES, FORBIDDEN_METHODS, kMaxCookieExpiresDateInSeconds, Request, Route, Response2, WebSocket, STATUS_TEXTS;
-var init_network2 = __esm({
- "packages/playwright-core/src/server/network.ts"() {
- "use strict";
- init_manualPromise();
- init_assert();
- init_browserContext();
- init_fetch();
- init_instrumentation();
- FORBIDDEN_HEADER_NAMES = /* @__PURE__ */ new Set([
- "accept-charset",
- "accept-encoding",
- "access-control-request-headers",
- "access-control-request-method",
- "connection",
- "content-length",
- "cookie",
- "date",
- "dnt",
- "expect",
- "host",
- "keep-alive",
- "origin",
- "referer",
- "set-cookie",
- "te",
- "trailer",
- "transfer-encoding",
- "upgrade",
- "via"
- ]);
- FORBIDDEN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "TRACE", "TRACK"]);
- kMaxCookieExpiresDateInSeconds = 253402300799;
- Request = class _Request extends SdkObject {
- constructor(context2, frame, serviceWorker, redirectedFrom, documentId, url2, resourceType, method, postData, headers, wallTimeMs) {
- super(frame || context2, "request");
- this._response = null;
- this._redirectedTo = null;
- this._failureText = null;
- this._frame = null;
- this._serviceWorker = null;
- this._rawRequestHeadersPromise = new ManualPromise();
- this._waitForResponsePromise = new ManualPromise();
- this._responseEndTiming = -1;
- assert(!url2.startsWith("data:"), "Data urls should not fire requests");
- this._context = context2;
- this._frame = frame;
- this._serviceWorker = serviceWorker;
- this._redirectedFrom = redirectedFrom;
- if (redirectedFrom)
- redirectedFrom._redirectedTo = this;
- this._documentId = documentId;
- this._url = stripFragmentFromUrl(url2);
- this._resourceType = resourceType;
- this._method = method;
- this._postData = postData;
- this._headers = headers;
- this._wallTimeMs = wallTimeMs;
- this._isFavicon = url2.endsWith("/favicon.ico") || !!redirectedFrom?._isFavicon;
- }
- static {
- this.Events = {
- Response: "response"
- };
- }
- wallTimeMs() {
- return this._wallTimeMs;
- }
- async raceWithPageClosure(progress2, promise) {
- const scope = this._serviceWorker?.openScope ?? this._frame?._page.openScope;
- if (scope)
- return await progress2.race(scope.race(promise));
- return await progress2.race(promise);
- }
- async rawRequestHeaders(progress2) {
- return await this.raceWithPageClosure(progress2, this.internalRawRequestHeaders());
- }
- async response(progress2) {
- return await this.raceWithPageClosure(progress2, this._waitForResponse());
- }
- _setFailureText(failureText) {
- this._failureText = failureText;
- this._waitForResponsePromise.resolve(null);
- }
- _applyOverrides(overrides) {
- this._overrides = { ...this._overrides, ...overrides };
- return this._overrides;
- }
- overrides() {
- return this._overrides;
- }
- url() {
- return this._overrides?.url || this._url;
- }
- resourceType() {
- return this._resourceType;
- }
- method() {
- return this._overrides?.method || this._method;
- }
- postDataBuffer() {
- return this._overrides?.postData || this._postData;
- }
- headers() {
- return this._overrides?.headers || this._headers;
- }
- headerValue(name) {
- const lowerCaseName = name.toLowerCase();
- return this.headers().find((h) => h.name.toLowerCase() === lowerCaseName)?.value;
- }
- // "null" means no raw headers available - we'll use provisional headers as raw headers.
- setRawRequestHeaders(headers) {
- if (!this._rawRequestHeadersPromise.isDone())
- this._rawRequestHeadersPromise.resolve(headers || this._headers);
- }
- async internalRawRequestHeaders() {
- return this._overrides?.headers || this._rawRequestHeadersPromise;
- }
- _waitForResponse() {
- return this._waitForResponsePromise;
- }
- _existingResponse() {
- return this._response;
- }
- _setResponse(response2) {
- this._response = response2;
- this._waitForResponsePromise.resolve(response2);
- this.emit(_Request.Events.Response, response2);
- }
- _finalRequest() {
- return this._redirectedTo ? this._redirectedTo._finalRequest() : this;
- }
- frame() {
- return this._frame;
- }
- serviceWorker() {
- return this._serviceWorker;
- }
- isNavigationRequest() {
- return !!this._documentId;
- }
- redirectedFrom() {
- return this._redirectedFrom;
- }
- failure() {
- if (this._failureText === null)
- return null;
- return {
- errorText: this._failureText
- };
- }
- // TODO(bidi): remove once post body is available.
- _setBodySize(size) {
- this._bodySize = size;
- }
- bodySize() {
- return this._bodySize || this.postDataBuffer()?.length || 0;
- }
- async _requestHeadersSize() {
- return requestHeadersSize(await this.internalRawRequestHeaders(), this.url(), this.method());
- }
- };
- Route = class extends SdkObject {
- constructor(request2, delegate) {
- super(request2._frame || request2._context, "route");
- this._handled = false;
- this._futureHandlers = [];
- this._request = request2;
- this._delegate = delegate;
- this._request._context.addRouteInFlight(this);
- }
- handle(handlers) {
- this._futureHandlers = [...handlers];
- this.continue({ isFallback: true }).catch(() => {
- });
- }
- async removeHandler(handler) {
- this._futureHandlers = this._futureHandlers.filter((h) => h !== handler);
- if (handler === this._currentHandler) {
- await this.continue({ isFallback: true }).catch(() => {
- });
- return;
- }
- }
- request() {
- return this._request;
- }
- async abort(errorCode = "failed") {
- this._startHandling();
- this._request._context.emit(BrowserContext.Events.RequestAborted, this._request);
- await this._delegate.abort(errorCode);
- this._endHandling();
- }
- redirectNavigationRequest(url2) {
- this._startHandling();
- assert(this._request.isNavigationRequest());
- this._request.frame().redirectNavigation(url2, this._request._documentId, this._request.headerValue("referer"));
- this._endHandling();
- }
- async fulfill(overrides) {
- this._startHandling();
- let body = overrides.body;
- let isBase64 = overrides.isBase64 || false;
- if (body === void 0) {
- if (overrides.fetchResponseUid) {
- const buffer = this._request._context.fetchRequest.fetchResponses.get(overrides.fetchResponseUid) || APIRequestContext.findResponseBody(overrides.fetchResponseUid);
- assert(buffer, "Fetch response has been disposed");
- body = buffer.toString("base64");
- isBase64 = true;
- } else {
- body = "";
- isBase64 = false;
- }
- } else if (!overrides.status || overrides.status < 200 || overrides.status >= 400) {
- this._request._responseBodyOverride = { body, isBase64 };
- }
- const headers = [...overrides.headers || []];
- this._maybeAddCorsHeaders(headers);
- this._request._context.emit(BrowserContext.Events.RequestFulfilled, this._request);
- await this._delegate.fulfill({
- status: overrides.status || 200,
- headers,
- body,
- isBase64
- });
- this._endHandling();
- }
- // See https://github.com/microsoft/playwright/issues/12929
- _maybeAddCorsHeaders(headers) {
- const origin = this._request.headerValue("origin");
- if (!origin)
- return;
- const requestUrl = new URL(this._request.url());
- if (!requestUrl.protocol.startsWith("http"))
- return;
- if (requestUrl.origin === origin.trim())
- return;
- const corsHeader = headers.find(({ name }) => name === "access-control-allow-origin");
- if (corsHeader)
- return;
- headers.push({ name: "access-control-allow-origin", value: origin });
- headers.push({ name: "access-control-allow-credentials", value: "true" });
- headers.push({ name: "vary", value: "Origin" });
- }
- async continue(overrides) {
- if (overrides.url) {
- const newUrl = new URL(overrides.url);
- const oldUrl = new URL(this._request.url());
- if (oldUrl.protocol !== newUrl.protocol)
- throw new Error("New URL must have same protocol as overridden URL");
- }
- if (overrides.headers) {
- overrides.headers = applyHeadersOverrides(this._request._headers, overrides.headers);
- }
- overrides = this._request._applyOverrides(overrides);
- const nextHandler = this._futureHandlers.shift();
- if (nextHandler) {
- this._currentHandler = nextHandler;
- nextHandler(this, this._request);
- return;
- }
- if (!overrides.isFallback)
- this._request._context.emit(BrowserContext.Events.RequestContinued, this._request);
- this._startHandling();
- await this._delegate.continue(overrides);
- this._endHandling();
- }
- _startHandling() {
- assert(!this._handled, "Route is already handled!");
- this._handled = true;
- this._currentHandler = void 0;
- }
- _endHandling() {
- this._futureHandlers = [];
- this._currentHandler = void 0;
- this._request._context.removeRouteInFlight(this);
- }
- };
- Response2 = class extends SdkObject {
- constructor(request2, status, statusText2, headers, timing, getResponseBodyCallback, fromServiceWorker) {
- super(request2.frame() || request2._context, "response");
- this._contentPromise = null;
- this._finishedPromise = new ManualPromise();
- this._headersMap = /* @__PURE__ */ new Map();
- this._serverAddrPromise = new ManualPromise();
- this._securityDetailsPromise = new ManualPromise();
- this._rawResponseHeadersPromise = new ManualPromise();
- this._httpVersionPromise = new ManualPromise();
- this._encodedBodySizePromise = new ManualPromise();
- this._transferSizePromise = new ManualPromise();
- this._responseHeadersSizePromise = new ManualPromise();
- this._request = request2;
- this._timing = timing;
- this._status = status;
- this._statusText = statusText2;
- this._url = request2.url();
- this._headers = headers;
- for (const { name, value: value2 } of this._headers)
- this._headersMap.set(name.toLowerCase(), value2);
- this._getResponseBodyCallback = getResponseBodyCallback;
- this._request._setResponse(this);
- this._fromServiceWorker = fromServiceWorker;
- }
- async body(progress2) {
- return await this._request.raceWithPageClosure(progress2, this.internalBody());
- }
- async securityDetails(progress2) {
- return await this._request.raceWithPageClosure(progress2, this.internalSecurityDetails());
- }
- async serverAddr(progress2) {
- return await this._request.raceWithPageClosure(progress2, this.internalServerAddr());
- }
- async rawResponseHeaders(progress2) {
- return await this._request.raceWithPageClosure(progress2, this.internalRawResponseHeaders());
- }
- async httpVersion(progress2) {
- return await this._request.raceWithPageClosure(progress2, this.internalHttpVersion());
- }
- async sizes(progress2) {
- return await this._request.raceWithPageClosure(progress2, this.internalSizes());
- }
- _serverAddrFinished(addr) {
- this._serverAddrPromise.resolve(addr);
- }
- _securityDetailsFinished(securityDetails) {
- this._securityDetailsPromise.resolve(securityDetails);
- }
- _requestFinished(responseEndTiming) {
- this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart);
- if (this._timing.requestStart === -1)
- this._timing.requestStart = this._request._responseEndTiming;
- this._finishedPromise.resolve();
- }
- _setHttpVersion(httpVersion) {
- this._httpVersionPromise.resolve(httpVersion);
- }
- url() {
- return this._url;
- }
- status() {
- return this._status;
- }
- statusText() {
- return this._statusText;
- }
- headers() {
- return this._headers;
- }
- headerValue(name) {
- return this._headersMap.get(name);
- }
- // "null" means no raw headers available - we'll use provisional headers as raw headers.
- setRawResponseHeaders(headers) {
- if (!this._rawResponseHeadersPromise.isDone())
- this._rawResponseHeadersPromise.resolve(headers || this._headers);
- }
- setTransferSize(size) {
- this._transferSizePromise.resolve(size);
- }
- setEncodedBodySize(size) {
- this._encodedBodySizePromise.resolve(size);
- }
- setResponseHeadersSize(size) {
- this._responseHeadersSizePromise.resolve(size);
- }
- timing() {
- return this._timing;
- }
- async internalSecurityDetails() {
- return await this._securityDetailsPromise || null;
- }
- async internalServerAddr() {
- return await this._serverAddrPromise || null;
- }
- async internalRawResponseHeaders() {
- return await this._rawResponseHeadersPromise;
- }
- internalBody() {
- if (!this._contentPromise) {
- this._contentPromise = this._finishedPromise.then(async () => {
- if (this._status >= 300 && this._status <= 399)
- throw new Error("Response body is unavailable for redirect responses");
- if (this._request._responseBodyOverride) {
- const { body, isBase64 } = this._request._responseBodyOverride;
- return Buffer.from(body, isBase64 ? "base64" : "utf-8");
- }
- return this._getResponseBodyCallback();
- });
- }
- return this._contentPromise;
- }
- request() {
- return this._request;
- }
- finished() {
- return this._finishedPromise;
- }
- frame() {
- return this._request.frame();
- }
- async internalHttpVersion() {
- const httpVersion = await this._httpVersionPromise || null;
- if (!httpVersion)
- return "HTTP/1.1";
- if (httpVersion === "http/1.1")
- return "HTTP/1.1";
- if (httpVersion === "h2")
- return "HTTP/2.0";
- return httpVersion;
- }
- fromServiceWorker() {
- return this._fromServiceWorker;
- }
- async responseHeadersSize() {
- const availableSize = await this._responseHeadersSizePromise;
- if (availableSize !== null)
- return availableSize;
- return responseHeadersSize(await this._rawResponseHeadersPromise, this.statusText());
- }
- async internalSizes() {
- const requestHeadersSize2 = await this._request._requestHeadersSize();
- const responseHeadersSize2 = await this.responseHeadersSize();
- let encodedBodySize = await this._encodedBodySizePromise;
- if (encodedBodySize === null) {
- const headers = await this._rawResponseHeadersPromise;
- const contentLength = headers.find((h) => h.name.toLowerCase() === "content-length")?.value;
- encodedBodySize = contentLength ? +contentLength : 0;
- }
- let transferSize = await this._transferSizePromise;
- if (transferSize === null) {
- transferSize = responseHeadersSize2 + encodedBodySize;
- }
- return {
- requestBodySize: this._request.bodySize(),
- requestHeadersSize: requestHeadersSize2,
- responseBodySize: encodedBodySize,
- responseHeadersSize: responseHeadersSize2,
- transferSize
- };
- }
- };
- WebSocket = class _WebSocket extends SdkObject {
- constructor(parent, url2) {
- super(parent, "ws");
- this._notified = false;
- this._url = stripFragmentFromUrl(url2);
- }
- static {
- this.Events = {
- Close: "close",
- SocketError: "socketerror",
- FrameReceived: "framereceived",
- FrameSent: "framesent",
- Request: "request",
- Response: "response"
- };
- }
- markAsNotified() {
- if (this._notified)
- return false;
- this._notified = true;
- return true;
- }
- url() {
- return this._url;
- }
- wallTimeMs() {
- return this._wallTimeMs;
- }
- setWallTimeMs(wallTimeMs) {
- this._wallTimeMs = wallTimeMs;
- }
- requestSent(headers) {
- this.emit(_WebSocket.Events.Request, { headers });
- }
- responseReceived(status, statusText2, headers) {
- this.emit(_WebSocket.Events.Response, { status, statusText: statusText2, headers });
- }
- frameSent(opcode, data, wallTimeMs) {
- this.emit(_WebSocket.Events.FrameSent, { opcode, data, wallTimeMs });
- }
- frameReceived(opcode, data, wallTimeMs) {
- this.emit(_WebSocket.Events.FrameReceived, { opcode, data, wallTimeMs });
- }
- error(errorMessage) {
- this.emit(_WebSocket.Events.SocketError, errorMessage);
- }
- closed() {
- this.emit(_WebSocket.Events.Close);
- }
- };
- STATUS_TEXTS = {
- "100": "Continue",
- "101": "Switching Protocols",
- "102": "Processing",
- "103": "Early Hints",
- "200": "OK",
- "201": "Created",
- "202": "Accepted",
- "203": "Non-Authoritative Information",
- "204": "No Content",
- "205": "Reset Content",
- "206": "Partial Content",
- "207": "Multi-Status",
- "208": "Already Reported",
- "226": "IM Used",
- "300": "Multiple Choices",
- "301": "Moved Permanently",
- "302": "Found",
- "303": "See Other",
- "304": "Not Modified",
- "305": "Use Proxy",
- "306": "Switch Proxy",
- "307": "Temporary Redirect",
- "308": "Permanent Redirect",
- "400": "Bad Request",
- "401": "Unauthorized",
- "402": "Payment Required",
- "403": "Forbidden",
- "404": "Not Found",
- "405": "Method Not Allowed",
- "406": "Not Acceptable",
- "407": "Proxy Authentication Required",
- "408": "Request Timeout",
- "409": "Conflict",
- "410": "Gone",
- "411": "Length Required",
- "412": "Precondition Failed",
- "413": "Payload Too Large",
- "414": "URI Too Long",
- "415": "Unsupported Media Type",
- "416": "Range Not Satisfiable",
- "417": "Expectation Failed",
- "418": "I'm a teapot",
- "421": "Misdirected Request",
- "422": "Unprocessable Entity",
- "423": "Locked",
- "424": "Failed Dependency",
- "425": "Too Early",
- "426": "Upgrade Required",
- "428": "Precondition Required",
- "429": "Too Many Requests",
- "431": "Request Header Fields Too Large",
- "451": "Unavailable For Legal Reasons",
- "500": "Internal Server Error",
- "501": "Not Implemented",
- "502": "Bad Gateway",
- "503": "Service Unavailable",
- "504": "Gateway Timeout",
- "505": "HTTP Version Not Supported",
- "506": "Variant Also Negotiates",
- "507": "Insufficient Storage",
- "508": "Loop Detected",
- "510": "Not Extended",
- "511": "Network Authentication Required"
- };
- }
-});
-
-// packages/playwright-core/src/server/cookieStore.ts
-function parseRawCookie(header) {
- const pairs = header.split(";").filter((s) => s.trim().length > 0).map((p) => {
- let key = "";
- let value3 = "";
- const separatorPos = p.indexOf("=");
- if (separatorPos === -1) {
- key = p.trim();
- } else {
- key = p.slice(0, separatorPos).trim();
- value3 = p.slice(separatorPos + 1).trim();
- }
- return [key, value3];
- });
- if (!pairs.length)
- return null;
- const [name, value2] = pairs[0];
- const cookie = {
- name,
- value: value2
- };
- for (let i = 1; i < pairs.length; i++) {
- const [name2, value3] = pairs[i];
- switch (name2.toLowerCase()) {
- case "expires":
- const expiresMs = +new Date(value3);
- if (isFinite(expiresMs)) {
- if (expiresMs <= 0)
- cookie.expires = 0;
- else
- cookie.expires = Math.min(expiresMs / 1e3, kMaxCookieExpiresDateInSeconds);
- }
- break;
- case "max-age":
- const maxAgeSec = parseInt(value3, 10);
- if (isFinite(maxAgeSec)) {
- if (maxAgeSec <= 0)
- cookie.expires = 0;
- else
- cookie.expires = Math.min(Date.now() / 1e3 + maxAgeSec, kMaxCookieExpiresDateInSeconds);
- }
- break;
- case "domain":
- cookie.domain = value3.toLocaleLowerCase() || "";
- if (cookie.domain && !cookie.domain.startsWith(".") && cookie.domain.includes("."))
- cookie.domain = "." + cookie.domain;
- break;
- case "path":
- cookie.path = value3 || "";
- break;
- case "secure":
- cookie.secure = true;
- break;
- case "httponly":
- cookie.httpOnly = true;
- break;
- case "samesite":
- switch (value3.toLowerCase()) {
- case "none":
- cookie.sameSite = "None";
- break;
- case "lax":
- cookie.sameSite = "Lax";
- break;
- case "strict":
- cookie.sameSite = "Strict";
- break;
- }
- break;
- }
- }
- return cookie;
-}
-function domainMatches(value2, domain) {
- if (value2 === domain)
- return true;
- if (!domain.startsWith("."))
- return false;
- value2 = "." + value2;
- return value2.endsWith(domain);
-}
-function pathMatches(value2, path59) {
- if (value2 === path59)
- return true;
- if (!value2.endsWith("/"))
- value2 = value2 + "/";
- if (!path59.endsWith("/"))
- path59 = path59 + "/";
- return value2.startsWith(path59);
-}
-var Cookie, CookieStore;
-var init_cookieStore = __esm({
- "packages/playwright-core/src/server/cookieStore.ts"() {
- "use strict";
- init_network2();
- Cookie = class {
- constructor(data) {
- this._raw = data;
- }
- _name() {
- return this._raw.name;
- }
- // https://datatracker.ietf.org/doc/html/rfc6265#section-5.4
- matches(url2) {
- if (this._raw.secure && (url2.protocol !== "https:" && !isLocalHostname(url2.hostname)))
- return false;
- if (!domainMatches(url2.hostname, this._raw.domain))
- return false;
- if (!pathMatches(url2.pathname, this._raw.path))
- return false;
- return true;
- }
- _equals(other) {
- return this._raw.name === other._raw.name && this._raw.domain === other._raw.domain && this._raw.path === other._raw.path;
- }
- _networkCookie() {
- return this._raw;
- }
- _updateExpiresFrom(other) {
- this._raw.expires = other._raw.expires;
- }
- _expired() {
- if (this._raw.expires === -1)
- return false;
- return this._raw.expires * 1e3 < Date.now();
- }
- };
- CookieStore = class _CookieStore {
- constructor() {
- this._nameToCookies = /* @__PURE__ */ new Map();
- }
- addCookies(cookies) {
- for (const cookie of cookies)
- this._addCookie(new Cookie(cookie));
- }
- cookies(url2) {
- const result2 = [];
- for (const cookie of this._cookiesIterator()) {
- if (cookie.matches(url2))
- result2.push(cookie._networkCookie());
- }
- return result2;
- }
- allCookies() {
- const result2 = [];
- for (const cookie of this._cookiesIterator())
- result2.push(cookie._networkCookie());
- return result2;
- }
- _addCookie(cookie) {
- let set = this._nameToCookies.get(cookie._name());
- if (!set) {
- set = /* @__PURE__ */ new Set();
- this._nameToCookies.set(cookie._name(), set);
- }
- for (const other of set) {
- if (other._equals(cookie))
- set.delete(other);
- }
- set.add(cookie);
- _CookieStore.pruneExpired(set);
- }
- *_cookiesIterator() {
- for (const [name, cookies] of this._nameToCookies) {
- _CookieStore.pruneExpired(cookies);
- for (const cookie of cookies)
- yield cookie;
- if (cookies.size === 0)
- this._nameToCookies.delete(name);
- }
- }
- static pruneExpired(cookies) {
- for (const cookie of cookies) {
- if (cookie._expired())
- cookies.delete(cookie);
- }
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/formData.ts
-function generateUniqueBoundaryString() {
- const charCodes = [];
- for (let i = 0; i < 16; i++)
- charCodes.push(alphaNumericEncodingMap[Math.floor(Math.random() * alphaNumericEncodingMap.length)]);
- return "----WebKitFormBoundary" + String.fromCharCode(...charCodes);
-}
-var mime2, MultipartFormData, alphaNumericEncodingMap;
-var init_formData = __esm({
- "packages/playwright-core/src/server/formData.ts"() {
- "use strict";
- mime2 = require("./utilsBundle").mime;
- MultipartFormData = class {
- constructor() {
- this._chunks = [];
- this._boundary = generateUniqueBoundaryString();
- }
- contentTypeHeader() {
- return `multipart/form-data; boundary=${this._boundary}`;
- }
- addField(name, value2) {
- this._beginMultiPartHeader(name);
- this._finishMultiPartHeader();
- this._chunks.push(Buffer.from(value2));
- this._finishMultiPartField();
- }
- addFileField(name, value2) {
- this._beginMultiPartHeader(name);
- this._chunks.push(Buffer.from(`; filename="${value2.name}"`));
- this._chunks.push(Buffer.from(`\r
-content-type: ${value2.mimeType || mime2.getType(value2.name) || "application/octet-stream"}`));
- this._finishMultiPartHeader();
- this._chunks.push(value2.buffer);
- this._finishMultiPartField();
- }
- finish() {
- this._addBoundary(true);
- return Buffer.concat(this._chunks);
- }
- _beginMultiPartHeader(name) {
- this._addBoundary();
- this._chunks.push(Buffer.from(`content-disposition: form-data; name="${name}"`));
- }
- _finishMultiPartHeader() {
- this._chunks.push(Buffer.from(`\r
-\r
-`));
- }
- _finishMultiPartField() {
- this._chunks.push(Buffer.from(`\r
-`));
- }
- _addBoundary(isLastBoundary) {
- this._chunks.push(Buffer.from("--" + this._boundary));
- if (isLastBoundary)
- this._chunks.push(Buffer.from("--"));
- this._chunks.push(Buffer.from("\r\n"));
- }
- };
- alphaNumericEncodingMap = [
- 65,
- 66,
- 67,
- 68,
- 69,
- 70,
- 71,
- 72,
- 73,
- 74,
- 75,
- 76,
- 77,
- 78,
- 79,
- 80,
- 81,
- 82,
- 83,
- 84,
- 85,
- 86,
- 87,
- 88,
- 89,
- 90,
- 97,
- 98,
- 99,
- 100,
- 101,
- 102,
- 103,
- 104,
- 105,
- 106,
- 107,
- 108,
- 109,
- 110,
- 111,
- 112,
- 113,
- 114,
- 115,
- 116,
- 117,
- 118,
- 119,
- 120,
- 121,
- 122,
- 48,
- 49,
- 50,
- 51,
- 52,
- 53,
- 54,
- 55,
- 56,
- 57,
- 65,
- 66
- ];
- }
-});
-
-// packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts
-function loadDummyServerCertsIfNeeded() {
- if (dummyServerTlsOptions)
- return;
- const { cert, key } = generateSelfSignedCertificate();
- dummyServerTlsOptions = { key, cert };
-}
-function normalizeOrigin(origin) {
- try {
- return new URL(origin).origin;
- } catch (error) {
- return origin;
- }
-}
-function convertClientCertificatesToTLSOptions(clientCertificates) {
- if (!clientCertificates || !clientCertificates.length)
- return;
- const tlsOptions = {
- pfx: [],
- key: [],
- cert: []
- };
- for (const cert of clientCertificates) {
- if (cert.cert)
- tlsOptions.cert.push(cert.cert);
- if (cert.key)
- tlsOptions.key.push({ pem: cert.key, passphrase: cert.passphrase });
- if (cert.pfx)
- tlsOptions.pfx.push({ buf: cert.pfx, passphrase: cert.passphrase });
- }
- return tlsOptions;
-}
-function getMatchingTLSOptionsForOrigin(clientCertificates, origin) {
- const matchingCerts = clientCertificates?.filter(
- (c) => normalizeOrigin(c.origin) === origin
- );
- return convertClientCertificatesToTLSOptions(matchingCerts);
-}
-function rewriteToLocalhostIfNeeded(host) {
- return host === "local.playwright" ? "localhost" : host;
-}
-function rewriteOpenSSLErrorIfNeeded(error) {
- if (error.message !== "unsupported" && error.code !== "ERR_CRYPTO_UNSUPPORTED_OPERATION")
- return error;
- return rewriteErrorMessage(error, [
- "Unsupported TLS certificate.",
- "Most likely, the security algorithm of the given certificate was deprecated by OpenSSL.",
- "For more details, see https://github.com/openssl/openssl/blob/master/README-PROVIDERS.md#the-legacy-provider",
- "You could probably modernize the certificate by following the steps at https://github.com/nodejs/node/issues/40672#issuecomment-1243648223"
- ].join("\n"));
-}
-function parseALPNFromClientHello(buffer) {
- if (buffer.length < 6)
- return null;
- if (buffer[0] !== 22)
- return null;
- let offset = 5;
- if (buffer[offset] !== 1)
- return null;
- offset += 4;
- offset += 2;
- offset += 32;
- if (offset >= buffer.length)
- return null;
- const sessionIdLength = buffer[offset];
- offset += 1 + sessionIdLength;
- if (offset + 2 > buffer.length)
- return null;
- const cipherSuitesLength = buffer.readUInt16BE(offset);
- offset += 2 + cipherSuitesLength;
- if (offset >= buffer.length)
- return null;
- const compressionMethodsLength = buffer[offset];
- offset += 1 + compressionMethodsLength;
- if (offset + 2 > buffer.length)
- return null;
- const extensionsLength = buffer.readUInt16BE(offset);
- offset += 2;
- const extensionsEnd = offset + extensionsLength;
- if (extensionsEnd > buffer.length)
- return null;
- while (offset + 4 <= extensionsEnd) {
- const extensionType = buffer.readUInt16BE(offset);
- offset += 2;
- const extensionLength = buffer.readUInt16BE(offset);
- offset += 2;
- if (offset + extensionLength > extensionsEnd)
- return null;
- if (extensionType === 16)
- return parseALPNExtension(buffer.subarray(offset, offset + extensionLength));
- offset += extensionLength;
- }
- return null;
-}
-function parseALPNExtension(buffer) {
- if (buffer.length < 2)
- return null;
- const listLength = buffer.readUInt16BE(0);
- if (listLength !== buffer.length - 2)
- return null;
- const protocols = [];
- let offset = 2;
- while (offset < buffer.length) {
- const protocolLength = buffer[offset];
- offset += 1;
- if (offset + protocolLength > buffer.length)
- break;
- const protocol = buffer.subarray(offset, offset + protocolLength).toString("utf8");
- protocols.push(protocol);
- offset += protocolLength;
- }
- return protocols.length > 0 ? protocols : null;
-}
-var import_events4, import_http23, import_net3, import_stream3, import_tls2, getProxyForUrl2, dummyServerTlsOptions, SocksProxyConnection, ClientCertificatesProxy;
-var init_socksClientCertificatesInterceptor = __esm({
- "packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts"() {
- "use strict";
- import_events4 = require("events");
- import_http23 = __toESM(require("http2"));
- import_net3 = __toESM(require("net"));
- import_stream3 = __toESM(require("stream"));
- import_tls2 = __toESM(require("tls"));
- init_socksProxy();
- init_debugLogger();
- init_happyEyeballs();
- init_stringUtils();
- init_crypto();
- init_stackTrace();
- init_network();
- init_browserContext();
- ({ getProxyForUrl: getProxyForUrl2 } = require("./utilsBundle"));
- dummyServerTlsOptions = void 0;
- SocksProxyConnection = class {
- constructor(socksProxy, uid, host, port) {
- this._firstPackageReceived = false;
- this._closed = false;
- this.socksProxy = socksProxy;
- this.uid = uid;
- this.host = host;
- this.port = port;
- this._serverCloseEventListener = () => {
- this._browserEncrypted.destroy();
- };
- this._browserEncrypted = new import_stream3.default.Duplex({
- read: () => {
- },
- write: (data, encoding, callback) => {
- this.socksProxy._socksProxy.sendSocketData({ uid: this.uid, data });
- callback();
- },
- destroy: (error, callback) => {
- if (error)
- socksProxy._socksProxy.sendSocketError({ uid: this.uid, error: error.message });
- else
- socksProxy._socksProxy.sendSocketEnd({ uid: this.uid });
- callback();
- }
- });
- }
- async connect() {
- const proxyAgent = this.socksProxy._getProxyAgent(this.host, this.port);
- if (proxyAgent)
- this._serverEncrypted = await proxyAgent.connect(new import_events4.EventEmitter(), { host: rewriteToLocalhostIfNeeded(this.host), port: this.port, secureEndpoint: false });
- else
- this._serverEncrypted = await createSocket(rewriteToLocalhostIfNeeded(this.host), this.port);
- this._serverEncrypted.once("close", this._serverCloseEventListener);
- this._serverEncrypted.once("error", (error) => this._browserEncrypted.destroy(error));
- if (this._closed) {
- this._serverEncrypted.destroy();
- return;
- }
- this.socksProxy._socksProxy.socketConnected({
- uid: this.uid,
- host: this._serverEncrypted.localAddress,
- port: this._serverEncrypted.localPort
- });
- }
- onClose() {
- this._serverEncrypted.destroy();
- this._browserEncrypted.destroy();
- this._closed = true;
- }
- onData(data) {
- if (!this._firstPackageReceived) {
- this._firstPackageReceived = true;
- const secureContext = data[0] === 22 ? this.socksProxy.secureContextMap.get(normalizeOrigin(`https://${this.host}:${this.port}`)) : void 0;
- if (secureContext)
- this._establishTlsTunnel(this._browserEncrypted, data, secureContext);
- else
- this._establishPlaintextTunnel(this._browserEncrypted);
- }
- this._browserEncrypted.push(data);
- }
- _establishPlaintextTunnel(browserEncrypted) {
- browserEncrypted.pipe(this._serverEncrypted);
- this._serverEncrypted.pipe(browserEncrypted);
- }
- _establishTlsTunnel(browserEncrypted, clientHello, secureContext) {
- const browserALPNProtocols = parseALPNFromClientHello(clientHello) || ["http/1.1"];
- debugLogger.log("client-certificates", `Browser->Proxy ${this.host}:${this.port} offers ALPN ${browserALPNProtocols}`);
- const rejectUnauthorized = !this.socksProxy.ignoreHTTPSErrors;
- const serverDecrypted = import_tls2.default.connect({
- socket: this._serverEncrypted,
- host: this.host,
- port: this.port,
- rejectUnauthorized,
- ALPNProtocols: browserALPNProtocols,
- servername: !import_net3.default.isIP(this.host) ? this.host : void 0,
- secureContext
- }, async () => {
- const browserDecrypted = await this._upgradeToTLSIfNeeded(browserEncrypted, serverDecrypted.alpnProtocol);
- debugLogger.log("client-certificates", `Proxy->Server ${this.host}:${this.port} chooses ALPN ${browserDecrypted.alpnProtocol}`);
- browserDecrypted.pipe(serverDecrypted);
- serverDecrypted.pipe(browserDecrypted);
- const cleanup = (error) => this._serverEncrypted.destroy(error);
- browserDecrypted.once("error", cleanup);
- serverDecrypted.once("error", cleanup);
- browserDecrypted.once("close", cleanup);
- serverDecrypted.once("close", cleanup);
- if (this._closed)
- serverDecrypted.destroy();
- });
- serverDecrypted.once("error", async (error) => {
- debugLogger.log("client-certificates", `error when connecting to server: ${error.message.replaceAll("\n", " ")}`);
- this._serverEncrypted.removeListener("close", this._serverCloseEventListener);
- this._serverEncrypted.destroy();
- const browserDecrypted = await this._upgradeToTLSIfNeeded(this._browserEncrypted, serverDecrypted.alpnProtocol);
- const responseBody = escapeHTML("Playwright client-certificate error: " + error.message).replaceAll("\n", " ");
- if (browserDecrypted.alpnProtocol === "h2") {
- if ("performServerHandshake" in import_http23.default) {
- const session2 = import_http23.default.performServerHandshake(browserDecrypted);
- session2.on("error", (error2) => {
- this._browserEncrypted.destroy(error2);
- });
- session2.once("stream", (stream3) => {
- const cleanup = (error2) => {
- session2.close();
- this._browserEncrypted.destroy(error2);
- };
- stream3.once("end", cleanup);
- stream3.once("error", cleanup);
- stream3.respond({
- [import_http23.default.constants.HTTP2_HEADER_CONTENT_TYPE]: "text/html",
- [import_http23.default.constants.HTTP2_HEADER_STATUS]: 503
- });
- stream3.end(responseBody);
- });
- } else {
- this._browserEncrypted.destroy(error);
- }
- } else {
- browserDecrypted.end([
- "HTTP/1.1 503 Internal Server Error",
- "Content-Type: text/html; charset=utf-8",
- "Content-Length: " + Buffer.byteLength(responseBody),
- "",
- responseBody
- ].join("\r\n"));
- }
- });
- }
- async _upgradeToTLSIfNeeded(socket, alpnProtocol) {
- this._brorwserDecrypted ??= new Promise((resolve, reject) => {
- const dummyServer = import_tls2.default.createServer({
- ...dummyServerTlsOptions,
- ALPNProtocols: [alpnProtocol || "http/1.1"]
- });
- dummyServer.emit("connection", socket);
- dummyServer.once("secureConnection", (tlsSocket) => {
- dummyServer.close();
- resolve(tlsSocket);
- });
- dummyServer.once("error", (error) => {
- dummyServer.close();
- reject(error);
- });
- });
- return this._brorwserDecrypted;
- }
- };
- ClientCertificatesProxy = class _ClientCertificatesProxy {
- constructor(contextOptions) {
- this._connections = /* @__PURE__ */ new Map();
- this.secureContextMap = /* @__PURE__ */ new Map();
- verifyClientCertificates(contextOptions.clientCertificates);
- this.ignoreHTTPSErrors = contextOptions.ignoreHTTPSErrors;
- this._proxy = contextOptions.proxy;
- this._initSecureContexts(contextOptions.clientCertificates);
- this._socksProxy = new SocksProxy();
- this._socksProxy.setPattern("*");
- this._socksProxy.addListener(SocksProxy.Events.SocksRequested, async (payload) => {
- try {
- const connection = new SocksProxyConnection(this, payload.uid, payload.host, payload.port);
- await connection.connect();
- this._connections.set(payload.uid, connection);
- } catch (error) {
- debugLogger.log("client-certificates", `Failed to connect to ${payload.host}:${payload.port}: ${error.message}`);
- this._socksProxy.socketFailed({ uid: payload.uid, errorCode: error.code });
- }
- });
- this._socksProxy.addListener(SocksProxy.Events.SocksData, (payload) => {
- this._connections.get(payload.uid)?.onData(payload.data);
- });
- this._socksProxy.addListener(SocksProxy.Events.SocksClosed, (payload) => {
- this._connections.get(payload.uid)?.onClose();
- this._connections.delete(payload.uid);
- });
- loadDummyServerCertsIfNeeded();
- }
- _getProxyAgent(host, port) {
- const proxyFromOptions = createProxyAgent(this._proxy);
- if (proxyFromOptions)
- return proxyFromOptions;
- const proxyFromEnv = getProxyForUrl2(`https://${host}:${port}`);
- if (proxyFromEnv)
- return createProxyAgent({ server: proxyFromEnv });
- }
- _initSecureContexts(clientCertificates) {
- const origin2certs = /* @__PURE__ */ new Map();
- for (const cert of clientCertificates || []) {
- const origin = normalizeOrigin(cert.origin);
- const certs = origin2certs.get(origin) || [];
- certs.push(cert);
- origin2certs.set(origin, certs);
- }
- for (const [origin, certs] of origin2certs) {
- try {
- this.secureContextMap.set(origin, import_tls2.default.createSecureContext(convertClientCertificatesToTLSOptions(certs)));
- } catch (error) {
- error = rewriteOpenSSLErrorIfNeeded(error);
- throw rewriteErrorMessage(error, `Failed to load client certificate: ${error.message}`);
- }
- }
- }
- static async create(progress2, contextOptions) {
- const proxy = new _ClientCertificatesProxy(contextOptions);
- try {
- await progress2.race(proxy._socksProxy.listen(0, "127.0.0.1"));
- return proxy;
- } catch (error) {
- await progress2.race(proxy.close());
- throw error;
- }
- }
- proxySettings() {
- return { server: `socks5://127.0.0.1:${this._socksProxy.port()}` };
- }
- async close() {
- await this._socksProxy.close();
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts
-function frameSnapshotStreamer(snapshotStreamer, removeNoScript) {
- if (window[snapshotStreamer])
- return;
- const kShadowAttribute = "__playwright_shadow_root_";
- const kValueAttribute = "__playwright_value_";
- const kCheckedAttribute = "__playwright_checked_";
- const kSelectedAttribute = "__playwright_selected_";
- const kScrollTopAttribute = "__playwright_scroll_top_";
- const kScrollLeftAttribute = "__playwright_scroll_left_";
- const kStyleSheetAttribute = "__playwright_style_sheet_";
- const kTargetAttribute = "__playwright_target__";
- const kCustomElementsAttribute = "__playwright_custom_elements__";
- const kCurrentSrcAttribute = "__playwright_current_src__";
- const kBoundingRectAttribute = "__playwright_bounding_rect__";
- const kPopoverOpenAttribute = "__playwright_popover_open_";
- const kDialogOpenAttribute = "__playwright_dialog_open_";
- const kSnapshotFrameId = Symbol("__playwright_snapshot_frameid_");
- const kCachedData = Symbol("__playwright_snapshot_cache_");
- const kEndOfList = Symbol("__playwright_end_of_list_");
- function resetCachedData(obj) {
- delete obj[kCachedData];
- }
- function ensureCachedData(obj) {
- if (!obj[kCachedData])
- obj[kCachedData] = {};
- return obj[kCachedData];
- }
- const kObserverConfig = { attributes: true, subtree: true };
- function removeHash2(url2) {
- try {
- const u = new URL(url2);
- u.hash = "";
- return u.toString();
- } catch (e) {
- return url2;
- }
- }
- class Streamer {
- constructor() {
- this._lastSnapshotNumber = 0;
- this._staleStyleSheets = /* @__PURE__ */ new Set();
- this._modifiedStyleSheets = /* @__PURE__ */ new Set();
- this._readingStyleSheet = false;
- this._targetGeneration = 0;
- const invalidateCSSGroupingRule = (rule) => {
- if (rule.parentStyleSheet)
- this._invalidateStyleSheet(rule.parentStyleSheet);
- };
- this._interceptNativeMethod(window.CSSStyleSheet.prototype, "insertRule", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeMethod(window.CSSStyleSheet.prototype, "deleteRule", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeMethod(window.CSSStyleSheet.prototype, "addRule", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeMethod(window.CSSStyleSheet.prototype, "removeRule", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeGetter(window.CSSStyleSheet.prototype, "rules", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeGetter(window.CSSStyleSheet.prototype, "cssRules", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeMethod(window.CSSStyleSheet.prototype, "replaceSync", (sheet) => this._invalidateStyleSheet(sheet));
- this._interceptNativeMethod(window.CSSGroupingRule.prototype, "insertRule", invalidateCSSGroupingRule);
- this._interceptNativeMethod(window.CSSGroupingRule.prototype, "deleteRule", invalidateCSSGroupingRule);
- this._interceptNativeGetter(window.CSSGroupingRule.prototype, "cssRules", invalidateCSSGroupingRule);
- this._interceptNativeSetter(window.StyleSheet.prototype, "disabled", (sheet) => {
- if (sheet instanceof CSSStyleSheet)
- this._invalidateStyleSheet(sheet);
- });
- this._interceptNativeAsyncMethod(window.CSSStyleSheet.prototype, "replace", (sheet) => this._invalidateStyleSheet(sheet));
- this._fakeBase = document.createElement("base");
- this._observer = new MutationObserver((list) => this._handleMutations(list));
- this._ensureObservingCurrentDocument();
- }
- _refreshListenersWhenNeeded() {
- this._refreshListeners();
- const customEventName = "__playwright_snapshotter_global_listeners_check__";
- let seenEvent = false;
- const handleCustomEvent = () => seenEvent = true;
- window.addEventListener(customEventName, handleCustomEvent);
- const observer = new MutationObserver((entries) => {
- const newDocumentElement = entries.some((entry) => Array.from(entry.addedNodes).includes(document.documentElement));
- if (newDocumentElement) {
- seenEvent = false;
- window.dispatchEvent(new CustomEvent(customEventName));
- if (!seenEvent) {
- window.addEventListener(customEventName, handleCustomEvent);
- this._refreshListeners();
- }
- }
- });
- observer.observe(document, { childList: true });
- }
- _refreshListeners() {
- document.addEventListener("__playwright_mark_target__", (event) => {
- const target = event.composedPath()[0];
- if (target?.nodeType !== Node.ELEMENT_NODE)
- return;
- target.__playwright_target__ = this._targetGeneration;
- });
- document.addEventListener("__playwright_reset_targets__", () => {
- ++this._targetGeneration;
- });
- }
- _interceptNativeMethod(obj, method, cb) {
- const native = obj[method];
- if (!native)
- return;
- obj[method] = function(...args) {
- const result2 = native.call(this, ...args);
- cb(this, result2);
- return result2;
- };
- }
- _interceptNativeAsyncMethod(obj, method, cb) {
- const native = obj[method];
- if (!native)
- return;
- obj[method] = async function(...args) {
- const result2 = await native.call(this, ...args);
- cb(this, result2);
- return result2;
- };
- }
- _interceptNativeGetter(obj, prop, cb) {
- const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- Object.defineProperty(obj, prop, {
- ...descriptor,
- get: function() {
- const result2 = descriptor.get.call(this);
- cb(this, result2);
- return result2;
- }
- });
- }
- _interceptNativeSetter(obj, prop, cb) {
- const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- Object.defineProperty(obj, prop, {
- ...descriptor,
- set: function(value2) {
- const result2 = descriptor.set.call(this, value2);
- cb(this, value2);
- return result2;
- }
- });
- }
- _handleMutations(list) {
- for (const mutation of list)
- ensureCachedData(mutation.target).attributesCached = void 0;
- }
- _ensureObservingCurrentDocument() {
- if (this._observedDocument === document)
- return;
- this._observedDocument = document;
- this._observer.disconnect();
- this._observer.observe(document, kObserverConfig);
- this._refreshListenersWhenNeeded();
- }
- _invalidateStyleSheet(sheet) {
- if (this._readingStyleSheet)
- return;
- this._staleStyleSheets.add(sheet);
- if (sheet.href !== null)
- this._modifiedStyleSheets.add(sheet);
- }
- _updateStyleElementStyleSheetTextIfNeeded(sheet, forceText) {
- const data = ensureCachedData(sheet);
- if (this._staleStyleSheets.has(sheet) || forceText && data.cssText === void 0) {
- this._staleStyleSheets.delete(sheet);
- try {
- data.cssText = this._getSheetText(sheet);
- } catch (e) {
- data.cssText = "";
- }
- }
- return data.cssText;
- }
- // Returns either content, ref, or no override.
- _updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber) {
- const data = ensureCachedData(sheet);
- if (this._staleStyleSheets.has(sheet)) {
- this._staleStyleSheets.delete(sheet);
- try {
- data.cssText = this._getSheetText(sheet);
- data.cssRef = snapshotNumber;
- return data.cssText;
- } catch (e) {
- }
- }
- return data.cssRef === void 0 ? void 0 : snapshotNumber - data.cssRef;
- }
- markIframe(iframeElement, frameId) {
- iframeElement[kSnapshotFrameId] = frameId;
- }
- resetHistory() {
- this._staleStyleSheets.clear();
- const visitNode = (node) => {
- resetCachedData(node);
- if (node.nodeType === Node.ELEMENT_NODE) {
- const element2 = node;
- if (element2.shadowRoot)
- visitNode(element2.shadowRoot);
- }
- for (let child = node.firstChild; child; child = child.nextSibling)
- visitNode(child);
- };
- visitNode(document.documentElement);
- visitNode(this._fakeBase);
- }
- __sanitizeMetaAttribute(name, value2, httpEquiv) {
- if (name === "charset")
- return "utf-8";
- if (httpEquiv.toLowerCase() !== "content-type" || name !== "content")
- return value2;
- const [type3, ...params2] = value2.split(";");
- if (type3 !== "text/html" || params2.length <= 0)
- return value2;
- const charsetParamIdx = params2.findIndex((param) => param.trim().startsWith("charset="));
- if (charsetParamIdx > -1)
- params2[charsetParamIdx] = "charset=utf-8";
- return `${type3}; ${params2.join("; ")}`;
- }
- _sanitizeUrl(url2) {
- if (url2.startsWith("javascript:") || url2.startsWith("vbscript:"))
- return "";
- return url2;
- }
- _sanitizeSrcSet(srcset) {
- return srcset.split(",").map((src) => {
- src = src.trim();
- const spaceIndex = src.lastIndexOf(" ");
- if (spaceIndex === -1)
- return this._sanitizeUrl(src);
- return this._sanitizeUrl(src.substring(0, spaceIndex).trim()) + src.substring(spaceIndex);
- }).join(", ");
- }
- _resolveUrl(base, url2) {
- if (url2 === "")
- return "";
- try {
- return new URL(url2, base).href;
- } catch (e) {
- return url2;
- }
- }
- _getSheetBase(sheet) {
- let rootSheet = sheet;
- while (rootSheet.parentStyleSheet)
- rootSheet = rootSheet.parentStyleSheet;
- if (rootSheet.ownerNode)
- return rootSheet.ownerNode.baseURI;
- return document.baseURI;
- }
- _getSheetText(sheet) {
- this._readingStyleSheet = true;
- try {
- if (sheet.disabled)
- return "";
- const rules = [];
- for (const rule of sheet.cssRules)
- rules.push(rule.cssText);
- return rules.join("\n");
- } finally {
- this._readingStyleSheet = false;
- }
- }
- captureSnapshot(reset) {
- const timestamp = performance.now();
- const snapshotNumber = ++this._lastSnapshotNumber;
- if (reset === "history")
- this.resetHistory();
- if (reset)
- ++this._targetGeneration;
- let nodeCounter = 0;
- let shadowDomNesting = 0;
- let headNesting = 0;
- this._ensureObservingCurrentDocument();
- this._handleMutations(this._observer.takeRecords());
- const definedCustomElements = /* @__PURE__ */ new Set();
- const visitNode = (node) => {
- const nodeType = node.nodeType;
- const nodeName = nodeType === Node.DOCUMENT_FRAGMENT_NODE ? "template" : node.nodeName;
- if (nodeType !== Node.ELEMENT_NODE && nodeType !== Node.DOCUMENT_FRAGMENT_NODE && nodeType !== Node.TEXT_NODE)
- return;
- if (nodeName === "SCRIPT")
- return;
- if (nodeName === "LINK" && nodeType === Node.ELEMENT_NODE) {
- const rel = node.getAttribute("rel")?.toLowerCase();
- if (rel === "preload" || rel === "prefetch")
- return;
- }
- if (removeNoScript && nodeName === "NOSCRIPT")
- return;
- if (nodeName === "META") {
- const httpEquiv = node.httpEquiv.toLowerCase();
- if (httpEquiv === "content-security-policy" || httpEquiv === "refresh" || httpEquiv === "set-cookie")
- return;
- }
- if ((nodeName === "IFRAME" || nodeName === "FRAME") && headNesting)
- return;
- const data = ensureCachedData(node);
- const values = [];
- let equals = !!data.cached;
- let extraNodes = 0;
- const expectValue = (value2) => {
- equals = equals && data.cached[values.length] === value2;
- values.push(value2);
- };
- const checkAndReturn = (n) => {
- data.attributesCached = true;
- if (equals)
- return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] };
- nodeCounter += extraNodes;
- data.ref = [snapshotNumber, nodeCounter++];
- data.cached = values;
- return { equals: false, n };
- };
- if (nodeType === Node.TEXT_NODE) {
- const value2 = node.nodeValue || "";
- expectValue(value2);
- return checkAndReturn(value2);
- }
- if (nodeName === "STYLE") {
- const sheet = node.sheet;
- let cssText;
- if (sheet)
- cssText = this._updateStyleElementStyleSheetTextIfNeeded(sheet);
- cssText = cssText || node.textContent || "";
- expectValue(cssText);
- extraNodes++;
- return checkAndReturn([nodeName, {}, cssText]);
- }
- const attrs = {};
- const result3 = [nodeName, attrs];
- const visitChild = (child) => {
- const snapshot3 = visitNode(child);
- if (snapshot3) {
- result3.push(snapshot3.n);
- expectValue(child);
- equals = equals && snapshot3.equals;
- }
- };
- const visitChildStyleSheet = (child) => {
- const snapshot3 = visitStyleSheet(child);
- if (snapshot3) {
- result3.push(snapshot3.n);
- expectValue(child);
- equals = equals && snapshot3.equals;
- }
- };
- if (nodeType === Node.DOCUMENT_FRAGMENT_NODE)
- attrs[kShadowAttribute] = "open";
- if (nodeType === Node.ELEMENT_NODE) {
- const element2 = node;
- if (element2.localName.includes("-") && window.customElements?.get(element2.localName))
- definedCustomElements.add(element2.localName);
- if (nodeName === "INPUT" || nodeName === "TEXTAREA") {
- const value2 = element2.value;
- expectValue(kValueAttribute);
- expectValue(value2);
- attrs[kValueAttribute] = value2;
- }
- if (nodeName === "INPUT" && ["checkbox", "radio"].includes(element2.type)) {
- const value2 = element2.checked ? "true" : "false";
- expectValue(kCheckedAttribute);
- expectValue(value2);
- attrs[kCheckedAttribute] = value2;
- }
- if (nodeName === "OPTION") {
- const value2 = element2.selected ? "true" : "false";
- expectValue(kSelectedAttribute);
- expectValue(value2);
- attrs[kSelectedAttribute] = value2;
- }
- if (nodeName === "CANVAS" || nodeName === "IFRAME" || nodeName === "FRAME") {
- const boundingRect = element2.getBoundingClientRect();
- const value2 = JSON.stringify({
- left: boundingRect.left,
- top: boundingRect.top,
- right: boundingRect.right,
- bottom: boundingRect.bottom
- });
- expectValue(kBoundingRectAttribute);
- expectValue(value2);
- attrs[kBoundingRectAttribute] = value2;
- }
- if (element2.popover && element2.matches && element2.matches(":popover-open")) {
- const value2 = "true";
- expectValue(kPopoverOpenAttribute);
- expectValue(value2);
- attrs[kPopoverOpenAttribute] = value2;
- }
- if (nodeName === "DIALOG" && element2.open) {
- const value2 = element2.matches(":modal") ? "modal" : "true";
- expectValue(kDialogOpenAttribute);
- expectValue(value2);
- attrs[kDialogOpenAttribute] = value2;
- }
- if (element2.scrollTop) {
- expectValue(kScrollTopAttribute);
- expectValue(element2.scrollTop);
- attrs[kScrollTopAttribute] = "" + element2.scrollTop;
- }
- if (element2.scrollLeft) {
- expectValue(kScrollLeftAttribute);
- expectValue(element2.scrollLeft);
- attrs[kScrollLeftAttribute] = "" + element2.scrollLeft;
- }
- if (element2.shadowRoot) {
- ++shadowDomNesting;
- visitChild(element2.shadowRoot);
- --shadowDomNesting;
- }
- if (element2.__playwright_target__ === this._targetGeneration) {
- expectValue(kTargetAttribute);
- attrs[kTargetAttribute] = "";
- }
- }
- if (nodeName === "HEAD") {
- ++headNesting;
- this._fakeBase.setAttribute("href", document.baseURI);
- visitChild(this._fakeBase);
- }
- for (let child = node.firstChild; child; child = child.nextSibling)
- visitChild(child);
- if (nodeName === "HEAD")
- --headNesting;
- expectValue(kEndOfList);
- let documentOrShadowRoot = null;
- if (node.ownerDocument.documentElement === node)
- documentOrShadowRoot = node.ownerDocument;
- else if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE)
- documentOrShadowRoot = node;
- if (documentOrShadowRoot) {
- for (const sheet of documentOrShadowRoot.adoptedStyleSheets || [])
- visitChildStyleSheet(sheet);
- expectValue(kEndOfList);
- }
- if (nodeName === "IFRAME" || nodeName === "FRAME") {
- const element2 = node;
- const frameId = element2[kSnapshotFrameId];
- const name = "src";
- const value2 = frameId ? `/snapshot/${frameId}` : "";
- expectValue(name);
- expectValue(value2);
- attrs[name] = value2;
- }
- if (nodeName === "BODY" && definedCustomElements.size) {
- const value2 = [...definedCustomElements].join(",");
- expectValue(kCustomElementsAttribute);
- expectValue(value2);
- attrs[kCustomElementsAttribute] = value2;
- }
- if (nodeName === "IMG" || nodeName === "PICTURE") {
- const value2 = nodeName === "PICTURE" ? "" : this._sanitizeUrl(node.currentSrc);
- expectValue(kCurrentSrcAttribute);
- expectValue(value2);
- attrs[kCurrentSrcAttribute] = value2;
- }
- if (equals && data.attributesCached && !shadowDomNesting)
- return checkAndReturn(result3);
- if (nodeType === Node.ELEMENT_NODE) {
- const element2 = node;
- for (let i = 0; i < element2.attributes.length; i++) {
- const name = element2.attributes[i].name;
- if (nodeName === "LINK" && name === "integrity")
- continue;
- if (nodeName === "IFRAME" && (name === "src" || name === "srcdoc" || name === "sandbox"))
- continue;
- if (nodeName === "FRAME" && name === "src")
- continue;
- if (nodeName === "DIALOG" && name === "open")
- continue;
- let value2 = element2.attributes[i].value;
- if (nodeName === "META")
- value2 = this.__sanitizeMetaAttribute(name, value2, node.httpEquiv);
- else if (name === "src" && nodeName === "IMG")
- value2 = this._sanitizeUrl(value2);
- else if (name === "srcset" && nodeName === "IMG")
- value2 = this._sanitizeSrcSet(value2);
- else if (name === "srcset" && nodeName === "SOURCE")
- value2 = this._sanitizeSrcSet(value2);
- else if (name === "href" && nodeName === "LINK")
- value2 = this._sanitizeUrl(value2);
- else if (name.startsWith("on"))
- value2 = "";
- expectValue(name);
- expectValue(value2);
- attrs[name] = value2;
- }
- expectValue(kEndOfList);
- }
- if (result3.length === 2 && !Object.keys(attrs).length)
- result3.pop();
- return checkAndReturn(result3);
- };
- const visitStyleSheet = (sheet) => {
- const data = ensureCachedData(sheet);
- const oldCSSText = data.cssText;
- const cssText = this._updateStyleElementStyleSheetTextIfNeeded(
- sheet,
- true
- /* forceText */
- );
- if (cssText === oldCSSText)
- return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] };
- data.ref = [snapshotNumber, nodeCounter++];
- return {
- equals: false,
- n: ["template", {
- [kStyleSheetAttribute]: cssText
- }]
- };
- };
- let html;
- if (document.documentElement) {
- const { n } = visitNode(document.documentElement);
- html = n;
- } else {
- html = ["html"];
- }
- const result2 = {
- html,
- doctype: document.doctype ? document.doctype.name : void 0,
- resourceOverrides: [],
- viewport: {
- width: window.innerWidth,
- height: window.innerHeight
- },
- url: location.href,
- wallTime: Date.now(),
- collectionTime: 0
- };
- for (const sheet of this._modifiedStyleSheets) {
- if (sheet.href === null)
- continue;
- const content = this._updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber);
- if (content === void 0) {
- continue;
- }
- const base = this._getSheetBase(sheet);
- const url2 = removeHash2(this._resolveUrl(base, sheet.href));
- result2.resourceOverrides.push({ url: url2, content, contentType: "text/css" });
- }
- result2.collectionTime = performance.now() - timestamp;
- return result2;
- }
- }
- window[snapshotStreamer] = new Streamer();
-}
-var init_snapshotterInjected = __esm({
- "packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts"() {
- "use strict";
- }
-});
-
-// packages/playwright-core/src/server/trace/recorder/snapshotter.ts
-var mime3, Snapshotter, kNeedsResetSymbol;
-var init_snapshotter = __esm({
- "packages/playwright-core/src/server/trace/recorder/snapshotter.ts"() {
- "use strict";
- init_time();
- init_crypto();
- init_debugLogger();
- init_eventsHelper();
- init_snapshotterInjected();
- init_browserContext();
- init_progress();
- mime3 = require("./utilsBundle").mime;
- Snapshotter = class {
- constructor(context2, delegate) {
- this._eventListeners = [];
- this._started = false;
- this._context = context2;
- this._delegate = delegate;
- const guid = createGuid();
- this._snapshotStreamer = "__playwright_snapshot_streamer_" + guid;
- }
- started() {
- return this._started;
- }
- async start(progress2) {
- this._started = true;
- if (!this._initScript)
- await this._initialize(progress2);
- await progress2.race(this.reset());
- }
- async reset() {
- if (this._started)
- await this._context.safeNonStallingEvaluateInAllFrames(`window["${this._snapshotStreamer}"].resetHistory()`, "main");
- }
- stop() {
- this._started = false;
- }
- async resetForReuse() {
- if (this._initScript) {
- eventsHelper.removeEventListeners(this._eventListeners);
- await this._initScript.dispose();
- this._initScript = void 0;
- }
- }
- async _initialize(progress2) {
- for (const page of this._context.pages())
- this._onPage(page);
- this._eventListeners = [
- eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, this._onPage.bind(this)),
- eventsHelper.addEventListener(this._context, BrowserContext.Events.FrameAttached, (frame) => this._annotateFrameHierarchy(frame))
- ];
- const { javaScriptEnabled } = this._context._options;
- const initScriptSource = `(${frameSnapshotStreamer})("${this._snapshotStreamer}", ${javaScriptEnabled || javaScriptEnabled === void 0})`;
- this._initScript = await this._context.addInitScript(progress2, initScriptSource);
- await progress2.race(this._context.safeNonStallingEvaluateInAllFrames(initScriptSource, "main"));
- }
- dispose() {
- eventsHelper.removeEventListeners(this._eventListeners);
- }
- async _captureFrameSnapshot(frame, resetTargets) {
- const needsHistoryReset = !!frame[kNeedsResetSymbol];
- frame[kNeedsResetSymbol] = false;
- const reset = needsHistoryReset ? "history" : resetTargets ? "targets" : void 0;
- const expression2 = `window["${this._snapshotStreamer}"].captureSnapshot(${JSON.stringify(reset)})`;
- try {
- return await frame.nonStallingRawEvaluateInExistingMainContext(expression2);
- } catch (e) {
- frame[kNeedsResetSymbol] = true;
- debugLogger.log("error", e);
- }
- }
- async captureSnapshot(page, callId, snapshotName, resetTargets) {
- const snapshots = page.frames().map(async (frame) => {
- const data = await this._captureFrameSnapshot(frame, resetTargets);
- if (!data || !this._started)
- return;
- const snapshot3 = {
- callId,
- snapshotName,
- pageId: page.guid,
- frameId: frame.guid,
- frameUrl: data.url,
- doctype: data.doctype,
- html: data.html,
- viewport: data.viewport,
- timestamp: monotonicTime(),
- wallTime: data.wallTime,
- collectionTime: data.collectionTime,
- resourceOverrides: [],
- isMainFrame: page.mainFrame() === frame
- };
- for (const { url: url2, content, contentType } of data.resourceOverrides) {
- if (typeof content === "string") {
- const buffer = Buffer.from(content);
- const sha1 = calculateSha1(buffer) + "." + (mime3.getExtension(contentType) || "dat");
- this._delegate.onSnapshotterBlob({ sha1, buffer });
- snapshot3.resourceOverrides.push({ url: url2, sha1 });
- } else {
- snapshot3.resourceOverrides.push({ url: url2, ref: content });
- }
- }
- this._delegate.onFrameSnapshot(snapshot3);
- });
- await Promise.all(snapshots);
- }
- _onPage(page) {
- for (const frame of page.frames())
- this._annotateFrameHierarchy(frame);
- }
- _annotateFrameHierarchy(frame) {
- (async () => {
- const frameElement = await frame.frameElement(nullProgress);
- const parent = frame.parentFrame();
- if (!parent)
- return;
- const context2 = await parent.mainContext();
- await context2?.evaluate(({ snapshotStreamer, frameElement: frameElement2, frameId }) => {
- window[snapshotStreamer].markIframe(frameElement2, frameId);
- }, { snapshotStreamer: this._snapshotStreamer, frameElement, frameId: frame.guid });
- frameElement.dispose();
- })().catch(() => {
- });
- }
- };
- kNeedsResetSymbol = Symbol("kNeedsReset");
- }
-});
-
-// packages/playwright-core/src/server/artifact.ts
-var import_fs12, Artifact;
-var init_artifact = __esm({
- "packages/playwright-core/src/server/artifact.ts"() {
- "use strict";
- import_fs12 = __toESM(require("fs"));
- init_manualPromise();
- init_assert();
- init_errors();
- init_instrumentation();
- Artifact = class extends SdkObject {
- constructor(parent, localPath, unaccessibleErrorMessage, cancelCallback) {
- super(parent, "artifact");
- this._finishedPromise = new ManualPromise();
- this._saveCallbacks = [];
- this._finished = false;
- this._deleted = false;
- this._localPath = localPath;
- this._unaccessibleErrorMessage = unaccessibleErrorMessage;
- this._cancelCallback = cancelCallback;
- }
- async localPathAfterFinished(progress2) {
- return await progress2.race(this._localPathAfterFinished());
- }
- async failureError(progress2) {
- return await progress2.race(this._failureError());
- }
- async cancel(progress2) {
- return await progress2.race(this._cancel());
- }
- async delete(progress2) {
- return await progress2.race(this._delete());
- }
- localPath() {
- return this._localPath;
- }
- async _localPathAfterFinished() {
- if (this._unaccessibleErrorMessage)
- throw new Error(this._unaccessibleErrorMessage);
- await this._finishedPromise;
- if (this._failureErrorValue)
- throw this._failureErrorValue;
- return this._localPath;
- }
- saveAs(progress2, saveCallback) {
- if (this._unaccessibleErrorMessage)
- throw new Error(this._unaccessibleErrorMessage);
- if (this._deleted)
- throw new Error(`File already deleted. Save before deleting.`);
- if (this._failureErrorValue)
- throw this._failureErrorValue;
- if (this._finished) {
- saveCallback(this._localPath).catch(() => {
- });
- return;
- }
- this._saveCallbacks.push(saveCallback);
- }
- async _failureError() {
- if (this._unaccessibleErrorMessage)
- return this._unaccessibleErrorMessage;
- await this._finishedPromise;
- return this._failureErrorValue?.message || null;
- }
- async _cancel() {
- assert(this._cancelCallback !== void 0);
- return this._cancelCallback();
- }
- async _delete() {
- if (this._unaccessibleErrorMessage)
- return;
- const fileName = await this._localPathAfterFinished();
- if (this._deleted)
- return;
- this._deleted = true;
- if (fileName)
- await import_fs12.default.promises.unlink(fileName).catch((e) => {
- });
- }
- async deleteOnContextClose() {
- if (this._deleted)
- return;
- this._deleted = true;
- if (!this._unaccessibleErrorMessage)
- await import_fs12.default.promises.unlink(this._localPath).catch((e) => {
- });
- await this.reportFinished(new TargetClosedError(this.closeReason()));
- }
- async reportFinished(error) {
- if (this._finished)
- return;
- this._finished = true;
- this._failureErrorValue = error;
- if (error) {
- for (const callback of this._saveCallbacks)
- await callback("", error);
- } else {
- for (const callback of this._saveCallbacks)
- await callback(this._localPath);
- }
- this._saveCallbacks = [];
- this._finishedPromise.resolve();
- }
- };
- }
-});
-
-// packages/playwright-core/src/protocol/validatorPrimitives.ts
-function findValidator(type3, method, kind) {
- const validator = maybeFindValidator(type3, method, kind);
- if (!validator)
- throw new ValidationError(`Unknown scheme for ${kind}: ${type3}.${method}`);
- return validator;
-}
-function maybeFindValidator(type3, method, kind) {
- const schemeName = type3 + (kind === "Initializer" ? "" : method[0].toUpperCase() + method.substring(1)) + kind;
- return scheme[schemeName];
-}
-function createMetadataValidator() {
- return tOptional(scheme["Metadata"]);
-}
-function createWaitInfoValidator() {
- return scheme["WaitInfo"];
-}
-var ValidationError, scheme, tFloat, tInt, tBoolean, tString, tBinary, tAny, tOptional, tArray, tObject, tEnum, tChannel, tType;
-var init_validatorPrimitives = __esm({
- "packages/playwright-core/src/protocol/validatorPrimitives.ts"() {
- "use strict";
- ValidationError = class extends Error {
- };
- scheme = {};
- tFloat = (arg, path59, context2) => {
- if (arg instanceof Number)
- return arg.valueOf();
- if (typeof arg === "number")
- return arg;
- throw new ValidationError(`${path59}: expected float, got ${typeof arg}`);
- };
- tInt = (arg, path59, context2) => {
- let value2;
- if (arg instanceof Number)
- value2 = arg.valueOf();
- else if (typeof arg === "number")
- value2 = arg;
- else
- throw new ValidationError(`${path59}: expected integer, got ${typeof arg}`);
- if (!Number.isInteger(value2))
- throw new ValidationError(`${path59}: expected integer, got float ${value2}`);
- return value2;
- };
- tBoolean = (arg, path59, context2) => {
- if (arg instanceof Boolean)
- return arg.valueOf();
- if (typeof arg === "boolean")
- return arg;
- throw new ValidationError(`${path59}: expected boolean, got ${typeof arg}`);
- };
- tString = (arg, path59, context2) => {
- if (arg instanceof String)
- return arg.valueOf();
- if (typeof arg === "string")
- return arg;
- throw new ValidationError(`${path59}: expected string, got ${typeof arg}`);
- };
- tBinary = (arg, path59, context2) => {
- if (context2.binary === "fromBase64") {
- if (arg instanceof String)
- return Buffer.from(arg.valueOf(), "base64");
- if (typeof arg === "string")
- return Buffer.from(arg, "base64");
- throw new ValidationError(`${path59}: expected base64-encoded buffer, got ${typeof arg}`);
- }
- if (context2.binary === "toBase64") {
- if (!(arg instanceof Buffer))
- throw new ValidationError(`${path59}: expected Buffer, got ${typeof arg}`);
- return arg.toString("base64");
- }
- if (context2.binary === "buffer") {
- if (!(arg instanceof Buffer) && !(arg instanceof Object))
- throw new ValidationError(`${path59}: expected Buffer, got ${typeof arg}`);
- return arg;
- }
- throw new ValidationError(`Unsupported binary behavior "${context2.binary}"`);
- };
- tAny = (arg, path59, context2) => {
- return arg;
- };
- tOptional = (v) => {
- return (arg, path59, context2) => {
- if (Object.is(arg, void 0))
- return arg;
- return v(arg, path59, context2);
- };
- };
- tArray = (v) => {
- return (arg, path59, context2) => {
- if (!Array.isArray(arg))
- throw new ValidationError(`${path59}: expected array, got ${typeof arg}`);
- return arg.map((x, index) => v(x, path59 + "[" + index + "]", context2));
- };
- };
- tObject = (s) => {
- return (arg, path59, context2) => {
- if (Object.is(arg, null))
- throw new ValidationError(`${path59}: expected object, got null`);
- if (typeof arg !== "object")
- throw new ValidationError(`${path59}: expected object, got ${typeof arg}`);
- const result2 = {};
- for (const [key, v] of Object.entries(s)) {
- const value2 = v(arg[key], path59 ? path59 + "." + key : key, context2);
- if (!Object.is(value2, void 0))
- result2[key] = value2;
- }
- if (context2.isUnderTest()) {
- for (const [key, value2] of Object.entries(arg)) {
- if (key.startsWith("__testHook"))
- result2[key] = value2;
- }
- }
- return result2;
- };
- };
- tEnum = (e) => {
- return (arg, path59, context2) => {
- if (!e.includes(arg))
- throw new ValidationError(`${path59}: expected one of (${e.join("|")})`);
- return arg;
- };
- };
- tChannel = (names) => {
- return (arg, path59, context2) => {
- return context2.tChannelImpl(names, arg, path59, context2);
- };
- };
- tType = (name) => {
- return (arg, path59, context2) => {
- const v = scheme[name];
- if (!v)
- throw new ValidationError(path59 + ': unknown type "' + name + '"');
- return v(arg, path59, context2);
- };
- };
- }
-});
-
-// packages/playwright-core/src/protocol/validator.ts
-var init_validator = __esm({
- "packages/playwright-core/src/protocol/validator.ts"() {
- "use strict";
- init_validatorPrimitives();
- init_validatorPrimitives();
- scheme.AndroidInitializer = tOptional(tObject({}));
- scheme.AndroidDevicesParams = tObject({
- host: tOptional(tString),
- port: tOptional(tInt),
- omitDriverInstall: tOptional(tBoolean)
- });
- scheme.AndroidDevicesResult = tObject({
- devices: tArray(tChannel(["AndroidDevice"]))
- });
- scheme.AndroidSocketInitializer = tOptional(tObject({}));
- scheme.AndroidSocketDataEvent = tObject({
- data: tBinary
- });
- scheme.AndroidSocketCloseEvent = tOptional(tObject({}));
- scheme.AndroidSocketWriteParams = tObject({
- data: tBinary
- });
- scheme.AndroidSocketWriteResult = tOptional(tObject({}));
- scheme.AndroidSocketCloseParams = tOptional(tObject({}));
- scheme.AndroidSocketCloseResult = tOptional(tObject({}));
- scheme.AndroidDeviceInitializer = tObject({
- model: tString,
- serial: tString
- });
- scheme.AndroidDeviceCloseEvent = tOptional(tObject({}));
- scheme.AndroidDeviceWebViewAddedEvent = tObject({
- webView: tType("AndroidWebView")
- });
- scheme.AndroidDeviceWebViewRemovedEvent = tObject({
- socketName: tString
- });
- scheme.AndroidDeviceWaitParams = tObject({
- androidSelector: tType("AndroidSelector"),
- state: tOptional(tEnum(["gone"])),
- timeout: tFloat
- });
- scheme.AndroidDeviceWaitResult = tOptional(tObject({}));
- scheme.AndroidDeviceFillParams = tObject({
- androidSelector: tType("AndroidSelector"),
- text: tString,
- timeout: tFloat
- });
- scheme.AndroidDeviceFillResult = tOptional(tObject({}));
- scheme.AndroidDeviceTapParams = tObject({
- androidSelector: tType("AndroidSelector"),
- duration: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDeviceTapResult = tOptional(tObject({}));
- scheme.AndroidDeviceDragParams = tObject({
- androidSelector: tType("AndroidSelector"),
- dest: tType("Point"),
- speed: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDeviceDragResult = tOptional(tObject({}));
- scheme.AndroidDeviceFlingParams = tObject({
- androidSelector: tType("AndroidSelector"),
- direction: tEnum(["up", "down", "left", "right"]),
- speed: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDeviceFlingResult = tOptional(tObject({}));
- scheme.AndroidDeviceLongTapParams = tObject({
- androidSelector: tType("AndroidSelector"),
- timeout: tFloat
- });
- scheme.AndroidDeviceLongTapResult = tOptional(tObject({}));
- scheme.AndroidDevicePinchCloseParams = tObject({
- androidSelector: tType("AndroidSelector"),
- percent: tFloat,
- speed: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDevicePinchCloseResult = tOptional(tObject({}));
- scheme.AndroidDevicePinchOpenParams = tObject({
- androidSelector: tType("AndroidSelector"),
- percent: tFloat,
- speed: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDevicePinchOpenResult = tOptional(tObject({}));
- scheme.AndroidDeviceScrollParams = tObject({
- androidSelector: tType("AndroidSelector"),
- direction: tEnum(["up", "down", "left", "right"]),
- percent: tFloat,
- speed: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDeviceScrollResult = tOptional(tObject({}));
- scheme.AndroidDeviceSwipeParams = tObject({
- androidSelector: tType("AndroidSelector"),
- direction: tEnum(["up", "down", "left", "right"]),
- percent: tFloat,
- speed: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.AndroidDeviceSwipeResult = tOptional(tObject({}));
- scheme.AndroidDeviceInfoParams = tObject({
- androidSelector: tType("AndroidSelector")
- });
- scheme.AndroidDeviceInfoResult = tObject({
- info: tType("AndroidElementInfo")
- });
- scheme.AndroidDeviceScreenshotParams = tOptional(tObject({}));
- scheme.AndroidDeviceScreenshotResult = tObject({
- binary: tBinary
- });
- scheme.AndroidDeviceInputTypeParams = tObject({
- text: tString
- });
- scheme.AndroidDeviceInputTypeResult = tOptional(tObject({}));
- scheme.AndroidDeviceInputPressParams = tObject({
- key: tString
- });
- scheme.AndroidDeviceInputPressResult = tOptional(tObject({}));
- scheme.AndroidDeviceInputTapParams = tObject({
- point: tType("Point")
- });
- scheme.AndroidDeviceInputTapResult = tOptional(tObject({}));
- scheme.AndroidDeviceInputSwipeParams = tObject({
- segments: tArray(tType("Point")),
- steps: tInt
- });
- scheme.AndroidDeviceInputSwipeResult = tOptional(tObject({}));
- scheme.AndroidDeviceInputDragParams = tObject({
- from: tType("Point"),
- to: tType("Point"),
- steps: tInt
- });
- scheme.AndroidDeviceInputDragResult = tOptional(tObject({}));
- scheme.AndroidDeviceLaunchBrowserParams = tObject({
- noDefaultViewport: tOptional(tBoolean),
- viewport: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- screen: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- ignoreHTTPSErrors: tOptional(tBoolean),
- clientCertificates: tOptional(tArray(tObject({
- origin: tString,
- cert: tOptional(tBinary),
- key: tOptional(tBinary),
- passphrase: tOptional(tString),
- pfx: tOptional(tBinary)
- }))),
- javaScriptEnabled: tOptional(tBoolean),
- bypassCSP: tOptional(tBoolean),
- userAgent: tOptional(tString),
- locale: tOptional(tString),
- timezoneId: tOptional(tString),
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- })),
- permissions: tOptional(tArray(tString)),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- offline: tOptional(tBoolean),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString),
- send: tOptional(tEnum(["always", "unauthorized"]))
- })),
- deviceScaleFactor: tOptional(tFloat),
- isMobile: tOptional(tBoolean),
- hasTouch: tOptional(tBoolean),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),
- forcedColors: tOptional(tEnum(["active", "none", "no-override"])),
- acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),
- contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),
- baseURL: tOptional(tString),
- recordVideo: tOptional(tObject({
- dir: tOptional(tString),
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- showActions: tOptional(tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- }))
- })),
- strictSelectors: tOptional(tBoolean),
- serviceWorkers: tOptional(tEnum(["allow", "block"])),
- selectorEngines: tOptional(tArray(tType("SelectorEngine"))),
- testIdAttributeName: tOptional(tString),
- pkg: tOptional(tString),
- args: tOptional(tArray(tString)),
- proxy: tOptional(tObject({
- server: tString,
- bypass: tOptional(tString),
- username: tOptional(tString),
- password: tOptional(tString)
- }))
- });
- scheme.AndroidDeviceLaunchBrowserResult = tObject({
- context: tChannel(["BrowserContext"])
- });
- scheme.AndroidDeviceOpenParams = tObject({
- command: tString
- });
- scheme.AndroidDeviceOpenResult = tObject({
- socket: tChannel(["AndroidSocket"])
- });
- scheme.AndroidDeviceShellParams = tObject({
- command: tString
- });
- scheme.AndroidDeviceShellResult = tObject({
- result: tBinary
- });
- scheme.AndroidDeviceInstallApkParams = tObject({
- file: tBinary,
- args: tOptional(tArray(tString))
- });
- scheme.AndroidDeviceInstallApkResult = tOptional(tObject({}));
- scheme.AndroidDevicePushParams = tObject({
- file: tBinary,
- path: tString,
- mode: tOptional(tInt)
- });
- scheme.AndroidDevicePushResult = tOptional(tObject({}));
- scheme.AndroidDeviceConnectToWebViewParams = tObject({
- socketName: tString
- });
- scheme.AndroidDeviceConnectToWebViewResult = tObject({
- context: tChannel(["BrowserContext"])
- });
- scheme.AndroidDeviceCloseParams = tOptional(tObject({}));
- scheme.AndroidDeviceCloseResult = tOptional(tObject({}));
- scheme.AndroidWebView = tObject({
- pid: tInt,
- pkg: tString,
- socketName: tString
- });
- scheme.AndroidSelector = tObject({
- checkable: tOptional(tBoolean),
- checked: tOptional(tBoolean),
- clazz: tOptional(tString),
- clickable: tOptional(tBoolean),
- depth: tOptional(tInt),
- desc: tOptional(tString),
- enabled: tOptional(tBoolean),
- focusable: tOptional(tBoolean),
- focused: tOptional(tBoolean),
- hasChild: tOptional(tObject({
- androidSelector: tType("AndroidSelector")
- })),
- hasDescendant: tOptional(tObject({
- androidSelector: tType("AndroidSelector"),
- maxDepth: tOptional(tInt)
- })),
- longClickable: tOptional(tBoolean),
- pkg: tOptional(tString),
- res: tOptional(tString),
- scrollable: tOptional(tBoolean),
- selected: tOptional(tBoolean),
- text: tOptional(tString)
- });
- scheme.AndroidElementInfo = tObject({
- children: tOptional(tArray(tType("AndroidElementInfo"))),
- clazz: tString,
- desc: tString,
- res: tString,
- pkg: tString,
- text: tString,
- bounds: tType("Rect"),
- checkable: tBoolean,
- checked: tBoolean,
- clickable: tBoolean,
- enabled: tBoolean,
- focusable: tBoolean,
- focused: tBoolean,
- longClickable: tBoolean,
- scrollable: tBoolean,
- selected: tBoolean
- });
- scheme.APIRequestContextInitializer = tObject({
- tracing: tChannel(["Tracing"])
- });
- scheme.APIRequestContextFetchParams = tObject({
- url: tString,
- encodedParams: tOptional(tString),
- params: tOptional(tArray(tType("NameValue"))),
- method: tOptional(tString),
- headers: tOptional(tArray(tType("NameValue"))),
- postData: tOptional(tBinary),
- jsonData: tOptional(tString),
- formData: tOptional(tArray(tType("NameValue"))),
- multipartData: tOptional(tArray(tType("FormField"))),
- timeout: tFloat,
- failOnStatusCode: tOptional(tBoolean),
- ignoreHTTPSErrors: tOptional(tBoolean),
- maxRedirects: tOptional(tInt),
- maxRetries: tOptional(tInt)
- });
- scheme.APIRequestContextFetchResult = tObject({
- response: tType("APIResponse")
- });
- scheme.APIRequestContextFetchResponseBodyParams = tObject({
- fetchUid: tString
- });
- scheme.APIRequestContextFetchResponseBodyResult = tObject({
- binary: tOptional(tBinary)
- });
- scheme.APIRequestContextFetchLogParams = tObject({
- fetchUid: tString
- });
- scheme.APIRequestContextFetchLogResult = tObject({
- log: tArray(tString)
- });
- scheme.APIRequestContextStorageStateParams = tObject({
- indexedDB: tOptional(tBoolean)
- });
- scheme.APIRequestContextStorageStateResult = tObject({
- cookies: tArray(tType("NetworkCookie")),
- origins: tArray(tType("OriginStorage"))
- });
- scheme.APIRequestContextDisposeAPIResponseParams = tObject({
- fetchUid: tString
- });
- scheme.APIRequestContextDisposeAPIResponseResult = tOptional(tObject({}));
- scheme.APIRequestContextDisposeParams = tObject({
- reason: tOptional(tString)
- });
- scheme.APIRequestContextDisposeResult = tOptional(tObject({}));
- scheme.APIResponse = tObject({
- fetchUid: tString,
- url: tString,
- status: tInt,
- statusText: tString,
- headers: tArray(tType("NameValue")),
- securityDetails: tOptional(tType("SecurityDetails")),
- serverAddr: tOptional(tType("RemoteAddr"))
- });
- scheme.ArtifactInitializer = tObject({
- absolutePath: tString
- });
- scheme.ArtifactPathAfterFinishedParams = tOptional(tObject({}));
- scheme.ArtifactPathAfterFinishedResult = tObject({
- value: tString
- });
- scheme.ArtifactSaveAsParams = tObject({
- path: tString
- });
- scheme.ArtifactSaveAsResult = tOptional(tObject({}));
- scheme.ArtifactSaveAsStreamParams = tOptional(tObject({}));
- scheme.ArtifactSaveAsStreamResult = tObject({
- stream: tChannel(["Stream"])
- });
- scheme.ArtifactFailureParams = tOptional(tObject({}));
- scheme.ArtifactFailureResult = tObject({
- error: tOptional(tString)
- });
- scheme.ArtifactStreamParams = tOptional(tObject({}));
- scheme.ArtifactStreamResult = tObject({
- stream: tChannel(["Stream"])
- });
- scheme.ArtifactCancelParams = tOptional(tObject({}));
- scheme.ArtifactCancelResult = tOptional(tObject({}));
- scheme.ArtifactDeleteParams = tOptional(tObject({}));
- scheme.ArtifactDeleteResult = tOptional(tObject({}));
- scheme.StreamInitializer = tOptional(tObject({}));
- scheme.StreamReadParams = tObject({
- size: tOptional(tInt)
- });
- scheme.StreamReadResult = tObject({
- binary: tBinary
- });
- scheme.StreamCloseParams = tOptional(tObject({}));
- scheme.StreamCloseResult = tOptional(tObject({}));
- scheme.WritableStreamInitializer = tOptional(tObject({}));
- scheme.WritableStreamWriteParams = tObject({
- binary: tBinary
- });
- scheme.WritableStreamWriteResult = tOptional(tObject({}));
- scheme.WritableStreamCloseParams = tOptional(tObject({}));
- scheme.WritableStreamCloseResult = tOptional(tObject({}));
- scheme.BrowserInitializer = tObject({
- version: tString,
- name: tString,
- browserName: tEnum(["chromium", "firefox", "webkit"])
- });
- scheme.BrowserContextEvent = tObject({
- context: tChannel(["BrowserContext"])
- });
- scheme.BrowserCloseEvent = tOptional(tObject({}));
- scheme.BrowserStartServerParams = tObject({
- title: tString,
- workspaceDir: tOptional(tString),
- metadata: tOptional(tAny),
- host: tOptional(tString),
- port: tOptional(tInt)
- });
- scheme.BrowserStartServerResult = tObject({
- endpoint: tString
- });
- scheme.BrowserStopServerParams = tOptional(tObject({}));
- scheme.BrowserStopServerResult = tOptional(tObject({}));
- scheme.BrowserCloseParams = tObject({
- reason: tOptional(tString)
- });
- scheme.BrowserCloseResult = tOptional(tObject({}));
- scheme.BrowserKillForTestsParams = tOptional(tObject({}));
- scheme.BrowserKillForTestsResult = tOptional(tObject({}));
- scheme.BrowserDefaultUserAgentForTestParams = tOptional(tObject({}));
- scheme.BrowserDefaultUserAgentForTestResult = tObject({
- userAgent: tString
- });
- scheme.BrowserNewContextParams = tObject({
- noDefaultViewport: tOptional(tBoolean),
- viewport: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- screen: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- ignoreHTTPSErrors: tOptional(tBoolean),
- clientCertificates: tOptional(tArray(tObject({
- origin: tString,
- cert: tOptional(tBinary),
- key: tOptional(tBinary),
- passphrase: tOptional(tString),
- pfx: tOptional(tBinary)
- }))),
- javaScriptEnabled: tOptional(tBoolean),
- bypassCSP: tOptional(tBoolean),
- userAgent: tOptional(tString),
- locale: tOptional(tString),
- timezoneId: tOptional(tString),
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- })),
- permissions: tOptional(tArray(tString)),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- offline: tOptional(tBoolean),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString),
- send: tOptional(tEnum(["always", "unauthorized"]))
- })),
- deviceScaleFactor: tOptional(tFloat),
- isMobile: tOptional(tBoolean),
- hasTouch: tOptional(tBoolean),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),
- forcedColors: tOptional(tEnum(["active", "none", "no-override"])),
- acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),
- contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),
- baseURL: tOptional(tString),
- recordVideo: tOptional(tObject({
- dir: tOptional(tString),
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- showActions: tOptional(tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- }))
- })),
- strictSelectors: tOptional(tBoolean),
- serviceWorkers: tOptional(tEnum(["allow", "block"])),
- selectorEngines: tOptional(tArray(tType("SelectorEngine"))),
- testIdAttributeName: tOptional(tString),
- proxy: tOptional(tObject({
- server: tString,
- bypass: tOptional(tString),
- username: tOptional(tString),
- password: tOptional(tString)
- })),
- storageState: tOptional(tObject({
- cookies: tOptional(tArray(tType("SetNetworkCookie"))),
- origins: tOptional(tArray(tType("SetOriginStorage")))
- }))
- });
- scheme.BrowserNewContextResult = tObject({
- context: tChannel(["BrowserContext"])
- });
- scheme.BrowserNewContextForReuseParams = tObject({
- noDefaultViewport: tOptional(tBoolean),
- viewport: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- screen: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- ignoreHTTPSErrors: tOptional(tBoolean),
- clientCertificates: tOptional(tArray(tObject({
- origin: tString,
- cert: tOptional(tBinary),
- key: tOptional(tBinary),
- passphrase: tOptional(tString),
- pfx: tOptional(tBinary)
- }))),
- javaScriptEnabled: tOptional(tBoolean),
- bypassCSP: tOptional(tBoolean),
- userAgent: tOptional(tString),
- locale: tOptional(tString),
- timezoneId: tOptional(tString),
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- })),
- permissions: tOptional(tArray(tString)),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- offline: tOptional(tBoolean),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString),
- send: tOptional(tEnum(["always", "unauthorized"]))
- })),
- deviceScaleFactor: tOptional(tFloat),
- isMobile: tOptional(tBoolean),
- hasTouch: tOptional(tBoolean),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),
- forcedColors: tOptional(tEnum(["active", "none", "no-override"])),
- acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),
- contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),
- baseURL: tOptional(tString),
- recordVideo: tOptional(tObject({
- dir: tOptional(tString),
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- showActions: tOptional(tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- }))
- })),
- strictSelectors: tOptional(tBoolean),
- serviceWorkers: tOptional(tEnum(["allow", "block"])),
- selectorEngines: tOptional(tArray(tType("SelectorEngine"))),
- testIdAttributeName: tOptional(tString),
- proxy: tOptional(tObject({
- server: tString,
- bypass: tOptional(tString),
- username: tOptional(tString),
- password: tOptional(tString)
- })),
- storageState: tOptional(tObject({
- cookies: tOptional(tArray(tType("SetNetworkCookie"))),
- origins: tOptional(tArray(tType("SetOriginStorage")))
- }))
- });
- scheme.BrowserNewContextForReuseResult = tObject({
- context: tChannel(["BrowserContext"])
- });
- scheme.BrowserDisconnectFromReusedContextParams = tObject({
- reason: tString
- });
- scheme.BrowserDisconnectFromReusedContextResult = tOptional(tObject({}));
- scheme.BrowserNewBrowserCDPSessionParams = tOptional(tObject({}));
- scheme.BrowserNewBrowserCDPSessionResult = tObject({
- session: tChannel(["CDPSession"])
- });
- scheme.BrowserStartTracingParams = tObject({
- page: tOptional(tChannel(["Page"])),
- screenshots: tOptional(tBoolean),
- categories: tOptional(tArray(tString))
- });
- scheme.BrowserStartTracingResult = tOptional(tObject({}));
- scheme.BrowserStopTracingParams = tOptional(tObject({}));
- scheme.BrowserStopTracingResult = tObject({
- artifact: tChannel(["Artifact"])
- });
- scheme.BrowserContextInitializer = tObject({
- debugger: tChannel(["Debugger"]),
- requestContext: tChannel(["APIRequestContext"]),
- tracing: tChannel(["Tracing"]),
- options: tObject({
- noDefaultViewport: tOptional(tBoolean),
- viewport: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- screen: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- ignoreHTTPSErrors: tOptional(tBoolean),
- clientCertificates: tOptional(tArray(tObject({
- origin: tString,
- cert: tOptional(tBinary),
- key: tOptional(tBinary),
- passphrase: tOptional(tString),
- pfx: tOptional(tBinary)
- }))),
- javaScriptEnabled: tOptional(tBoolean),
- bypassCSP: tOptional(tBoolean),
- userAgent: tOptional(tString),
- locale: tOptional(tString),
- timezoneId: tOptional(tString),
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- })),
- permissions: tOptional(tArray(tString)),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- offline: tOptional(tBoolean),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString),
- send: tOptional(tEnum(["always", "unauthorized"]))
- })),
- deviceScaleFactor: tOptional(tFloat),
- isMobile: tOptional(tBoolean),
- hasTouch: tOptional(tBoolean),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),
- forcedColors: tOptional(tEnum(["active", "none", "no-override"])),
- acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),
- contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),
- baseURL: tOptional(tString),
- recordVideo: tOptional(tObject({
- dir: tOptional(tString),
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- showActions: tOptional(tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- }))
- })),
- strictSelectors: tOptional(tBoolean),
- serviceWorkers: tOptional(tEnum(["allow", "block"])),
- selectorEngines: tOptional(tArray(tType("SelectorEngine"))),
- testIdAttributeName: tOptional(tString)
- })
- });
- scheme.BrowserContextBindingCallEvent = tObject({
- binding: tChannel(["BindingCall"])
- });
- scheme.BrowserContextConsoleEvent = tObject({
- type: tString,
- text: tString,
- args: tArray(tChannel(["ElementHandle", "JSHandle"])),
- location: tObject({
- url: tString,
- lineNumber: tInt,
- columnNumber: tInt
- }),
- timestamp: tFloat,
- page: tOptional(tChannel(["Page"])),
- worker: tOptional(tChannel(["Worker"]))
- });
- scheme.BrowserContextCloseEvent = tOptional(tObject({}));
- scheme.BrowserContextDialogEvent = tObject({
- dialog: tChannel(["Dialog"])
- });
- scheme.BrowserContextPageEvent = tObject({
- page: tChannel(["Page"])
- });
- scheme.BrowserContextPageErrorEvent = tObject({
- error: tType("SerializedError"),
- page: tChannel(["Page"]),
- location: tObject({
- url: tString,
- line: tInt,
- column: tInt
- })
- });
- scheme.BrowserContextRouteEvent = tObject({
- route: tChannel(["Route"])
- });
- scheme.BrowserContextWebSocketRouteEvent = tObject({
- webSocketRoute: tChannel(["WebSocketRoute"])
- });
- scheme.BrowserContextServiceWorkerEvent = tObject({
- worker: tChannel(["Worker"])
- });
- scheme.BrowserContextRequestEvent = tObject({
- request: tChannel(["Request"]),
- page: tOptional(tChannel(["Page"]))
- });
- scheme.BrowserContextRequestFailedEvent = tObject({
- request: tChannel(["Request"]),
- failureText: tOptional(tString),
- responseEndTiming: tFloat,
- page: tOptional(tChannel(["Page"]))
- });
- scheme.BrowserContextRequestFinishedEvent = tObject({
- request: tChannel(["Request"]),
- response: tOptional(tChannel(["Response"])),
- responseEndTiming: tFloat,
- page: tOptional(tChannel(["Page"]))
- });
- scheme.BrowserContextResponseEvent = tObject({
- response: tChannel(["Response"]),
- page: tOptional(tChannel(["Page"]))
- });
- scheme.BrowserContextRecorderEventEvent = tObject({
- event: tEnum(["actionAdded", "actionUpdated", "signalAdded"]),
- data: tAny,
- page: tChannel(["Page"]),
- code: tString
- });
- scheme.BrowserContextAddCookiesParams = tObject({
- cookies: tArray(tType("SetNetworkCookie"))
- });
- scheme.BrowserContextAddCookiesResult = tOptional(tObject({}));
- scheme.BrowserContextAddInitScriptParams = tObject({
- source: tString
- });
- scheme.BrowserContextAddInitScriptResult = tObject({
- disposable: tChannel(["Disposable"])
- });
- scheme.BrowserContextClearCookiesParams = tObject({
- name: tOptional(tString),
- nameRegexSource: tOptional(tString),
- nameRegexFlags: tOptional(tString),
- domain: tOptional(tString),
- domainRegexSource: tOptional(tString),
- domainRegexFlags: tOptional(tString),
- path: tOptional(tString),
- pathRegexSource: tOptional(tString),
- pathRegexFlags: tOptional(tString)
- });
- scheme.BrowserContextClearCookiesResult = tOptional(tObject({}));
- scheme.BrowserContextClearPermissionsParams = tOptional(tObject({}));
- scheme.BrowserContextClearPermissionsResult = tOptional(tObject({}));
- scheme.BrowserContextCloseParams = tObject({
- reason: tOptional(tString)
- });
- scheme.BrowserContextCloseResult = tOptional(tObject({}));
- scheme.BrowserContextCookiesParams = tObject({
- urls: tArray(tString)
- });
- scheme.BrowserContextCookiesResult = tObject({
- cookies: tArray(tType("NetworkCookie"))
- });
- scheme.BrowserContextExposeBindingParams = tObject({
- name: tString
- });
- scheme.BrowserContextExposeBindingResult = tObject({
- disposable: tChannel(["Disposable"])
- });
- scheme.BrowserContextGrantPermissionsParams = tObject({
- permissions: tArray(tString),
- origin: tOptional(tString)
- });
- scheme.BrowserContextGrantPermissionsResult = tOptional(tObject({}));
- scheme.BrowserContextNewPageParams = tOptional(tObject({}));
- scheme.BrowserContextNewPageResult = tObject({
- page: tChannel(["Page"])
- });
- scheme.BrowserContextRegisterSelectorEngineParams = tObject({
- selectorEngine: tType("SelectorEngine")
- });
- scheme.BrowserContextRegisterSelectorEngineResult = tOptional(tObject({}));
- scheme.BrowserContextSetTestIdAttributeNameParams = tObject({
- testIdAttributeName: tString
- });
- scheme.BrowserContextSetTestIdAttributeNameResult = tOptional(tObject({}));
- scheme.BrowserContextSetExtraHTTPHeadersParams = tObject({
- headers: tArray(tType("NameValue"))
- });
- scheme.BrowserContextSetExtraHTTPHeadersResult = tOptional(tObject({}));
- scheme.BrowserContextSetGeolocationParams = tObject({
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- }))
- });
- scheme.BrowserContextSetGeolocationResult = tOptional(tObject({}));
- scheme.BrowserContextSetHTTPCredentialsParams = tObject({
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString)
- }))
- });
- scheme.BrowserContextSetHTTPCredentialsResult = tOptional(tObject({}));
- scheme.BrowserContextSetNetworkInterceptionPatternsParams = tObject({
- patterns: tArray(tObject({
- glob: tOptional(tString),
- regexSource: tOptional(tString),
- regexFlags: tOptional(tString),
- urlPattern: tOptional(tType("URLPattern"))
- }))
- });
- scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({}));
- scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({
- patterns: tArray(tObject({
- glob: tOptional(tString),
- regexSource: tOptional(tString),
- regexFlags: tOptional(tString),
- urlPattern: tOptional(tType("URLPattern"))
- }))
- });
- scheme.BrowserContextSetWebSocketInterceptionPatternsResult = tOptional(tObject({}));
- scheme.BrowserContextSetOfflineParams = tObject({
- offline: tBoolean
- });
- scheme.BrowserContextSetOfflineResult = tOptional(tObject({}));
- scheme.BrowserContextStorageStateParams = tObject({
- indexedDB: tOptional(tBoolean)
- });
- scheme.BrowserContextStorageStateResult = tObject({
- cookies: tArray(tType("NetworkCookie")),
- origins: tArray(tType("OriginStorage"))
- });
- scheme.BrowserContextSetStorageStateParams = tObject({
- storageState: tOptional(tObject({
- cookies: tOptional(tArray(tType("SetNetworkCookie"))),
- origins: tOptional(tArray(tType("SetOriginStorage")))
- }))
- });
- scheme.BrowserContextSetStorageStateResult = tOptional(tObject({}));
- scheme.BrowserContextPauseParams = tOptional(tObject({}));
- scheme.BrowserContextPauseResult = tOptional(tObject({}));
- scheme.BrowserContextEnableRecorderParams = tObject({
- language: tOptional(tString),
- mode: tOptional(tEnum(["inspecting", "recording"])),
- recorderMode: tOptional(tEnum(["default", "api"])),
- pauseOnNextStatement: tOptional(tBoolean),
- testIdAttributeName: tOptional(tString),
- launchOptions: tOptional(tAny),
- contextOptions: tOptional(tAny),
- device: tOptional(tString),
- saveStorage: tOptional(tString),
- outputFile: tOptional(tString),
- handleSIGINT: tOptional(tBoolean),
- omitCallTracking: tOptional(tBoolean)
- });
- scheme.BrowserContextEnableRecorderResult = tOptional(tObject({}));
- scheme.BrowserContextDisableRecorderParams = tOptional(tObject({}));
- scheme.BrowserContextDisableRecorderResult = tOptional(tObject({}));
- scheme.BrowserContextExposeConsoleApiParams = tOptional(tObject({}));
- scheme.BrowserContextExposeConsoleApiResult = tOptional(tObject({}));
- scheme.BrowserContextNewCDPSessionParams = tObject({
- page: tOptional(tChannel(["Page"])),
- frame: tOptional(tChannel(["Frame"]))
- });
- scheme.BrowserContextNewCDPSessionResult = tObject({
- session: tChannel(["CDPSession"])
- });
- scheme.BrowserContextCreateTempFilesParams = tObject({
- rootDirName: tOptional(tString),
- items: tArray(tObject({
- name: tString,
- lastModifiedMs: tOptional(tFloat)
- }))
- });
- scheme.BrowserContextCreateTempFilesResult = tObject({
- rootDir: tOptional(tChannel(["WritableStream"])),
- writableStreams: tArray(tChannel(["WritableStream"]))
- });
- scheme.BrowserContextUpdateSubscriptionParams = tObject({
- event: tEnum(["console", "dialog", "request", "response", "requestFinished", "requestFailed"]),
- enabled: tBoolean
- });
- scheme.BrowserContextUpdateSubscriptionResult = tOptional(tObject({}));
- scheme.BrowserContextClockFastForwardParams = tObject({
- ticksNumber: tOptional(tFloat),
- ticksString: tOptional(tString)
- });
- scheme.BrowserContextClockFastForwardResult = tOptional(tObject({}));
- scheme.BrowserContextClockInstallParams = tObject({
- timeNumber: tOptional(tFloat),
- timeString: tOptional(tString)
- });
- scheme.BrowserContextClockInstallResult = tOptional(tObject({}));
- scheme.BrowserContextClockPauseAtParams = tObject({
- timeNumber: tOptional(tFloat),
- timeString: tOptional(tString)
- });
- scheme.BrowserContextClockPauseAtResult = tOptional(tObject({}));
- scheme.BrowserContextClockResumeParams = tOptional(tObject({}));
- scheme.BrowserContextClockResumeResult = tOptional(tObject({}));
- scheme.BrowserContextClockRunForParams = tObject({
- ticksNumber: tOptional(tFloat),
- ticksString: tOptional(tString)
- });
- scheme.BrowserContextClockRunForResult = tOptional(tObject({}));
- scheme.BrowserContextClockSetFixedTimeParams = tObject({
- timeNumber: tOptional(tFloat),
- timeString: tOptional(tString)
- });
- scheme.BrowserContextClockSetFixedTimeResult = tOptional(tObject({}));
- scheme.BrowserContextClockSetSystemTimeParams = tObject({
- timeNumber: tOptional(tFloat),
- timeString: tOptional(tString)
- });
- scheme.BrowserContextClockSetSystemTimeResult = tOptional(tObject({}));
- scheme.BrowserContextCredentialsInstallParams = tOptional(tObject({}));
- scheme.BrowserContextCredentialsInstallResult = tOptional(tObject({}));
- scheme.BrowserContextCredentialsCreateParams = tObject({
- rpId: tString,
- id: tOptional(tString),
- userHandle: tOptional(tString),
- privateKey: tOptional(tString),
- publicKey: tOptional(tString)
- });
- scheme.BrowserContextCredentialsCreateResult = tObject({
- credential: tType("VirtualCredential")
- });
- scheme.BrowserContextCredentialsGetParams = tObject({
- rpId: tOptional(tString),
- id: tOptional(tString)
- });
- scheme.BrowserContextCredentialsGetResult = tObject({
- credentials: tArray(tType("VirtualCredential"))
- });
- scheme.BrowserContextCredentialsDeleteParams = tObject({
- id: tString
- });
- scheme.BrowserContextCredentialsDeleteResult = tOptional(tObject({}));
- scheme.BrowserTypeInitializer = tObject({
- executablePath: tString,
- name: tString
- });
- scheme.BrowserTypeLaunchParams = tObject({
- channel: tOptional(tString),
- executablePath: tOptional(tString),
- args: tOptional(tArray(tString)),
- ignoreAllDefaultArgs: tOptional(tBoolean),
- ignoreDefaultArgs: tOptional(tArray(tString)),
- handleSIGINT: tOptional(tBoolean),
- handleSIGTERM: tOptional(tBoolean),
- handleSIGHUP: tOptional(tBoolean),
- timeout: tFloat,
- env: tOptional(tArray(tType("NameValue"))),
- headless: tOptional(tBoolean),
- proxy: tOptional(tObject({
- server: tString,
- bypass: tOptional(tString),
- username: tOptional(tString),
- password: tOptional(tString)
- })),
- downloadsPath: tOptional(tString),
- tracesDir: tOptional(tString),
- artifactsDir: tOptional(tString),
- chromiumSandbox: tOptional(tBoolean),
- firefoxUserPrefs: tOptional(tAny),
- cdpPort: tOptional(tInt),
- slowMo: tOptional(tFloat)
- });
- scheme.BrowserTypeLaunchResult = tObject({
- browser: tChannel(["Browser"])
- });
- scheme.BrowserTypeLaunchPersistentContextParams = tObject({
- channel: tOptional(tString),
- executablePath: tOptional(tString),
- args: tOptional(tArray(tString)),
- ignoreAllDefaultArgs: tOptional(tBoolean),
- ignoreDefaultArgs: tOptional(tArray(tString)),
- handleSIGINT: tOptional(tBoolean),
- handleSIGTERM: tOptional(tBoolean),
- handleSIGHUP: tOptional(tBoolean),
- timeout: tFloat,
- env: tOptional(tArray(tType("NameValue"))),
- headless: tOptional(tBoolean),
- proxy: tOptional(tObject({
- server: tString,
- bypass: tOptional(tString),
- username: tOptional(tString),
- password: tOptional(tString)
- })),
- downloadsPath: tOptional(tString),
- tracesDir: tOptional(tString),
- artifactsDir: tOptional(tString),
- chromiumSandbox: tOptional(tBoolean),
- firefoxUserPrefs: tOptional(tAny),
- cdpPort: tOptional(tInt),
- noDefaultViewport: tOptional(tBoolean),
- viewport: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- screen: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- ignoreHTTPSErrors: tOptional(tBoolean),
- clientCertificates: tOptional(tArray(tObject({
- origin: tString,
- cert: tOptional(tBinary),
- key: tOptional(tBinary),
- passphrase: tOptional(tString),
- pfx: tOptional(tBinary)
- }))),
- javaScriptEnabled: tOptional(tBoolean),
- bypassCSP: tOptional(tBoolean),
- userAgent: tOptional(tString),
- locale: tOptional(tString),
- timezoneId: tOptional(tString),
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- })),
- permissions: tOptional(tArray(tString)),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- offline: tOptional(tBoolean),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString),
- send: tOptional(tEnum(["always", "unauthorized"]))
- })),
- deviceScaleFactor: tOptional(tFloat),
- isMobile: tOptional(tBoolean),
- hasTouch: tOptional(tBoolean),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),
- forcedColors: tOptional(tEnum(["active", "none", "no-override"])),
- acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),
- contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),
- baseURL: tOptional(tString),
- recordVideo: tOptional(tObject({
- dir: tOptional(tString),
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- showActions: tOptional(tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- }))
- })),
- strictSelectors: tOptional(tBoolean),
- serviceWorkers: tOptional(tEnum(["allow", "block"])),
- selectorEngines: tOptional(tArray(tType("SelectorEngine"))),
- testIdAttributeName: tOptional(tString),
- userDataDir: tString,
- slowMo: tOptional(tFloat)
- });
- scheme.BrowserTypeLaunchPersistentContextResult = tObject({
- browser: tChannel(["Browser"]),
- context: tChannel(["BrowserContext"])
- });
- scheme.BrowserTypeConnectOverCDPParams = tObject({
- endpointURL: tOptional(tString),
- headers: tOptional(tArray(tType("NameValue"))),
- slowMo: tOptional(tFloat),
- timeout: tFloat,
- isLocal: tOptional(tBoolean),
- noDefaults: tOptional(tBoolean),
- artifactsDir: tOptional(tString),
- transport: tOptional(tBinary)
- });
- scheme.BrowserTypeConnectOverCDPResult = tObject({
- browser: tChannel(["Browser"]),
- defaultContext: tOptional(tChannel(["BrowserContext"]))
- });
- scheme.BrowserTypeConnectToWorkerParams = tObject({
- endpoint: tString,
- timeout: tFloat
- });
- scheme.BrowserTypeConnectToWorkerResult = tObject({
- worker: tChannel(["Worker"])
- });
- scheme.Metadata = tObject({
- location: tOptional(tObject({
- file: tString,
- line: tOptional(tInt),
- column: tOptional(tInt)
- })),
- title: tOptional(tString),
- internal: tOptional(tBoolean),
- stepId: tOptional(tString)
- });
- scheme.ClientSideCallMetadata = tObject({
- id: tInt,
- stack: tOptional(tArray(tType("StackFrame")))
- });
- scheme.SDKLanguage = tEnum(["javascript", "python", "java", "csharp"]);
- scheme.DisposableInitializer = tOptional(tObject({}));
- scheme.DisposableDisposeParams = tOptional(tObject({}));
- scheme.DisposableDisposeResult = tOptional(tObject({}));
- scheme.WaitInfo = tObject({
- waitId: tString,
- phase: tEnum(["before", "after", "log"]),
- event: tOptional(tString),
- message: tOptional(tString),
- error: tOptional(tString)
- });
- scheme.ElectronInitializer = tOptional(tObject({}));
- scheme.ElectronLaunchParams = tObject({
- executablePath: tOptional(tString),
- args: tOptional(tArray(tString)),
- chromiumSandbox: tOptional(tBoolean),
- cwd: tOptional(tString),
- env: tOptional(tArray(tType("NameValue"))),
- timeout: tFloat,
- acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),
- bypassCSP: tOptional(tBoolean),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- geolocation: tOptional(tObject({
- longitude: tFloat,
- latitude: tFloat,
- accuracy: tOptional(tFloat)
- })),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString)
- })),
- ignoreHTTPSErrors: tOptional(tBoolean),
- locale: tOptional(tString),
- offline: tOptional(tBoolean),
- recordVideo: tOptional(tObject({
- dir: tOptional(tString),
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- showActions: tOptional(tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- }))
- })),
- strictSelectors: tOptional(tBoolean),
- timezoneId: tOptional(tString),
- tracesDir: tOptional(tString),
- artifactsDir: tOptional(tString),
- selectorEngines: tOptional(tArray(tType("SelectorEngine"))),
- testIdAttributeName: tOptional(tString)
- });
- scheme.ElectronLaunchResult = tObject({
- electronApplication: tChannel(["ElectronApplication"])
- });
- scheme.ElectronApplicationInitializer = tObject({
- context: tChannel(["BrowserContext"])
- });
- scheme.ElectronApplicationCloseEvent = tOptional(tObject({}));
- scheme.ElectronApplicationConsoleEvent = tObject({
- type: tString,
- text: tString,
- args: tArray(tChannel(["ElementHandle", "JSHandle"])),
- location: tObject({
- url: tString,
- lineNumber: tInt,
- columnNumber: tInt
- }),
- timestamp: tFloat
- });
- scheme.ElectronApplicationBrowserWindowParams = tObject({
- page: tChannel(["Page"])
- });
- scheme.ElectronApplicationBrowserWindowResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.ElectronApplicationEvaluateExpressionParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.ElectronApplicationEvaluateExpressionResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.ElectronApplicationEvaluateExpressionHandleResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.ElectronApplicationUpdateSubscriptionParams = tObject({
- event: tEnum(["console"]),
- enabled: tBoolean
- });
- scheme.ElectronApplicationUpdateSubscriptionResult = tOptional(tObject({}));
- scheme.FrameInitializer = tObject({
- url: tString,
- name: tString,
- parentFrame: tOptional(tChannel(["Frame"])),
- loadStates: tArray(tType("LifecycleEvent"))
- });
- scheme.FrameLoadstateEvent = tObject({
- add: tOptional(tType("LifecycleEvent")),
- remove: tOptional(tType("LifecycleEvent"))
- });
- scheme.FrameNavigatedEvent = tObject({
- url: tString,
- name: tString,
- newDocument: tOptional(tObject({
- request: tOptional(tChannel(["Request"]))
- })),
- error: tOptional(tString)
- });
- scheme.FrameEvalOnSelectorParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.FrameEvalOnSelectorResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.FrameEvalOnSelectorAllParams = tObject({
- selector: tString,
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.FrameEvalOnSelectorAllResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.FrameAddScriptTagParams = tObject({
- url: tOptional(tString),
- content: tOptional(tString),
- type: tOptional(tString)
- });
- scheme.FrameAddScriptTagResult = tObject({
- element: tChannel(["ElementHandle"])
- });
- scheme.FrameAddStyleTagParams = tObject({
- url: tOptional(tString),
- content: tOptional(tString)
- });
- scheme.FrameAddStyleTagResult = tObject({
- element: tChannel(["ElementHandle"])
- });
- scheme.FrameAriaSnapshotParams = tObject({
- mode: tOptional(tEnum(["ai", "default"])),
- track: tOptional(tString),
- selector: tOptional(tString),
- depth: tOptional(tInt),
- boxes: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameAriaSnapshotResult = tObject({
- snapshot: tString
- });
- scheme.FrameBlurParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameBlurResult = tOptional(tObject({}));
- scheme.FrameCheckParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- force: tOptional(tBoolean),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.FrameCheckResult = tOptional(tObject({}));
- scheme.FrameClickParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- force: tOptional(tBoolean),
- noWaitAfter: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- delay: tOptional(tFloat),
- button: tOptional(tEnum(["left", "right", "middle"])),
- clickCount: tOptional(tInt),
- timeout: tFloat,
- trial: tOptional(tBoolean),
- steps: tOptional(tInt)
- });
- scheme.FrameClickResult = tOptional(tObject({}));
- scheme.FrameContentParams = tOptional(tObject({}));
- scheme.FrameContentResult = tObject({
- value: tString
- });
- scheme.FrameDragAndDropParams = tObject({
- source: tString,
- target: tString,
- force: tOptional(tBoolean),
- timeout: tFloat,
- trial: tOptional(tBoolean),
- sourcePosition: tOptional(tType("Point")),
- targetPosition: tOptional(tType("Point")),
- strict: tOptional(tBoolean),
- steps: tOptional(tInt)
- });
- scheme.FrameDragAndDropResult = tOptional(tObject({}));
- scheme.FrameDropParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- position: tOptional(tType("Point")),
- payloads: tOptional(tArray(tObject({
- name: tString,
- mimeType: tOptional(tString),
- buffer: tBinary
- }))),
- localPaths: tOptional(tArray(tString)),
- streams: tOptional(tArray(tChannel(["WritableStream"]))),
- data: tOptional(tArray(tObject({
- mimeType: tString,
- value: tString
- }))),
- timeout: tFloat
- });
- scheme.FrameDropResult = tOptional(tObject({}));
- scheme.FrameDblclickParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- force: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- delay: tOptional(tFloat),
- button: tOptional(tEnum(["left", "right", "middle"])),
- timeout: tFloat,
- trial: tOptional(tBoolean),
- steps: tOptional(tInt)
- });
- scheme.FrameDblclickResult = tOptional(tObject({}));
- scheme.FrameDispatchEventParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- type: tString,
- eventInit: tType("SerializedArgument"),
- timeout: tFloat
- });
- scheme.FrameDispatchEventResult = tOptional(tObject({}));
- scheme.FrameEvaluateExpressionParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.FrameEvaluateExpressionResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.FrameEvaluateExpressionHandleParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.FrameEvaluateExpressionHandleResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.FrameFillParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- value: tString,
- force: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameFillResult = tOptional(tObject({}));
- scheme.FrameFocusParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameFocusResult = tOptional(tObject({}));
- scheme.FrameFrameElementParams = tOptional(tObject({}));
- scheme.FrameFrameElementResult = tObject({
- element: tChannel(["ElementHandle"])
- });
- scheme.FrameResolveSelectorParams = tObject({
- selector: tString
- });
- scheme.FrameResolveSelectorResult = tObject({
- resolvedSelector: tString
- });
- scheme.FrameHighlightParams = tObject({
- selector: tString,
- style: tOptional(tString)
- });
- scheme.FrameHighlightResult = tOptional(tObject({}));
- scheme.FrameHideHighlightParams = tObject({
- selector: tString
- });
- scheme.FrameHideHighlightResult = tOptional(tObject({}));
- scheme.FrameGetAttributeParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- name: tString,
- timeout: tFloat
- });
- scheme.FrameGetAttributeResult = tObject({
- value: tOptional(tString)
- });
- scheme.FrameGotoParams = tObject({
- url: tString,
- timeout: tFloat,
- waitUntil: tOptional(tType("LifecycleEvent")),
- referer: tOptional(tString)
- });
- scheme.FrameGotoResult = tObject({
- response: tOptional(tChannel(["Response"]))
- });
- scheme.FrameHoverParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- force: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.FrameHoverResult = tOptional(tObject({}));
- scheme.FrameInnerHTMLParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameInnerHTMLResult = tObject({
- value: tString
- });
- scheme.FrameInnerTextParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameInnerTextResult = tObject({
- value: tString
- });
- scheme.FrameInputValueParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameInputValueResult = tObject({
- value: tString
- });
- scheme.FrameIsCheckedParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameIsCheckedResult = tObject({
- value: tBoolean
- });
- scheme.FrameIsDisabledParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameIsDisabledResult = tObject({
- value: tBoolean
- });
- scheme.FrameIsEnabledParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameIsEnabledResult = tObject({
- value: tBoolean
- });
- scheme.FrameIsHiddenParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean)
- });
- scheme.FrameIsHiddenResult = tObject({
- value: tBoolean
- });
- scheme.FrameIsVisibleParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean)
- });
- scheme.FrameIsVisibleResult = tObject({
- value: tBoolean
- });
- scheme.FrameIsEditableParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameIsEditableResult = tObject({
- value: tBoolean
- });
- scheme.FramePressParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- key: tString,
- delay: tOptional(tFloat),
- noWaitAfter: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FramePressResult = tOptional(tObject({}));
- scheme.FrameQuerySelectorParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean)
- });
- scheme.FrameQuerySelectorResult = tObject({
- element: tOptional(tChannel(["ElementHandle"]))
- });
- scheme.FrameQuerySelectorAllParams = tObject({
- selector: tString
- });
- scheme.FrameQuerySelectorAllResult = tObject({
- elements: tArray(tChannel(["ElementHandle"]))
- });
- scheme.FrameQueryCountParams = tObject({
- selector: tString
- });
- scheme.FrameQueryCountResult = tObject({
- value: tInt
- });
- scheme.FrameSelectOptionParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- elements: tOptional(tArray(tChannel(["ElementHandle"]))),
- options: tOptional(tArray(tObject({
- valueOrLabel: tOptional(tString),
- value: tOptional(tString),
- label: tOptional(tString),
- index: tOptional(tInt)
- }))),
- force: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameSelectOptionResult = tObject({
- values: tArray(tString)
- });
- scheme.FrameSetContentParams = tObject({
- html: tString,
- timeout: tFloat,
- waitUntil: tOptional(tType("LifecycleEvent"))
- });
- scheme.FrameSetContentResult = tOptional(tObject({}));
- scheme.FrameSetInputFilesParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- payloads: tOptional(tArray(tObject({
- name: tString,
- mimeType: tOptional(tString),
- buffer: tBinary
- }))),
- localDirectory: tOptional(tString),
- directoryStream: tOptional(tChannel(["WritableStream"])),
- localPaths: tOptional(tArray(tString)),
- streams: tOptional(tArray(tChannel(["WritableStream"]))),
- timeout: tFloat
- });
- scheme.FrameSetInputFilesResult = tOptional(tObject({}));
- scheme.FrameTapParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- force: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.FrameTapResult = tOptional(tObject({}));
- scheme.FrameTextContentParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.FrameTextContentResult = tObject({
- value: tOptional(tString)
- });
- scheme.FrameTitleParams = tOptional(tObject({}));
- scheme.FrameTitleResult = tObject({
- value: tString
- });
- scheme.FrameTypeParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- text: tString,
- delay: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.FrameTypeResult = tOptional(tObject({}));
- scheme.FrameUncheckParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- force: tOptional(tBoolean),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.FrameUncheckResult = tOptional(tObject({}));
- scheme.FrameWaitForTimeoutParams = tObject({
- waitTimeout: tFloat
- });
- scheme.FrameWaitForTimeoutResult = tOptional(tObject({}));
- scheme.FrameWaitForFunctionParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument"),
- timeout: tFloat,
- pollingInterval: tOptional(tFloat)
- });
- scheme.FrameWaitForFunctionResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.FrameWaitForSelectorParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat,
- state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])),
- omitReturnValue: tOptional(tBoolean)
- });
- scheme.FrameWaitForSelectorResult = tObject({
- element: tOptional(tChannel(["ElementHandle"]))
- });
- scheme.FrameExpectParams = tObject({
- selector: tOptional(tString),
- expression: tString,
- expressionArg: tOptional(tAny),
- pseudo: tOptional(tEnum(["before", "after"])),
- expectedText: tOptional(tArray(tType("ExpectedTextValue"))),
- expectedNumber: tOptional(tFloat),
- expectedValue: tOptional(tType("SerializedArgument")),
- useInnerText: tOptional(tBoolean),
- isNot: tBoolean,
- timeout: tFloat
- });
- scheme.FrameExpectResult = tOptional(tObject({}));
- scheme.FrameExpectErrorDetails = tObject({
- received: tOptional(tObject({
- value: tOptional(tType("SerializedValue")),
- ariaSnapshot: tOptional(tString)
- })),
- timedOut: tOptional(tBoolean),
- customErrorMessage: tOptional(tString)
- });
- scheme.JSHandleInitializer = tObject({
- preview: tString
- });
- scheme.JSHandlePreviewUpdatedEvent = tObject({
- preview: tString
- });
- scheme.ElementHandlePreviewUpdatedEvent = tType("JSHandlePreviewUpdatedEvent");
- scheme.JSHandleDisposeParams = tOptional(tObject({}));
- scheme.ElementHandleDisposeParams = tType("JSHandleDisposeParams");
- scheme.JSHandleDisposeResult = tOptional(tObject({}));
- scheme.ElementHandleDisposeResult = tType("JSHandleDisposeResult");
- scheme.JSHandleEvaluateExpressionParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.ElementHandleEvaluateExpressionParams = tType("JSHandleEvaluateExpressionParams");
- scheme.JSHandleEvaluateExpressionResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.ElementHandleEvaluateExpressionResult = tType("JSHandleEvaluateExpressionResult");
- scheme.JSHandleEvaluateExpressionHandleParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.ElementHandleEvaluateExpressionHandleParams = tType("JSHandleEvaluateExpressionHandleParams");
- scheme.JSHandleEvaluateExpressionHandleResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.ElementHandleEvaluateExpressionHandleResult = tType("JSHandleEvaluateExpressionHandleResult");
- scheme.JSHandleGetPropertyListParams = tOptional(tObject({}));
- scheme.ElementHandleGetPropertyListParams = tType("JSHandleGetPropertyListParams");
- scheme.JSHandleGetPropertyListResult = tObject({
- properties: tArray(tObject({
- name: tString,
- value: tChannel(["ElementHandle", "JSHandle"])
- }))
- });
- scheme.ElementHandleGetPropertyListResult = tType("JSHandleGetPropertyListResult");
- scheme.JSHandleGetPropertyParams = tObject({
- name: tString
- });
- scheme.ElementHandleGetPropertyParams = tType("JSHandleGetPropertyParams");
- scheme.JSHandleGetPropertyResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.ElementHandleGetPropertyResult = tType("JSHandleGetPropertyResult");
- scheme.JSHandleJsonValueParams = tOptional(tObject({}));
- scheme.ElementHandleJsonValueParams = tType("JSHandleJsonValueParams");
- scheme.JSHandleJsonValueResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.ElementHandleJsonValueResult = tType("JSHandleJsonValueResult");
- scheme.ElementHandleInitializer = tObject({
- preview: tString
- });
- scheme.ElementHandleEvalOnSelectorParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.ElementHandleEvalOnSelectorResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.ElementHandleEvalOnSelectorAllParams = tObject({
- selector: tString,
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.ElementHandleEvalOnSelectorAllResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.ElementHandleBoundingBoxParams = tOptional(tObject({}));
- scheme.ElementHandleBoundingBoxResult = tObject({
- value: tOptional(tType("Rect"))
- });
- scheme.ElementHandleCheckParams = tObject({
- force: tOptional(tBoolean),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.ElementHandleCheckResult = tOptional(tObject({}));
- scheme.ElementHandleClickParams = tObject({
- force: tOptional(tBoolean),
- noWaitAfter: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- delay: tOptional(tFloat),
- button: tOptional(tEnum(["left", "right", "middle"])),
- clickCount: tOptional(tInt),
- timeout: tFloat,
- trial: tOptional(tBoolean),
- steps: tOptional(tInt)
- });
- scheme.ElementHandleClickResult = tOptional(tObject({}));
- scheme.ElementHandleContentFrameParams = tOptional(tObject({}));
- scheme.ElementHandleContentFrameResult = tObject({
- frame: tOptional(tChannel(["Frame"]))
- });
- scheme.ElementHandleDblclickParams = tObject({
- force: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- delay: tOptional(tFloat),
- button: tOptional(tEnum(["left", "right", "middle"])),
- timeout: tFloat,
- trial: tOptional(tBoolean),
- steps: tOptional(tInt)
- });
- scheme.ElementHandleDblclickResult = tOptional(tObject({}));
- scheme.ElementHandleDispatchEventParams = tObject({
- type: tString,
- eventInit: tType("SerializedArgument")
- });
- scheme.ElementHandleDispatchEventResult = tOptional(tObject({}));
- scheme.ElementHandleFillParams = tObject({
- value: tString,
- force: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.ElementHandleFillResult = tOptional(tObject({}));
- scheme.ElementHandleFocusParams = tOptional(tObject({}));
- scheme.ElementHandleFocusResult = tOptional(tObject({}));
- scheme.ElementHandleGetAttributeParams = tObject({
- name: tString
- });
- scheme.ElementHandleGetAttributeResult = tObject({
- value: tOptional(tString)
- });
- scheme.ElementHandleHoverParams = tObject({
- force: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.ElementHandleHoverResult = tOptional(tObject({}));
- scheme.ElementHandleInnerHTMLParams = tOptional(tObject({}));
- scheme.ElementHandleInnerHTMLResult = tObject({
- value: tString
- });
- scheme.ElementHandleInnerTextParams = tOptional(tObject({}));
- scheme.ElementHandleInnerTextResult = tObject({
- value: tString
- });
- scheme.ElementHandleInputValueParams = tOptional(tObject({}));
- scheme.ElementHandleInputValueResult = tObject({
- value: tString
- });
- scheme.ElementHandleIsCheckedParams = tOptional(tObject({}));
- scheme.ElementHandleIsCheckedResult = tObject({
- value: tBoolean
- });
- scheme.ElementHandleIsDisabledParams = tOptional(tObject({}));
- scheme.ElementHandleIsDisabledResult = tObject({
- value: tBoolean
- });
- scheme.ElementHandleIsEditableParams = tOptional(tObject({}));
- scheme.ElementHandleIsEditableResult = tObject({
- value: tBoolean
- });
- scheme.ElementHandleIsEnabledParams = tOptional(tObject({}));
- scheme.ElementHandleIsEnabledResult = tObject({
- value: tBoolean
- });
- scheme.ElementHandleIsHiddenParams = tOptional(tObject({}));
- scheme.ElementHandleIsHiddenResult = tObject({
- value: tBoolean
- });
- scheme.ElementHandleIsVisibleParams = tOptional(tObject({}));
- scheme.ElementHandleIsVisibleResult = tObject({
- value: tBoolean
- });
- scheme.ElementHandleOwnerFrameParams = tOptional(tObject({}));
- scheme.ElementHandleOwnerFrameResult = tObject({
- frame: tOptional(tChannel(["Frame"]))
- });
- scheme.ElementHandlePressParams = tObject({
- key: tString,
- delay: tOptional(tFloat),
- timeout: tFloat,
- noWaitAfter: tOptional(tBoolean)
- });
- scheme.ElementHandlePressResult = tOptional(tObject({}));
- scheme.ElementHandleQuerySelectorParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean)
- });
- scheme.ElementHandleQuerySelectorResult = tObject({
- element: tOptional(tChannel(["ElementHandle"]))
- });
- scheme.ElementHandleQuerySelectorAllParams = tObject({
- selector: tString
- });
- scheme.ElementHandleQuerySelectorAllResult = tObject({
- elements: tArray(tChannel(["ElementHandle"]))
- });
- scheme.ElementHandleScreenshotParams = tObject({
- timeout: tFloat,
- type: tOptional(tEnum(["png", "jpeg"])),
- quality: tOptional(tInt),
- omitBackground: tOptional(tBoolean),
- caret: tOptional(tEnum(["hide", "initial"])),
- animations: tOptional(tEnum(["disabled", "allow"])),
- scale: tOptional(tEnum(["css", "device"])),
- mask: tOptional(tArray(tObject({
- frame: tChannel(["Frame"]),
- selector: tString
- }))),
- maskColor: tOptional(tString),
- style: tOptional(tString)
- });
- scheme.ElementHandleScreenshotResult = tObject({
- binary: tBinary
- });
- scheme.ElementHandleScrollIntoViewIfNeededParams = tObject({
- timeout: tFloat
- });
- scheme.ElementHandleScrollIntoViewIfNeededResult = tOptional(tObject({}));
- scheme.ElementHandleSelectOptionParams = tObject({
- elements: tOptional(tArray(tChannel(["ElementHandle"]))),
- options: tOptional(tArray(tObject({
- valueOrLabel: tOptional(tString),
- value: tOptional(tString),
- label: tOptional(tString),
- index: tOptional(tInt)
- }))),
- force: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.ElementHandleSelectOptionResult = tObject({
- values: tArray(tString)
- });
- scheme.ElementHandleSelectTextParams = tObject({
- force: tOptional(tBoolean),
- timeout: tFloat
- });
- scheme.ElementHandleSelectTextResult = tOptional(tObject({}));
- scheme.ElementHandleSetInputFilesParams = tObject({
- payloads: tOptional(tArray(tObject({
- name: tString,
- mimeType: tOptional(tString),
- buffer: tBinary
- }))),
- localDirectory: tOptional(tString),
- directoryStream: tOptional(tChannel(["WritableStream"])),
- localPaths: tOptional(tArray(tString)),
- streams: tOptional(tArray(tChannel(["WritableStream"]))),
- timeout: tFloat
- });
- scheme.ElementHandleSetInputFilesResult = tOptional(tObject({}));
- scheme.ElementHandleTapParams = tObject({
- force: tOptional(tBoolean),
- modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.ElementHandleTapResult = tOptional(tObject({}));
- scheme.ElementHandleTextContentParams = tOptional(tObject({}));
- scheme.ElementHandleTextContentResult = tObject({
- value: tOptional(tString)
- });
- scheme.ElementHandleTypeParams = tObject({
- text: tString,
- delay: tOptional(tFloat),
- timeout: tFloat
- });
- scheme.ElementHandleTypeResult = tOptional(tObject({}));
- scheme.ElementHandleUncheckParams = tObject({
- force: tOptional(tBoolean),
- position: tOptional(tType("Point")),
- timeout: tFloat,
- trial: tOptional(tBoolean)
- });
- scheme.ElementHandleUncheckResult = tOptional(tObject({}));
- scheme.ElementHandleWaitForElementStateParams = tObject({
- state: tEnum(["visible", "hidden", "stable", "enabled", "disabled", "editable"]),
- timeout: tFloat
- });
- scheme.ElementHandleWaitForElementStateResult = tOptional(tObject({}));
- scheme.ElementHandleWaitForSelectorParams = tObject({
- selector: tString,
- strict: tOptional(tBoolean),
- timeout: tFloat,
- state: tOptional(tEnum(["attached", "detached", "visible", "hidden"]))
- });
- scheme.ElementHandleWaitForSelectorResult = tObject({
- element: tOptional(tChannel(["ElementHandle"]))
- });
- scheme.LocalUtilsInitializer = tObject({
- deviceDescriptors: tArray(tObject({
- name: tString,
- descriptor: tObject({
- userAgent: tString,
- viewport: tObject({
- width: tInt,
- height: tInt
- }),
- screen: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- deviceScaleFactor: tFloat,
- isMobile: tBoolean,
- hasTouch: tBoolean,
- defaultBrowserType: tEnum(["chromium", "firefox", "webkit"])
- })
- }))
- });
- scheme.LocalUtilsZipParams = tObject({
- zipFile: tString,
- entries: tArray(tType("NameValue")),
- stacksId: tOptional(tString),
- mode: tEnum(["write", "append"]),
- includeSources: tBoolean,
- additionalSources: tOptional(tArray(tString))
- });
- scheme.LocalUtilsZipResult = tOptional(tObject({}));
- scheme.LocalUtilsHarOpenParams = tObject({
- file: tString
- });
- scheme.LocalUtilsHarOpenResult = tObject({
- harId: tOptional(tString),
- error: tOptional(tString)
- });
- scheme.LocalUtilsHarLookupParams = tObject({
- harId: tString,
- url: tString,
- method: tString,
- headers: tArray(tType("NameValue")),
- postData: tOptional(tBinary),
- isNavigationRequest: tBoolean
- });
- scheme.LocalUtilsHarLookupResult = tObject({
- action: tEnum(["error", "redirect", "fulfill", "noentry"]),
- message: tOptional(tString),
- redirectURL: tOptional(tString),
- status: tOptional(tInt),
- headers: tOptional(tArray(tType("NameValue"))),
- body: tOptional(tBinary)
- });
- scheme.LocalUtilsHarCloseParams = tObject({
- harId: tString
- });
- scheme.LocalUtilsHarCloseResult = tOptional(tObject({}));
- scheme.LocalUtilsHarUnzipParams = tObject({
- zipFile: tString,
- harFile: tString,
- resourcesDir: tOptional(tString)
- });
- scheme.LocalUtilsHarUnzipResult = tOptional(tObject({}));
- scheme.LocalUtilsConnectParams = tObject({
- endpoint: tString,
- headers: tOptional(tAny),
- exposeNetwork: tOptional(tString),
- slowMo: tOptional(tFloat),
- timeout: tFloat,
- socksProxyRedirectPortForTest: tOptional(tInt)
- });
- scheme.LocalUtilsConnectResult = tObject({
- pipe: tChannel(["JsonPipe"]),
- headers: tArray(tType("NameValue"))
- });
- scheme.LocalUtilsTracingStartedParams = tObject({
- tracesDir: tOptional(tString),
- traceName: tString,
- live: tOptional(tBoolean)
- });
- scheme.LocalUtilsTracingStartedResult = tObject({
- stacksId: tString
- });
- scheme.LocalUtilsAddStackToTracingNoReplyParams = tObject({
- callData: tType("ClientSideCallMetadata")
- });
- scheme.LocalUtilsAddStackToTracingNoReplyResult = tOptional(tObject({}));
- scheme.LocalUtilsTraceDiscardedParams = tObject({
- stacksId: tString
- });
- scheme.LocalUtilsTraceDiscardedResult = tOptional(tObject({}));
- scheme.LocalUtilsGlobToRegexParams = tObject({
- glob: tString,
- baseURL: tOptional(tString),
- webSocketUrl: tOptional(tBoolean)
- });
- scheme.LocalUtilsGlobToRegexResult = tObject({
- regex: tString
- });
- scheme.SetNetworkCookie = tObject({
- name: tString,
- value: tString,
- url: tOptional(tString),
- domain: tOptional(tString),
- path: tOptional(tString),
- expires: tOptional(tFloat),
- httpOnly: tOptional(tBoolean),
- secure: tOptional(tBoolean),
- sameSite: tOptional(tEnum(["Strict", "Lax", "None"])),
- partitionKey: tOptional(tString),
- _crHasCrossSiteAncestor: tOptional(tBoolean)
- });
- scheme.NetworkCookie = tObject({
- name: tString,
- value: tString,
- domain: tString,
- path: tString,
- expires: tFloat,
- httpOnly: tBoolean,
- secure: tBoolean,
- sameSite: tEnum(["Strict", "Lax", "None"]),
- partitionKey: tOptional(tString),
- _crHasCrossSiteAncestor: tOptional(tBoolean)
- });
- scheme.RequestInitializer = tObject({
- frame: tOptional(tChannel(["Frame"])),
- serviceWorker: tOptional(tChannel(["Worker"])),
- url: tString,
- resourceType: tString,
- method: tString,
- postData: tOptional(tBinary),
- headers: tArray(tType("NameValue")),
- isNavigationRequest: tBoolean,
- redirectedFrom: tOptional(tChannel(["Request"]))
- });
- scheme.RequestResponseParams = tOptional(tObject({}));
- scheme.RequestResponseResult = tObject({
- response: tOptional(tChannel(["Response"]))
- });
- scheme.RequestRawRequestHeadersParams = tOptional(tObject({}));
- scheme.RequestRawRequestHeadersResult = tObject({
- headers: tArray(tType("NameValue"))
- });
- scheme.RouteInitializer = tObject({
- request: tChannel(["Request"])
- });
- scheme.RouteRedirectNavigationRequestParams = tObject({
- url: tString
- });
- scheme.RouteRedirectNavigationRequestResult = tOptional(tObject({}));
- scheme.RouteAbortParams = tObject({
- errorCode: tOptional(tString)
- });
- scheme.RouteAbortResult = tOptional(tObject({}));
- scheme.RouteContinueParams = tObject({
- url: tOptional(tString),
- method: tOptional(tString),
- headers: tOptional(tArray(tType("NameValue"))),
- postData: tOptional(tBinary),
- isFallback: tBoolean
- });
- scheme.RouteContinueResult = tOptional(tObject({}));
- scheme.RouteFulfillParams = tObject({
- status: tOptional(tInt),
- headers: tOptional(tArray(tType("NameValue"))),
- body: tOptional(tString),
- isBase64: tOptional(tBoolean),
- fetchResponseUid: tOptional(tString)
- });
- scheme.RouteFulfillResult = tOptional(tObject({}));
- scheme.WebSocketRouteInitializer = tObject({
- url: tString,
- protocols: tArray(tString)
- });
- scheme.WebSocketRouteMessageFromPageEvent = tObject({
- message: tString,
- isBase64: tBoolean
- });
- scheme.WebSocketRouteMessageFromServerEvent = tObject({
- message: tString,
- isBase64: tBoolean
- });
- scheme.WebSocketRouteClosePageEvent = tObject({
- code: tOptional(tInt),
- reason: tOptional(tString),
- wasClean: tBoolean
- });
- scheme.WebSocketRouteCloseServerEvent = tObject({
- code: tOptional(tInt),
- reason: tOptional(tString),
- wasClean: tBoolean
- });
- scheme.WebSocketRouteConnectParams = tOptional(tObject({}));
- scheme.WebSocketRouteConnectResult = tOptional(tObject({}));
- scheme.WebSocketRouteEnsureOpenedParams = tOptional(tObject({}));
- scheme.WebSocketRouteEnsureOpenedResult = tOptional(tObject({}));
- scheme.WebSocketRouteSendToPageParams = tObject({
- message: tString,
- isBase64: tBoolean
- });
- scheme.WebSocketRouteSendToPageResult = tOptional(tObject({}));
- scheme.WebSocketRouteSendToServerParams = tObject({
- message: tString,
- isBase64: tBoolean
- });
- scheme.WebSocketRouteSendToServerResult = tOptional(tObject({}));
- scheme.WebSocketRouteClosePageParams = tObject({
- code: tOptional(tInt),
- reason: tOptional(tString),
- wasClean: tBoolean
- });
- scheme.WebSocketRouteClosePageResult = tOptional(tObject({}));
- scheme.WebSocketRouteCloseServerParams = tObject({
- code: tOptional(tInt),
- reason: tOptional(tString),
- wasClean: tBoolean
- });
- scheme.WebSocketRouteCloseServerResult = tOptional(tObject({}));
- scheme.ResourceTiming = tObject({
- startTime: tFloat,
- domainLookupStart: tFloat,
- domainLookupEnd: tFloat,
- connectStart: tFloat,
- secureConnectionStart: tFloat,
- connectEnd: tFloat,
- requestStart: tFloat,
- responseStart: tFloat
- });
- scheme.ResponseInitializer = tObject({
- request: tChannel(["Request"]),
- url: tString,
- status: tInt,
- statusText: tString,
- headers: tArray(tType("NameValue")),
- timing: tType("ResourceTiming"),
- fromServiceWorker: tBoolean
- });
- scheme.ResponseBodyParams = tOptional(tObject({}));
- scheme.ResponseBodyResult = tObject({
- binary: tBinary
- });
- scheme.ResponseSecurityDetailsParams = tOptional(tObject({}));
- scheme.ResponseSecurityDetailsResult = tObject({
- value: tOptional(tType("SecurityDetails"))
- });
- scheme.ResponseServerAddrParams = tOptional(tObject({}));
- scheme.ResponseServerAddrResult = tObject({
- value: tOptional(tType("RemoteAddr"))
- });
- scheme.ResponseRawResponseHeadersParams = tOptional(tObject({}));
- scheme.ResponseRawResponseHeadersResult = tObject({
- headers: tArray(tType("NameValue"))
- });
- scheme.ResponseHttpVersionParams = tOptional(tObject({}));
- scheme.ResponseHttpVersionResult = tObject({
- value: tString
- });
- scheme.ResponseSizesParams = tOptional(tObject({}));
- scheme.ResponseSizesResult = tObject({
- sizes: tType("RequestSizes")
- });
- scheme.SecurityDetails = tObject({
- issuer: tOptional(tString),
- protocol: tOptional(tString),
- subjectName: tOptional(tString),
- validFrom: tOptional(tFloat),
- validTo: tOptional(tFloat)
- });
- scheme.RequestSizes = tObject({
- requestBodySize: tInt,
- requestHeadersSize: tInt,
- responseBodySize: tInt,
- responseHeadersSize: tInt
- });
- scheme.RemoteAddr = tObject({
- ipAddress: tString,
- port: tInt
- });
- scheme.WebSocketInitializer = tObject({
- url: tString
- });
- scheme.WebSocketOpenEvent = tOptional(tObject({}));
- scheme.WebSocketFrameSentEvent = tObject({
- opcode: tInt,
- data: tString
- });
- scheme.WebSocketFrameReceivedEvent = tObject({
- opcode: tInt,
- data: tString
- });
- scheme.WebSocketSocketErrorEvent = tObject({
- error: tString
- });
- scheme.WebSocketCloseEvent = tOptional(tObject({}));
- scheme.PageInitializer = tObject({
- mainFrame: tChannel(["Frame"]),
- viewportSize: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- isClosed: tBoolean,
- opener: tOptional(tChannel(["Page"])),
- video: tOptional(tChannel(["Artifact"]))
- });
- scheme.PageBindingCallEvent = tObject({
- binding: tChannel(["BindingCall"])
- });
- scheme.PageCloseEvent = tOptional(tObject({}));
- scheme.PageCrashEvent = tOptional(tObject({}));
- scheme.PageDownloadEvent = tObject({
- url: tString,
- suggestedFilename: tString,
- artifact: tChannel(["Artifact"])
- });
- scheme.PageViewportSizeChangedEvent = tObject({
- viewportSize: tOptional(tObject({
- width: tInt,
- height: tInt
- }))
- });
- scheme.PageFileChooserEvent = tObject({
- element: tChannel(["ElementHandle"]),
- isMultiple: tBoolean
- });
- scheme.PageFrameAttachedEvent = tObject({
- frame: tChannel(["Frame"])
- });
- scheme.PageFrameDetachedEvent = tObject({
- frame: tChannel(["Frame"])
- });
- scheme.PageLocatorHandlerTriggeredEvent = tObject({
- uid: tInt
- });
- scheme.PageRouteEvent = tObject({
- route: tChannel(["Route"])
- });
- scheme.PageScreencastFrameEvent = tObject({
- data: tBinary,
- timestamp: tFloat,
- viewportWidth: tInt,
- viewportHeight: tInt
- });
- scheme.PageWebSocketRouteEvent = tObject({
- webSocketRoute: tChannel(["WebSocketRoute"])
- });
- scheme.PageWebSocketEvent = tObject({
- webSocket: tChannel(["WebSocket"])
- });
- scheme.PageWorkerEvent = tObject({
- worker: tChannel(["Worker"])
- });
- scheme.PageAddInitScriptParams = tObject({
- source: tString
- });
- scheme.PageAddInitScriptResult = tObject({
- disposable: tChannel(["Disposable"])
- });
- scheme.PageCloseParams = tObject({
- reason: tOptional(tString)
- });
- scheme.PageCloseResult = tOptional(tObject({}));
- scheme.PageRunBeforeUnloadParams = tOptional(tObject({}));
- scheme.PageRunBeforeUnloadResult = tOptional(tObject({}));
- scheme.PageClearConsoleMessagesParams = tOptional(tObject({}));
- scheme.PageClearConsoleMessagesResult = tOptional(tObject({}));
- scheme.PageConsoleMessagesParams = tObject({
- filter: tOptional(tType("ConsoleMessagesFilter"))
- });
- scheme.PageConsoleMessagesResult = tObject({
- messages: tArray(tObject({
- type: tString,
- text: tString,
- args: tArray(tChannel(["ElementHandle", "JSHandle"])),
- location: tObject({
- url: tString,
- lineNumber: tInt,
- columnNumber: tInt
- }),
- timestamp: tFloat
- }))
- });
- scheme.PageEmulateMediaParams = tObject({
- media: tOptional(tEnum(["screen", "print", "no-override"])),
- colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),
- reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),
- forcedColors: tOptional(tEnum(["active", "none", "no-override"])),
- contrast: tOptional(tEnum(["no-preference", "more", "no-override"]))
- });
- scheme.PageEmulateMediaResult = tOptional(tObject({}));
- scheme.PageExposeBindingParams = tObject({
- name: tString
- });
- scheme.PageExposeBindingResult = tObject({
- disposable: tChannel(["Disposable"])
- });
- scheme.PageGoBackParams = tObject({
- timeout: tFloat,
- waitUntil: tOptional(tType("LifecycleEvent"))
- });
- scheme.PageGoBackResult = tObject({
- response: tOptional(tChannel(["Response"]))
- });
- scheme.PageGoForwardParams = tObject({
- timeout: tFloat,
- waitUntil: tOptional(tType("LifecycleEvent"))
- });
- scheme.PageGoForwardResult = tObject({
- response: tOptional(tChannel(["Response"]))
- });
- scheme.PageRequestGCParams = tOptional(tObject({}));
- scheme.PageRequestGCResult = tOptional(tObject({}));
- scheme.PageRegisterLocatorHandlerParams = tObject({
- selector: tString,
- noWaitAfter: tOptional(tBoolean)
- });
- scheme.PageRegisterLocatorHandlerResult = tObject({
- uid: tInt
- });
- scheme.PageResolveLocatorHandlerNoReplyParams = tObject({
- uid: tInt,
- remove: tOptional(tBoolean)
- });
- scheme.PageResolveLocatorHandlerNoReplyResult = tOptional(tObject({}));
- scheme.PageUnregisterLocatorHandlerParams = tObject({
- uid: tInt
- });
- scheme.PageUnregisterLocatorHandlerResult = tOptional(tObject({}));
- scheme.PageReloadParams = tObject({
- timeout: tFloat,
- waitUntil: tOptional(tType("LifecycleEvent"))
- });
- scheme.PageReloadResult = tObject({
- response: tOptional(tChannel(["Response"]))
- });
- scheme.PageExpectScreenshotParams = tObject({
- expected: tOptional(tBinary),
- timeout: tFloat,
- isNot: tBoolean,
- locator: tOptional(tObject({
- frame: tChannel(["Frame"]),
- selector: tString
- })),
- comparator: tOptional(tString),
- maxDiffPixels: tOptional(tInt),
- maxDiffPixelRatio: tOptional(tFloat),
- threshold: tOptional(tFloat),
- fullPage: tOptional(tBoolean),
- clip: tOptional(tType("Rect")),
- omitBackground: tOptional(tBoolean),
- caret: tOptional(tEnum(["hide", "initial"])),
- animations: tOptional(tEnum(["disabled", "allow"])),
- scale: tOptional(tEnum(["css", "device"])),
- mask: tOptional(tArray(tObject({
- frame: tChannel(["Frame"]),
- selector: tString
- }))),
- maskColor: tOptional(tString),
- style: tOptional(tString)
- });
- scheme.PageExpectScreenshotResult = tObject({
- actual: tOptional(tBinary)
- });
- scheme.PageExpectScreenshotErrorDetails = tObject({
- diff: tOptional(tBinary),
- customErrorMessage: tOptional(tString),
- actual: tOptional(tBinary),
- previous: tOptional(tBinary),
- timedOut: tOptional(tBoolean),
- log: tOptional(tArray(tString))
- });
- scheme.PageScreenshotParams = tObject({
- timeout: tFloat,
- type: tOptional(tEnum(["png", "jpeg"])),
- quality: tOptional(tInt),
- fullPage: tOptional(tBoolean),
- clip: tOptional(tType("Rect")),
- omitBackground: tOptional(tBoolean),
- caret: tOptional(tEnum(["hide", "initial"])),
- animations: tOptional(tEnum(["disabled", "allow"])),
- scale: tOptional(tEnum(["css", "device"])),
- mask: tOptional(tArray(tObject({
- frame: tChannel(["Frame"]),
- selector: tString
- }))),
- maskColor: tOptional(tString),
- style: tOptional(tString)
- });
- scheme.PageScreenshotResult = tObject({
- binary: tBinary
- });
- scheme.PageSetExtraHTTPHeadersParams = tObject({
- headers: tArray(tType("NameValue"))
- });
- scheme.PageSetExtraHTTPHeadersResult = tOptional(tObject({}));
- scheme.PageSetNetworkInterceptionPatternsParams = tObject({
- patterns: tArray(tObject({
- glob: tOptional(tString),
- regexSource: tOptional(tString),
- regexFlags: tOptional(tString),
- urlPattern: tOptional(tType("URLPattern"))
- }))
- });
- scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({}));
- scheme.PageSetWebSocketInterceptionPatternsParams = tObject({
- patterns: tArray(tObject({
- glob: tOptional(tString),
- regexSource: tOptional(tString),
- regexFlags: tOptional(tString),
- urlPattern: tOptional(tType("URLPattern"))
- }))
- });
- scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({}));
- scheme.PageSetViewportSizeParams = tObject({
- viewportSize: tObject({
- width: tInt,
- height: tInt
- })
- });
- scheme.PageSetViewportSizeResult = tOptional(tObject({}));
- scheme.PageKeyboardDownParams = tObject({
- key: tString
- });
- scheme.PageKeyboardDownResult = tOptional(tObject({}));
- scheme.PageKeyboardUpParams = tObject({
- key: tString
- });
- scheme.PageKeyboardUpResult = tOptional(tObject({}));
- scheme.PageKeyboardInsertTextParams = tObject({
- text: tString
- });
- scheme.PageKeyboardInsertTextResult = tOptional(tObject({}));
- scheme.PageKeyboardTypeParams = tObject({
- text: tString,
- delay: tOptional(tFloat)
- });
- scheme.PageKeyboardTypeResult = tOptional(tObject({}));
- scheme.PageKeyboardPressParams = tObject({
- key: tString,
- delay: tOptional(tFloat)
- });
- scheme.PageKeyboardPressResult = tOptional(tObject({}));
- scheme.PageMouseMoveParams = tObject({
- x: tFloat,
- y: tFloat,
- steps: tOptional(tInt)
- });
- scheme.PageMouseMoveResult = tOptional(tObject({}));
- scheme.PageMouseDownParams = tObject({
- button: tOptional(tEnum(["left", "right", "middle"])),
- clickCount: tOptional(tInt)
- });
- scheme.PageMouseDownResult = tOptional(tObject({}));
- scheme.PageMouseUpParams = tObject({
- button: tOptional(tEnum(["left", "right", "middle"])),
- clickCount: tOptional(tInt)
- });
- scheme.PageMouseUpResult = tOptional(tObject({}));
- scheme.PageMouseClickParams = tObject({
- x: tFloat,
- y: tFloat,
- delay: tOptional(tFloat),
- button: tOptional(tEnum(["left", "right", "middle"])),
- clickCount: tOptional(tInt)
- });
- scheme.PageMouseClickResult = tOptional(tObject({}));
- scheme.PageMouseWheelParams = tObject({
- deltaX: tFloat,
- deltaY: tFloat
- });
- scheme.PageMouseWheelResult = tOptional(tObject({}));
- scheme.PageTouchscreenTapParams = tObject({
- x: tFloat,
- y: tFloat
- });
- scheme.PageTouchscreenTapResult = tOptional(tObject({}));
- scheme.PageClearPageErrorsParams = tOptional(tObject({}));
- scheme.PageClearPageErrorsResult = tOptional(tObject({}));
- scheme.PagePageErrorsParams = tObject({
- filter: tOptional(tType("ConsoleMessagesFilter"))
- });
- scheme.PagePageErrorsResult = tObject({
- errors: tArray(tType("SerializedError"))
- });
- scheme.PagePdfParams = tObject({
- scale: tOptional(tFloat),
- displayHeaderFooter: tOptional(tBoolean),
- headerTemplate: tOptional(tString),
- footerTemplate: tOptional(tString),
- printBackground: tOptional(tBoolean),
- landscape: tOptional(tBoolean),
- pageRanges: tOptional(tString),
- format: tOptional(tString),
- width: tOptional(tString),
- height: tOptional(tString),
- preferCSSPageSize: tOptional(tBoolean),
- margin: tOptional(tObject({
- top: tOptional(tString),
- bottom: tOptional(tString),
- left: tOptional(tString),
- right: tOptional(tString)
- })),
- tagged: tOptional(tBoolean),
- outline: tOptional(tBoolean)
- });
- scheme.PagePdfResult = tObject({
- pdf: tBinary
- });
- scheme.PageRequestsParams = tOptional(tObject({}));
- scheme.PageRequestsResult = tObject({
- requests: tArray(tChannel(["Request"]))
- });
- scheme.PageStartJSCoverageParams = tObject({
- resetOnNavigation: tOptional(tBoolean),
- reportAnonymousScripts: tOptional(tBoolean)
- });
- scheme.PageStartJSCoverageResult = tOptional(tObject({}));
- scheme.PageStopJSCoverageParams = tOptional(tObject({}));
- scheme.PageStopJSCoverageResult = tObject({
- entries: tArray(tObject({
- url: tString,
- scriptId: tString,
- source: tOptional(tString),
- functions: tArray(tObject({
- functionName: tString,
- isBlockCoverage: tBoolean,
- ranges: tArray(tObject({
- startOffset: tInt,
- endOffset: tInt,
- count: tInt
- }))
- }))
- }))
- });
- scheme.PageStartCSSCoverageParams = tObject({
- resetOnNavigation: tOptional(tBoolean)
- });
- scheme.PageStartCSSCoverageResult = tOptional(tObject({}));
- scheme.PageStopCSSCoverageParams = tOptional(tObject({}));
- scheme.PageStopCSSCoverageResult = tObject({
- entries: tArray(tObject({
- url: tString,
- text: tOptional(tString),
- ranges: tArray(tObject({
- start: tInt,
- end: tInt
- }))
- }))
- });
- scheme.PageBringToFrontParams = tOptional(tObject({}));
- scheme.PageBringToFrontResult = tOptional(tObject({}));
- scheme.PagePickLocatorParams = tOptional(tObject({}));
- scheme.PagePickLocatorResult = tObject({
- selector: tString
- });
- scheme.PageCancelPickLocatorParams = tOptional(tObject({}));
- scheme.PageCancelPickLocatorResult = tOptional(tObject({}));
- scheme.PageHideHighlightParams = tOptional(tObject({}));
- scheme.PageHideHighlightResult = tOptional(tObject({}));
- scheme.PageScreencastShowOverlayParams = tObject({
- html: tString,
- duration: tOptional(tFloat)
- });
- scheme.PageScreencastShowOverlayResult = tObject({
- id: tString
- });
- scheme.PageScreencastRemoveOverlayParams = tObject({
- id: tString
- });
- scheme.PageScreencastRemoveOverlayResult = tOptional(tObject({}));
- scheme.PageScreencastChapterParams = tObject({
- title: tString,
- description: tOptional(tString),
- duration: tOptional(tFloat)
- });
- scheme.PageScreencastChapterResult = tOptional(tObject({}));
- scheme.PageScreencastSetOverlayVisibleParams = tObject({
- visible: tBoolean
- });
- scheme.PageScreencastSetOverlayVisibleResult = tOptional(tObject({}));
- scheme.PageScreencastShowActionsParams = tObject({
- duration: tOptional(tFloat),
- position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])),
- fontSize: tOptional(tInt),
- cursor: tOptional(tEnum(["none", "pointer"]))
- });
- scheme.PageScreencastShowActionsResult = tOptional(tObject({}));
- scheme.PageScreencastHideActionsParams = tOptional(tObject({}));
- scheme.PageScreencastHideActionsResult = tOptional(tObject({}));
- scheme.PageScreencastStartParams = tObject({
- size: tOptional(tObject({
- width: tInt,
- height: tInt
- })),
- quality: tOptional(tInt),
- sendFrames: tOptional(tBoolean),
- record: tOptional(tBoolean)
- });
- scheme.PageScreencastStartResult = tObject({
- artifact: tOptional(tChannel(["Artifact"]))
- });
- scheme.PageScreencastStopParams = tOptional(tObject({}));
- scheme.PageScreencastStopResult = tOptional(tObject({}));
- scheme.PageUpdateSubscriptionParams = tObject({
- event: tEnum(["console", "dialog", "fileChooser", "request", "response", "requestFinished", "requestFailed"]),
- enabled: tBoolean
- });
- scheme.PageUpdateSubscriptionResult = tOptional(tObject({}));
- scheme.PageSetDockTileParams = tObject({
- image: tBinary
- });
- scheme.PageSetDockTileResult = tOptional(tObject({}));
- scheme.PageWebStorageItemsParams = tObject({
- kind: tEnum(["local", "session"])
- });
- scheme.PageWebStorageItemsResult = tObject({
- items: tArray(tType("NameValue"))
- });
- scheme.PageWebStorageGetItemParams = tObject({
- kind: tEnum(["local", "session"]),
- name: tString
- });
- scheme.PageWebStorageGetItemResult = tObject({
- value: tOptional(tString)
- });
- scheme.PageWebStorageSetItemParams = tObject({
- kind: tEnum(["local", "session"]),
- name: tString,
- value: tString
- });
- scheme.PageWebStorageSetItemResult = tOptional(tObject({}));
- scheme.PageWebStorageRemoveItemParams = tObject({
- kind: tEnum(["local", "session"]),
- name: tString
- });
- scheme.PageWebStorageRemoveItemResult = tOptional(tObject({}));
- scheme.PageWebStorageClearParams = tObject({
- kind: tEnum(["local", "session"])
- });
- scheme.PageWebStorageClearResult = tOptional(tObject({}));
- scheme.RootInitializer = tOptional(tObject({}));
- scheme.RootInitializeParams = tObject({
- sdkLanguage: tType("SDKLanguage")
- });
- scheme.RootInitializeResult = tObject({
- playwright: tChannel(["Playwright"])
- });
- scheme.PlaywrightInitializer = tObject({
- chromium: tChannel(["BrowserType"]),
- firefox: tChannel(["BrowserType"]),
- webkit: tChannel(["BrowserType"]),
- android: tChannel(["Android"]),
- electron: tChannel(["Electron"]),
- utils: tOptional(tChannel(["LocalUtils"])),
- preLaunchedBrowser: tOptional(tChannel(["Browser"])),
- preConnectedAndroidDevice: tOptional(tChannel(["AndroidDevice"])),
- socksSupport: tOptional(tChannel(["SocksSupport"]))
- });
- scheme.PlaywrightNewRequestParams = tObject({
- baseURL: tOptional(tString),
- userAgent: tOptional(tString),
- ignoreHTTPSErrors: tOptional(tBoolean),
- extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),
- failOnStatusCode: tOptional(tBoolean),
- clientCertificates: tOptional(tArray(tObject({
- origin: tString,
- cert: tOptional(tBinary),
- key: tOptional(tBinary),
- passphrase: tOptional(tString),
- pfx: tOptional(tBinary)
- }))),
- maxRedirects: tOptional(tInt),
- httpCredentials: tOptional(tObject({
- username: tString,
- password: tString,
- origin: tOptional(tString),
- send: tOptional(tEnum(["always", "unauthorized"]))
- })),
- proxy: tOptional(tObject({
- server: tString,
- bypass: tOptional(tString),
- username: tOptional(tString),
- password: tOptional(tString)
- })),
- storageState: tOptional(tObject({
- cookies: tOptional(tArray(tType("NetworkCookie"))),
- origins: tOptional(tArray(tType("SetOriginStorage")))
- })),
- tracesDir: tOptional(tString)
- });
- scheme.PlaywrightNewRequestResult = tObject({
- request: tChannel(["APIRequestContext"])
- });
- scheme.DebugControllerInitializer = tOptional(tObject({}));
- scheme.DebugControllerInspectRequestedEvent = tObject({
- selector: tString,
- locator: tString,
- ariaSnapshot: tString
- });
- scheme.DebugControllerSetModeRequestedEvent = tObject({
- mode: tString
- });
- scheme.DebugControllerStateChangedEvent = tObject({
- pageCount: tInt
- });
- scheme.DebugControllerSourceChangedEvent = tObject({
- text: tString,
- header: tOptional(tString),
- footer: tOptional(tString),
- actions: tOptional(tArray(tString))
- });
- scheme.DebugControllerPausedEvent = tObject({
- paused: tBoolean
- });
- scheme.DebugControllerInitializeParams = tObject({
- codegenId: tString,
- sdkLanguage: tType("SDKLanguage")
- });
- scheme.DebugControllerInitializeResult = tOptional(tObject({}));
- scheme.DebugControllerSetReportStateChangedParams = tObject({
- enabled: tBoolean
- });
- scheme.DebugControllerSetReportStateChangedResult = tOptional(tObject({}));
- scheme.DebugControllerSetRecorderModeParams = tObject({
- mode: tEnum(["inspecting", "recording", "none"]),
- testIdAttributeName: tOptional(tString),
- generateAutoExpect: tOptional(tBoolean)
- });
- scheme.DebugControllerSetRecorderModeResult = tOptional(tObject({}));
- scheme.DebugControllerHighlightParams = tObject({
- selector: tOptional(tString),
- ariaTemplate: tOptional(tString)
- });
- scheme.DebugControllerHighlightResult = tOptional(tObject({}));
- scheme.DebugControllerHideHighlightParams = tOptional(tObject({}));
- scheme.DebugControllerHideHighlightResult = tOptional(tObject({}));
- scheme.DebugControllerResumeParams = tOptional(tObject({}));
- scheme.DebugControllerResumeResult = tOptional(tObject({}));
- scheme.DebugControllerKillParams = tOptional(tObject({}));
- scheme.DebugControllerKillResult = tOptional(tObject({}));
- scheme.SocksSupportInitializer = tOptional(tObject({}));
- scheme.SocksSupportSocksRequestedEvent = tObject({
- uid: tString,
- host: tString,
- port: tInt
- });
- scheme.SocksSupportSocksDataEvent = tObject({
- uid: tString,
- data: tBinary
- });
- scheme.SocksSupportSocksClosedEvent = tObject({
- uid: tString
- });
- scheme.SocksSupportSocksConnectedParams = tObject({
- uid: tString,
- host: tString,
- port: tInt
- });
- scheme.SocksSupportSocksConnectedResult = tOptional(tObject({}));
- scheme.SocksSupportSocksFailedParams = tObject({
- uid: tString,
- errorCode: tString
- });
- scheme.SocksSupportSocksFailedResult = tOptional(tObject({}));
- scheme.SocksSupportSocksDataParams = tObject({
- uid: tString,
- data: tBinary
- });
- scheme.SocksSupportSocksDataResult = tOptional(tObject({}));
- scheme.SocksSupportSocksErrorParams = tObject({
- uid: tString,
- error: tString
- });
- scheme.SocksSupportSocksErrorResult = tOptional(tObject({}));
- scheme.SocksSupportSocksEndParams = tObject({
- uid: tString
- });
- scheme.SocksSupportSocksEndResult = tOptional(tObject({}));
- scheme.JsonPipeInitializer = tOptional(tObject({}));
- scheme.JsonPipeMessageEvent = tObject({
- message: tAny
- });
- scheme.JsonPipeClosedEvent = tObject({
- reason: tOptional(tString)
- });
- scheme.JsonPipeSendParams = tObject({
- message: tAny
- });
- scheme.JsonPipeSendResult = tOptional(tObject({}));
- scheme.JsonPipeCloseParams = tOptional(tObject({}));
- scheme.JsonPipeCloseResult = tOptional(tObject({}));
- scheme.ExpectedTextValue = tObject({
- string: tOptional(tString),
- regexSource: tOptional(tString),
- regexFlags: tOptional(tString),
- matchSubstring: tOptional(tBoolean),
- ignoreCase: tOptional(tBoolean),
- normalizeWhiteSpace: tOptional(tBoolean)
- });
- scheme.SelectorEngine = tObject({
- name: tString,
- source: tString,
- contentScript: tOptional(tBoolean)
- });
- scheme.FormField = tObject({
- name: tString,
- value: tOptional(tString),
- file: tOptional(tObject({
- name: tString,
- mimeType: tOptional(tString),
- buffer: tBinary
- }))
- });
- scheme.LifecycleEvent = tEnum(["load", "domcontentloaded", "networkidle", "commit"]);
- scheme.ConsoleMessagesFilter = tEnum(["all", "since-navigation"]);
- scheme.RecorderSource = tObject({
- isRecorded: tBoolean,
- id: tString,
- label: tString,
- text: tString,
- language: tString,
- highlight: tArray(tObject({
- line: tInt,
- type: tString
- })),
- revealLine: tOptional(tInt),
- group: tOptional(tString)
- });
- scheme.IndexedDBDatabase = tObject({
- name: tString,
- version: tInt,
- stores: tArray(tObject({
- name: tString,
- autoIncrement: tBoolean,
- keyPath: tOptional(tString),
- keyPathArray: tOptional(tArray(tString)),
- records: tArray(tObject({
- key: tOptional(tAny),
- keyEncoded: tOptional(tAny),
- value: tOptional(tAny),
- valueEncoded: tOptional(tAny)
- })),
- indexes: tArray(tObject({
- name: tString,
- keyPath: tOptional(tString),
- keyPathArray: tOptional(tArray(tString)),
- multiEntry: tBoolean,
- unique: tBoolean
- }))
- }))
- });
- scheme.SetOriginStorage = tObject({
- origin: tString,
- localStorage: tArray(tType("NameValue")),
- indexedDB: tOptional(tArray(tType("IndexedDBDatabase")))
- });
- scheme.OriginStorage = tObject({
- origin: tString,
- localStorage: tArray(tType("NameValue")),
- indexedDB: tOptional(tArray(tType("IndexedDBDatabase")))
- });
- scheme.RecordHarOptions = tObject({
- content: tOptional(tEnum(["embed", "attach", "omit"])),
- mode: tOptional(tEnum(["full", "minimal"])),
- urlGlob: tOptional(tString),
- urlRegexSource: tOptional(tString),
- urlRegexFlags: tOptional(tString),
- harPath: tOptional(tString),
- resourcesDir: tOptional(tString)
- });
- scheme.CDPSessionInitializer = tOptional(tObject({}));
- scheme.CDPSessionEventEvent = tObject({
- method: tString,
- params: tOptional(tAny)
- });
- scheme.CDPSessionCloseEvent = tOptional(tObject({}));
- scheme.CDPSessionSendParams = tObject({
- method: tString,
- params: tOptional(tAny)
- });
- scheme.CDPSessionSendResult = tObject({
- result: tAny
- });
- scheme.CDPSessionDetachParams = tOptional(tObject({}));
- scheme.CDPSessionDetachResult = tOptional(tObject({}));
- scheme.BindingCallInitializer = tObject({
- frame: tChannel(["Frame"]),
- name: tString,
- args: tArray(tType("SerializedValue"))
- });
- scheme.BindingCallRejectParams = tObject({
- error: tType("SerializedError")
- });
- scheme.BindingCallRejectResult = tOptional(tObject({}));
- scheme.BindingCallResolveParams = tObject({
- result: tType("SerializedArgument")
- });
- scheme.BindingCallResolveResult = tOptional(tObject({}));
- scheme.DebuggerInitializer = tOptional(tObject({}));
- scheme.DebuggerPausedStateChangedEvent = tObject({
- pausedDetails: tOptional(tObject({
- location: tObject({
- file: tString,
- line: tOptional(tInt),
- column: tOptional(tInt)
- }),
- title: tString,
- stack: tOptional(tString)
- }))
- });
- scheme.DebuggerRequestPauseParams = tOptional(tObject({}));
- scheme.DebuggerRequestPauseResult = tOptional(tObject({}));
- scheme.DebuggerResumeParams = tOptional(tObject({}));
- scheme.DebuggerResumeResult = tOptional(tObject({}));
- scheme.DebuggerNextParams = tOptional(tObject({}));
- scheme.DebuggerNextResult = tOptional(tObject({}));
- scheme.DebuggerRunToParams = tObject({
- location: tObject({
- file: tString,
- line: tOptional(tInt),
- column: tOptional(tInt)
- })
- });
- scheme.DebuggerRunToResult = tOptional(tObject({}));
- scheme.DialogInitializer = tObject({
- page: tOptional(tChannel(["Page"])),
- type: tString,
- message: tString,
- defaultValue: tString
- });
- scheme.DialogAcceptParams = tObject({
- promptText: tOptional(tString)
- });
- scheme.DialogAcceptResult = tOptional(tObject({}));
- scheme.DialogDismissParams = tOptional(tObject({}));
- scheme.DialogDismissResult = tOptional(tObject({}));
- scheme.SerializedValue = tObject({
- n: tOptional(tFloat),
- b: tOptional(tBoolean),
- s: tOptional(tString),
- v: tOptional(tEnum(["null", "undefined", "NaN", "Infinity", "-Infinity", "-0"])),
- d: tOptional(tString),
- u: tOptional(tString),
- bi: tOptional(tString),
- ta: tOptional(tObject({
- b: tBinary,
- k: tEnum(["i8", "ui8", "ui8c", "i16", "ui16", "i32", "ui32", "f32", "f64", "bi64", "bui64"])
- })),
- e: tOptional(tObject({
- m: tString,
- n: tString,
- s: tString
- })),
- r: tOptional(tObject({
- p: tString,
- f: tString
- })),
- a: tOptional(tArray(tType("SerializedValue"))),
- o: tOptional(tArray(tObject({
- k: tString,
- v: tType("SerializedValue")
- }))),
- h: tOptional(tInt),
- id: tOptional(tInt),
- ref: tOptional(tInt)
- });
- scheme.SerializedArgument = tObject({
- value: tType("SerializedValue"),
- handles: tArray(tChannel("*"))
- });
- scheme.SerializedError = tObject({
- error: tOptional(tObject({
- message: tString,
- name: tString,
- stack: tOptional(tString)
- })),
- value: tOptional(tType("SerializedValue"))
- });
- scheme.StackFrame = tObject({
- file: tString,
- line: tInt,
- column: tInt,
- function: tOptional(tString)
- });
- scheme.VirtualCredential = tObject({
- id: tString,
- rpId: tString,
- userHandle: tString,
- privateKey: tString,
- publicKey: tString
- });
- scheme.Point = tObject({
- x: tFloat,
- y: tFloat
- });
- scheme.Rect = tObject({
- x: tFloat,
- y: tFloat,
- width: tFloat,
- height: tFloat
- });
- scheme.URLPattern = tObject({
- hash: tString,
- hostname: tString,
- password: tString,
- pathname: tString,
- port: tString,
- protocol: tString,
- search: tString,
- username: tString
- });
- scheme.NameValue = tObject({
- name: tString,
- value: tString
- });
- scheme.TracingInitializer = tOptional(tObject({}));
- scheme.TracingTracingStartParams = tObject({
- name: tOptional(tString),
- snapshots: tOptional(tBoolean),
- screenshots: tOptional(tBoolean),
- live: tOptional(tBoolean)
- });
- scheme.TracingTracingStartResult = tOptional(tObject({}));
- scheme.TracingTracingStartChunkParams = tObject({
- name: tOptional(tString),
- title: tOptional(tString)
- });
- scheme.TracingTracingStartChunkResult = tObject({
- traceName: tString
- });
- scheme.TracingTracingGroupParams = tObject({
- name: tString,
- location: tOptional(tObject({
- file: tString,
- line: tOptional(tInt),
- column: tOptional(tInt)
- }))
- });
- scheme.TracingTracingGroupResult = tOptional(tObject({}));
- scheme.TracingTracingGroupEndParams = tOptional(tObject({}));
- scheme.TracingTracingGroupEndResult = tOptional(tObject({}));
- scheme.TracingTracingStopChunkParams = tObject({
- mode: tEnum(["archive", "discard", "entries"])
- });
- scheme.TracingTracingStopChunkResult = tObject({
- artifact: tOptional(tChannel(["Artifact"])),
- entries: tOptional(tArray(tType("NameValue")))
- });
- scheme.TracingTracingStopParams = tOptional(tObject({}));
- scheme.TracingTracingStopResult = tOptional(tObject({}));
- scheme.TracingHarStartParams = tObject({
- page: tOptional(tChannel(["Page"])),
- options: tType("RecordHarOptions")
- });
- scheme.TracingHarStartResult = tObject({
- harId: tString
- });
- scheme.TracingHarExportParams = tObject({
- harId: tOptional(tString),
- mode: tEnum(["archive", "entries"])
- });
- scheme.TracingHarExportResult = tObject({
- artifact: tOptional(tChannel(["Artifact"])),
- entries: tOptional(tArray(tType("NameValue")))
- });
- scheme.WorkerInitializer = tObject({
- url: tString
- });
- scheme.WorkerConsoleEvent = tObject({
- type: tString,
- text: tString,
- args: tArray(tChannel(["ElementHandle", "JSHandle"])),
- location: tObject({
- url: tString,
- lineNumber: tInt,
- columnNumber: tInt
- }),
- timestamp: tFloat
- });
- scheme.WorkerCloseEvent = tOptional(tObject({}));
- scheme.WorkerDisconnectParams = tObject({
- reason: tOptional(tString)
- });
- scheme.WorkerDisconnectResult = tOptional(tObject({}));
- scheme.WorkerEvaluateExpressionParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.WorkerEvaluateExpressionResult = tObject({
- value: tType("SerializedValue")
- });
- scheme.WorkerEvaluateExpressionHandleParams = tObject({
- expression: tString,
- isFunction: tOptional(tBoolean),
- arg: tType("SerializedArgument")
- });
- scheme.WorkerEvaluateExpressionHandleResult = tObject({
- handle: tChannel(["ElementHandle", "JSHandle"])
- });
- scheme.WorkerUpdateSubscriptionParams = tObject({
- event: tEnum(["console"]),
- enabled: tBoolean
- });
- scheme.WorkerUpdateSubscriptionResult = tOptional(tObject({}));
- }
-});
-
-// packages/playwright-core/src/server/protocolError.ts
-function isProtocolError(e) {
- return e instanceof ProtocolError;
-}
-function isSessionClosedError(e) {
- return e instanceof ProtocolError && (e.type === "closed" || e.type === "crashed");
-}
-var ProtocolError;
-var init_protocolError = __esm({
- "packages/playwright-core/src/server/protocolError.ts"() {
- "use strict";
- init_stackTrace();
- ProtocolError = class extends Error {
- constructor(type3, method, logs) {
- super();
- this.type = type3;
- this.method = method;
- this.logs = logs;
- }
- setMessage(message) {
- rewriteErrorMessage(this, `Protocol error (${this.method}): ${message}`);
- }
- browserLogMessage() {
- return this.logs ? "\nBrowser logs:\n" + this.logs : "";
- }
- };
- }
-});
-
-// packages/playwright-core/src/server/callLog.ts
-function compressCallLog(log2) {
- const lines = [];
- for (const block of findRepeatedSubsequences(log2)) {
- for (let i = 0; i < block.sequence.length; i++) {
- const line = block.sequence[i];
- const leadingWhitespace = line.match(/^\s*/);
- const whitespacePrefix = " " + leadingWhitespace?.[0] || "";
- const countPrefix = `${block.count} \xD7 `;
- if (block.count > 1 && i === 0)
- lines.push(whitespacePrefix + countPrefix + line.trim());
- else if (block.count > 1)
- lines.push(whitespacePrefix + " ".repeat(countPrefix.length - 2) + "- " + line.trim());
- else
- lines.push(whitespacePrefix + "- " + line.trim());
- }
- }
- return lines;
-}
-function findRepeatedSubsequences(s) {
- const n = s.length;
- const result2 = [];
- let i = 0;
- const arraysEqual = (a1, a2) => {
- if (a1.length !== a2.length)
- return false;
- for (let j = 0; j < a1.length; j++) {
- if (a1[j] !== a2[j])
- return false;
- }
- return true;
- };
- while (i < n) {
- let maxRepeatCount = 1;
- let maxRepeatSubstr = [s[i]];
- let maxRepeatLength = 1;
- for (let p = 1; p <= n - i; p++) {
- const substr = s.slice(i, i + p);
- let k = 1;
- while (i + p * k <= n && arraysEqual(s.slice(i + p * (k - 1), i + p * k), substr))
- k += 1;
- k -= 1;
- if (k > 1 && k * p > maxRepeatCount * maxRepeatLength) {
- maxRepeatCount = k;
- maxRepeatSubstr = substr;
- maxRepeatLength = p;
- }
- }
- result2.push({ sequence: maxRepeatSubstr, count: maxRepeatCount });
- i += maxRepeatLength * maxRepeatCount;
- }
- return result2;
-}
-var findRepeatedSubsequencesForTest;
-var init_callLog = __esm({
- "packages/playwright-core/src/server/callLog.ts"() {
- "use strict";
- findRepeatedSubsequencesForTest = findRepeatedSubsequences;
- }
-});
-
-// packages/playwright-core/src/server/dispatchers/dispatcher.ts
-function setMaxDispatchersForTest(value2) {
- maxDispatchersOverride = value2;
-}
-function maxDispatchersForBucket(gcBucket) {
- return maxDispatchersOverride ?? {
- "JSHandle": 1e5,
- "ElementHandle": 1e5
- }[gcBucket] ?? 1e4;
-}
-var import_events5, metadataValidator, waitInfoValidator, maxDispatchersOverride, Dispatcher, RootDispatcher, DispatcherConnection;
-var init_dispatcher = __esm({
- "packages/playwright-core/src/server/dispatchers/dispatcher.ts"() {
- "use strict";
- import_events5 = require("events");
- init_protocolMetainfo();
- init_eventsHelper();
- init_debug();
- init_assert();
- init_time();
- init_stackTrace();
- init_validator();
- init_errors();
- init_instrumentation();
- init_protocolError();
- init_callLog();
- init_progress();
- metadataValidator = createMetadataValidator();
- waitInfoValidator = createWaitInfoValidator();
- Dispatcher = class extends import_events5.EventEmitter {
- constructor(parent, object, type3, initializer, gcBucket) {
- super();
- this._dispatchers = /* @__PURE__ */ new Map();
- this._disposed = false;
- this._eventListeners = [];
- this._activeProgressControllers = /* @__PURE__ */ new Set();
- this.connection = parent instanceof DispatcherConnection ? parent : parent.connection;
- this._parent = parent instanceof DispatcherConnection ? void 0 : parent;
- const guid = object.guid;
- this._guid = guid;
- this._type = type3;
- this._object = object;
- this._gcBucket = gcBucket ?? type3;
- this.connection.registerDispatcher(this);
- if (this._parent) {
- assert(!this._parent._dispatchers.has(guid));
- this._parent._dispatchers.set(guid, this);
- }
- if (this._parent)
- this.connection.sendCreate(this._parent, type3, guid, initializer);
- this.connection.maybeDisposeStaleDispatchers(this._gcBucket);
- }
- parentScope() {
- return this._parent;
- }
- addObjectListener(eventName, handler) {
- this._eventListeners.push(eventsHelper.addEventListener(this._object, eventName, handler));
- }
- adopt(child) {
- if (child._parent === this)
- return;
- const oldParent = child._parent;
- oldParent._dispatchers.delete(child._guid);
- this._dispatchers.set(child._guid, child);
- child._parent = this;
- this.connection.sendAdopt(this, child);
- }
- async _runCommand(callMetadata, method, validParams) {
- const controller = ProgressController.createForSdkObject(this._object, callMetadata);
- this._activeProgressControllers.add(controller);
- try {
- return await controller.run((progress2) => this[method](validParams, progress2), validParams?.timeout);
- } finally {
- this._activeProgressControllers.delete(controller);
- }
- }
- _dispatchEvent(method, params2) {
- if (this._disposed) {
- if (isUnderTest())
- throw new Error(`${this._guid} is sending "${String(method)}" event after being disposed`);
- return;
- }
- this.connection.sendEvent(this, method, params2);
- }
- _dispose(reason) {
- this._disposeRecursively(new TargetClosedError(this._object.closeReason()));
- this.connection.sendDispose(this, reason);
- }
- _onDispose() {
- }
- async stopPendingOperations(error) {
- const controllers = [];
- const collect = (dispatcher) => {
- controllers.push(...dispatcher._activeProgressControllers);
- for (const child of [...dispatcher._dispatchers.values()])
- collect(child);
- };
- collect(this);
- await Promise.all(controllers.map((controller) => controller.abort(error)));
- }
- _disposeRecursively(error) {
- assert(!this._disposed, `${this._guid} is disposed more than once`);
- this._onDispose();
- this._disposed = true;
- eventsHelper.removeEventListeners(this._eventListeners);
- this._parent?._dispatchers.delete(this._guid);
- const list = this.connection._dispatchersByBucket.get(this._gcBucket);
- list?.delete(this._guid);
- this.connection._dispatcherByGuid.delete(this._guid);
- this.connection._dispatcherByObject.delete(this._object);
- for (const dispatcher of [...this._dispatchers.values()])
- dispatcher._disposeRecursively(error);
- this._dispatchers.clear();
- }
- _debugScopeState() {
- return {
- _guid: this._guid,
- objects: Array.from(this._dispatchers.values()).map((o) => o._debugScopeState())
- };
- }
- };
- RootDispatcher = class extends Dispatcher {
- constructor(connection, createPlaywright2) {
- super(connection, createRootSdkObject(), "Root", {});
- this.createPlaywright = createPlaywright2;
- this._initialized = false;
- }
- async initialize(params2, progress2) {
- assert(this.createPlaywright);
- assert(!this._initialized);
- this._initialized = true;
- return {
- playwright: await progress2.race(this.createPlaywright(this, params2))
- };
- }
- };
- DispatcherConnection = class {
- constructor(isInProcess) {
- this._dispatcherByGuid = /* @__PURE__ */ new Map();
- this._dispatcherByObject = /* @__PURE__ */ new Map();
- this._dispatchersByBucket = /* @__PURE__ */ new Map();
- this.onmessage = (message) => {
- };
- this._waitOperations = /* @__PURE__ */ new Map();
- this._isInProcess = !!isInProcess;
- }
- sendEvent(dispatcher, event, params2) {
- const validator = findValidator(dispatcher._type, event, "Event");
- params2 = validator(params2, "", this._validatorToWireContext());
- this.onmessage({ guid: dispatcher._guid, method: event, params: params2 });
- }
- sendCreate(parent, type3, guid, initializer) {
- const validator = findValidator(type3, "", "Initializer");
- initializer = validator(initializer, "", this._validatorToWireContext());
- this.onmessage({ guid: parent._guid, method: "__create__", params: { type: type3, initializer, guid } });
- }
- sendAdopt(parent, dispatcher) {
- this.onmessage({ guid: parent._guid, method: "__adopt__", params: { guid: dispatcher._guid } });
- }
- sendDispose(dispatcher, reason) {
- this.onmessage({ guid: dispatcher._guid, method: "__dispose__", params: { reason } });
- }
- _validatorToWireContext() {
- return {
- tChannelImpl: this._tChannelImplToWire.bind(this),
- binary: this._isInProcess ? "buffer" : "toBase64",
- isUnderTest
- };
- }
- _validatorFromWireContext() {
- return {
- tChannelImpl: this._tChannelImplFromWire.bind(this),
- binary: this._isInProcess ? "buffer" : "fromBase64",
- isUnderTest
- };
- }
- _tChannelImplFromWire(names, arg, path59, context2) {
- if (arg && typeof arg === "object" && typeof arg.guid === "string") {
- const guid = arg.guid;
- const dispatcher = this._dispatcherByGuid.get(guid);
- if (!dispatcher)
- throw new ValidationError(`${path59}: no object with guid ${guid}`);
- if (names !== "*" && !names.includes(dispatcher._type))
- throw new ValidationError(`${path59}: object with guid ${guid} has type ${dispatcher._type}, expected ${names.toString()}`);
- return dispatcher;
- }
- throw new ValidationError(`${path59}: expected guid for ${names.toString()}`);
- }
- _tChannelImplToWire(names, arg, path59, context2) {
- if (arg instanceof Dispatcher) {
- if (names !== "*" && !names.includes(arg._type))
- throw new ValidationError(`${path59}: dispatcher with guid ${arg._guid} has type ${arg._type}, expected ${names.toString()}`);
- return { guid: arg._guid };
- }
- throw new ValidationError(`${path59}: expected dispatcher ${names.toString()}`);
- }
- existingDispatcher(object) {
- return this._dispatcherByObject.get(object);
- }
- registerDispatcher(dispatcher) {
- assert(!this._dispatcherByGuid.has(dispatcher._guid));
- this._dispatcherByGuid.set(dispatcher._guid, dispatcher);
- this._dispatcherByObject.set(dispatcher._object, dispatcher);
- let list = this._dispatchersByBucket.get(dispatcher._gcBucket);
- if (!list) {
- list = /* @__PURE__ */ new Set();
- this._dispatchersByBucket.set(dispatcher._gcBucket, list);
- }
- list.add(dispatcher._guid);
- }
- maybeDisposeStaleDispatchers(gcBucket) {
- const maxDispatchers = maxDispatchersForBucket(gcBucket);
- const list = this._dispatchersByBucket.get(gcBucket);
- if (!list || list.size <= maxDispatchers)
- return;
- const dispatchersArray = [...list];
- const disposeCount = maxDispatchers / 10 | 0;
- this._dispatchersByBucket.set(gcBucket, new Set(dispatchersArray.slice(disposeCount)));
- for (let i = 0; i < disposeCount; ++i) {
- const d = this._dispatcherByGuid.get(dispatchersArray[i]);
- if (!d)
- continue;
- d._dispose("gc");
- }
- }
- async dispatch(message) {
- const { id, guid, method, params: params2, metadata } = message;
- const dispatcher = this._dispatcherByGuid.get(guid);
- if (method === "__waitInfo__") {
- if (dispatcher)
- await this._dispatchWaitInfo(id, dispatcher, params2, metadata);
- return;
- }
- if (!dispatcher) {
- this.onmessage({ id, error: serializeError(new TargetClosedError(void 0)) });
- return;
- }
- let validParams;
- let validMetadata;
- try {
- const validator = findValidator(dispatcher._type, method, "Params");
- const validatorContext = this._validatorFromWireContext();
- validParams = validator(params2, "", validatorContext);
- validMetadata = metadataValidator(metadata, "", validatorContext);
- if (typeof dispatcher[method] !== "function")
- throw new Error(`Mismatching dispatcher: "${dispatcher._type}" does not implement "${method}"`);
- } catch (e) {
- this.onmessage({ id, error: serializeError(e) });
- return;
- }
- const metainfo = getMetainfo({ type: dispatcher._type, method });
- if (metainfo?.internal) {
- validMetadata.internal = true;
- }
- const sdkObject = dispatcher._object;
- const callMetadata = {
- id: `call@${id}`,
- location: validMetadata.location,
- title: validMetadata.title,
- internal: validMetadata.internal,
- stepId: validMetadata.stepId,
- objectId: sdkObject.guid,
- pageId: sdkObject.attribution?.page?.guid,
- frameId: sdkObject.attribution?.frame?.guid,
- startTime: monotonicTime(),
- endTime: 0,
- type: dispatcher._type,
- method,
- params: params2 || {},
- log: []
- };
- await sdkObject.instrumentation.onBeforeCall(sdkObject, callMetadata);
- const response2 = { id };
- try {
- if (this._dispatcherByGuid.get(guid) !== dispatcher)
- throw new TargetClosedError(sdkObject.closeReason());
- const result2 = await dispatcher._runCommand(callMetadata, method, validParams);
- const validator = findValidator(dispatcher._type, method, "Result");
- response2.result = validator(result2, "", this._validatorToWireContext());
- callMetadata.result = result2;
- } catch (e) {
- if (isTargetClosedError(e)) {
- const reason = sdkObject.closeReason();
- if (reason)
- rewriteErrorMessage(e, reason);
- } else if (isProtocolError(e)) {
- if (e.type === "closed")
- e = new TargetClosedError(sdkObject.closeReason(), e.browserLogMessage());
- else if (e.type === "crashed")
- rewriteErrorMessage(e, "Target crashed " + e.browserLogMessage());
- }
- response2.error = serializeError(e);
- const detailsValidator = maybeFindValidator(dispatcher._type, method, "ErrorDetails");
- if (detailsValidator)
- response2.errorDetails = detailsValidator(e?.details ?? {}, "", this._validatorToWireContext());
- callMetadata.error = response2.error;
- } finally {
- callMetadata.endTime = monotonicTime();
- await sdkObject.instrumentation.onAfterCall(sdkObject, callMetadata);
- if (metainfo?.slowMo)
- await this._doSlowMo(sdkObject);
- }
- if (response2.error)
- response2.log = compressCallLog(callMetadata.log);
- this.onmessage(response2);
- }
- async _doSlowMo(sdkObject) {
- const slowMo = sdkObject.attribution.browser?.options.slowMo;
- if (slowMo)
- await new Promise((f) => setTimeout(f, slowMo));
- }
- async _dispatchWaitInfo(id, dispatcher, params2, metadata) {
- let info;
- let validMetadata;
- try {
- const validatorContext = this._validatorFromWireContext();
- info = waitInfoValidator(params2, "", validatorContext);
- validMetadata = metadataValidator(metadata, "", validatorContext);
- } catch {
- return;
- }
- const sdkObject = dispatcher._object;
- if (info.phase === "before") {
- const callMetadata = {
- id: `call@${id}`,
- location: validMetadata.location,
- title: validMetadata.title,
- internal: validMetadata.internal,
- stepId: validMetadata.stepId,
- objectId: sdkObject.guid,
- pageId: sdkObject.attribution?.page?.guid,
- frameId: sdkObject.attribution?.frame?.guid,
- startTime: monotonicTime(),
- endTime: 0,
- type: dispatcher._type,
- method: "__waitInfo__",
- params: params2 || {},
- log: []
- };
- this._waitOperations.set(info.waitId, callMetadata);
- await sdkObject.instrumentation.onBeforeCall(sdkObject, callMetadata).catch(() => {
- });
- return;
- }
- const originalMetadata = this._waitOperations.get(info.waitId);
- if (!originalMetadata)
- return;
- if (info.phase === "log" && info.message) {
- originalMetadata.log.push(info.message);
- sdkObject.instrumentation.onCallLog(sdkObject, originalMetadata, "api", info.message);
- return;
- }
- if (info.phase === "after") {
- originalMetadata.endTime = monotonicTime();
- originalMetadata.error = info.error ? { error: { name: "Error", message: info.error } } : void 0;
- this._waitOperations.delete(info.waitId);
- await sdkObject.instrumentation.onAfterCall(sdkObject, originalMetadata).catch(() => {
- });
- }
- }
- };
- }
-});
-
-// packages/isomorphic/utilityScriptSerializers.ts
-function isRegExp5(obj) {
- try {
- return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";
- } catch (error) {
- return false;
- }
-}
-function isDate2(obj) {
- try {
- return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";
- } catch (error) {
- return false;
- }
-}
-function isURL2(obj) {
- try {
- return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";
- } catch (error) {
- return false;
- }
-}
-function isError3(obj) {
- try {
- return obj instanceof Error || obj && Object.getPrototypeOf(obj)?.name === "Error";
- } catch (error) {
- return false;
- }
-}
-function isTypedArray(obj, constructor) {
- try {
- return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;
- } catch (error) {
- return false;
- }
-}
-function isArrayBuffer(obj) {
- try {
- return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";
- } catch (error) {
- return false;
- }
-}
-function typedArrayToBase64(array) {
- if ("toBase64" in array)
- return array.toBase64();
- const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");
- return btoa(binary);
-}
-function base64ToTypedArray(base64, TypedArrayConstructor) {
- const binary = atob(base64);
- const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i++)
- bytes[i] = binary.charCodeAt(i);
- return new TypedArrayConstructor(bytes.buffer);
-}
-function parseEvaluationResultValue(value2, handles = [], refs = /* @__PURE__ */ new Map()) {
- if (Object.is(value2, void 0))
- return void 0;
- if (typeof value2 === "object" && value2) {
- if ("ref" in value2)
- return refs.get(value2.ref);
- if ("v" in value2) {
- if (value2.v === "undefined")
- return void 0;
- if (value2.v === "null")
- return null;
- if (value2.v === "NaN")
- return NaN;
- if (value2.v === "Infinity")
- return Infinity;
- if (value2.v === "-Infinity")
- return -Infinity;
- if (value2.v === "-0")
- return -0;
- return void 0;
- }
- if ("d" in value2) {
- return new Date(value2.d);
- }
- if ("u" in value2)
- return new URL(value2.u);
- if ("bi" in value2)
- return BigInt(value2.bi);
- if ("e" in value2) {
- const error = new Error(value2.e.m);
- error.name = value2.e.n;
- error.stack = value2.e.s;
- return error;
- }
- if ("r" in value2)
- return new RegExp(value2.r.p, value2.r.f);
- if ("a" in value2) {
- const result2 = [];
- refs.set(value2.id, result2);
- for (const a of value2.a)
- result2.push(parseEvaluationResultValue(a, handles, refs));
- return result2;
- }
- if ("o" in value2) {
- const result2 = {};
- refs.set(value2.id, result2);
- for (const { k, v } of value2.o) {
- if (k === "__proto__")
- continue;
- result2[k] = parseEvaluationResultValue(v, handles, refs);
- }
- return result2;
- }
- if ("h" in value2)
- return handles[value2.h];
- if ("ta" in value2)
- return base64ToTypedArray(value2.ta.b, typedArrayConstructors[value2.ta.k]);
- if ("ab" in value2)
- return base64ToTypedArray(value2.ab.b, Uint8Array).buffer;
- }
- return value2;
-}
-function serializeAsCallArgument(value2, handleSerializer) {
- return serialize(value2, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 });
-}
-function serialize(value2, handleSerializer, visitorInfo) {
- if (value2 && typeof value2 === "object") {
- if (typeof globalThis.Window === "function" && value2 instanceof globalThis.Window)
- return "ref: ";
- if (typeof globalThis.Document === "function" && value2 instanceof globalThis.Document)
- return "ref: ";
- if (typeof globalThis.Node === "function" && value2 instanceof globalThis.Node)
- return "ref: ";
- }
- return innerSerialize(value2, handleSerializer, visitorInfo);
-}
-function innerSerialize(value2, handleSerializer, visitorInfo) {
- const result2 = handleSerializer(value2);
- if ("fallThrough" in result2)
- value2 = result2.fallThrough;
- else
- return result2;
- if (typeof value2 === "symbol")
- return { v: "undefined" };
- if (Object.is(value2, void 0))
- return { v: "undefined" };
- if (Object.is(value2, null))
- return { v: "null" };
- if (Object.is(value2, NaN))
- return { v: "NaN" };
- if (Object.is(value2, Infinity))
- return { v: "Infinity" };
- if (Object.is(value2, -Infinity))
- return { v: "-Infinity" };
- if (Object.is(value2, -0))
- return { v: "-0" };
- if (typeof value2 === "boolean")
- return value2;
- if (typeof value2 === "number")
- return value2;
- if (typeof value2 === "string")
- return value2;
- if (typeof value2 === "bigint")
- return { bi: value2.toString() };
- if (isError3(value2)) {
- let stack;
- if (value2.stack?.startsWith(value2.name + ": " + value2.message)) {
- stack = value2.stack;
- } else {
- stack = `${value2.name}: ${value2.message}
-${value2.stack}`;
- }
- return { e: { n: value2.name, m: value2.message, s: stack } };
- }
- if (isDate2(value2))
- return { d: value2.toJSON() };
- if (isURL2(value2))
- return { u: value2.toJSON() };
- if (isRegExp5(value2))
- return { r: { p: value2.source, f: value2.flags } };
- for (const [k, ctor] of Object.entries(typedArrayConstructors)) {
- if (isTypedArray(value2, ctor))
- return { ta: { b: typedArrayToBase64(value2), k } };
- }
- if (isArrayBuffer(value2))
- return { ab: { b: typedArrayToBase64(new Uint8Array(value2)) } };
- const id = visitorInfo.visited.get(value2);
- if (id)
- return { ref: id };
- if (Array.isArray(value2)) {
- const a = [];
- const id2 = ++visitorInfo.lastId;
- visitorInfo.visited.set(value2, id2);
- for (let i = 0; i < value2.length; ++i)
- a.push(serialize(value2[i], handleSerializer, visitorInfo));
- return { a, id: id2 };
- }
- if (typeof value2 === "object") {
- const o = [];
- const id2 = ++visitorInfo.lastId;
- visitorInfo.visited.set(value2, id2);
- for (const name of Object.keys(value2)) {
- let item;
- try {
- item = value2[name];
- } catch (e) {
- continue;
- }
- if (name === "toJSON" && typeof item === "function")
- o.push({ k: name, v: { o: [], id: 0 } });
- else
- o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });
- }
- let jsonWrapper;
- try {
- if (o.length === 0 && value2.toJSON && typeof value2.toJSON === "function")
- jsonWrapper = { value: value2.toJSON() };
- } catch (e) {
- }
- if (jsonWrapper)
- return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);
- return { o, id: id2 };
- }
-}
-var typedArrayConstructors;
-var init_utilityScriptSerializers = __esm({
- "packages/isomorphic/utilityScriptSerializers.ts"() {
- "use strict";
- typedArrayConstructors = {
- i8: Int8Array,
- ui8: Uint8Array,
- ui8c: Uint8ClampedArray,
- i16: Int16Array,
- ui16: Uint16Array,
- i32: Int32Array,
- ui32: Uint32Array,
- // TODO: add Float16Array once it's in baseline
- f32: Float32Array,
- f64: Float64Array,
- bi64: BigInt64Array,
- bui64: BigUint64Array
- };
- }
-});
-
-// packages/playwright-core/src/generated/utilityScriptSource.ts
-var source3;
-var init_utilityScriptSource = __esm({
- "packages/playwright-core/src/generated/utilityScriptSource.ts"() {
- "use strict";
- source3 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/utilityScript.ts\nvar utilityScript_exports = {};\n__export(utilityScript_exports, {\n UtilityScript: () => UtilityScript\n});\nmodule.exports = __toCommonJS(utilityScript_exports);\n\n// packages/isomorphic/utilityScriptSerializers.ts\nfunction isRegExp(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date,\n AbortSignal: global.AbortSignal\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n return returnByValue ? this._promiseAwareJsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _promiseAwareJsonValueNoThrow(value) {\n const safeJson = (value2) => {\n try {\n return this.jsonValue(true, value2);\n } catch (e) {\n return void 0;\n }\n };\n if (value && typeof value === "object" && typeof value.then === "function") {\n return (async () => {\n const promiseValue = await value;\n return safeJson(promiseValue);\n })();\n }\n return safeJson(value);\n }\n};\n';
- }
-});
-
-// packages/playwright-core/src/server/javascript.ts
-async function evaluate(context2, returnByValue, pageFunction, ...args) {
- return evaluateExpression(context2, String(pageFunction), { returnByValue, isFunction: typeof pageFunction === "function" }, ...args);
-}
-async function evaluateExpression(context2, expression2, options, ...args) {
- expression2 = normalizeEvaluationExpression(expression2, options.isFunction);
- const handles = [];
- const toDispose = [];
- const pushHandle = (handle) => {
- handles.push(handle);
- return handles.length - 1;
- };
- args = args.map((arg) => serializeAsCallArgument(arg, (handle) => {
- if (handle instanceof JSHandle) {
- if (!handle._objectId)
- return { fallThrough: handle._value };
- if (handle._disposed)
- throw new JavaScriptErrorInEvaluate("JSHandle is disposed!");
- const adopted = context2.adoptIfNeeded(handle);
- if (adopted === null)
- return { h: pushHandle(Promise.resolve(handle)) };
- toDispose.push(adopted);
- return { h: pushHandle(adopted) };
- }
- return { fallThrough: handle };
- }));
- const utilityScriptObjects = [];
- for (const handle of await Promise.all(handles)) {
- if (handle._context !== context2)
- throw new JavaScriptErrorInEvaluate("JSHandles can be evaluated only in the context they were created!");
- utilityScriptObjects.push(handle);
- }
- const utilityScriptValues = [options.isFunction, options.returnByValue, expression2, args.length, ...args];
- const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`;
- try {
- return await context2._evaluateWithArguments(script, options.returnByValue || false, utilityScriptValues, utilityScriptObjects);
- } finally {
- toDispose.map((handlePromise) => handlePromise.then((handle) => handle.dispose()));
- }
-}
-function parseUnserializableValue(unserializableValue) {
- if (unserializableValue === "NaN")
- return NaN;
- if (unserializableValue === "Infinity")
- return Infinity;
- if (unserializableValue === "-Infinity")
- return -Infinity;
- if (unserializableValue === "-0")
- return -0;
-}
-function normalizeEvaluationExpression(expression2, isFunction2) {
- expression2 = expression2.trim();
- if (isFunction2) {
- try {
- new Function("(" + expression2 + ")");
- } catch (e1) {
- if (expression2.startsWith("async "))
- expression2 = "async function " + expression2.substring("async ".length);
- else
- expression2 = "function " + expression2;
- try {
- new Function("(" + expression2 + ")");
- } catch (e2) {
- throw new Error("Passed function is not well-serializable!");
- }
- }
- }
- if (/^(async)?\s*function(\s|\()/.test(expression2))
- expression2 = "(" + expression2 + ")";
- return expression2;
-}
-function isJavaScriptErrorInEvaluate(error) {
- return error instanceof JavaScriptErrorInEvaluate;
-}
-function sparseArrayToString(entries) {
- const arrayEntries = [];
- for (const { name, value: value2 } of entries) {
- const index = +name;
- if (isNaN(index) || index < 0)
- continue;
- arrayEntries.push({ index, value: value2 });
- }
- arrayEntries.sort((a, b) => a.index - b.index);
- let lastIndex = -1;
- const tokens = [];
- for (const { index, value: value2 } of arrayEntries) {
- const emptyItems = index - lastIndex - 1;
- if (emptyItems === 1)
- tokens.push(`empty`);
- else if (emptyItems > 1)
- tokens.push(`empty x ${emptyItems}`);
- tokens.push(String(value2));
- lastIndex = index;
- }
- return "[" + tokens.join(", ") + "]";
-}
-var ExecutionContext, JSHandle, JavaScriptErrorInEvaluate, snapshottedFunctionBuiltins, snapshottedObjectBuiltins, snapshottedTimerBuiltins, saveGlobalsSnapshotSource, mainWorldGlobalsSnapshotSource;
-var init_javascript = __esm({
- "packages/playwright-core/src/server/javascript.ts"() {
- "use strict";
- init_utilityScriptSerializers();
- init_manualPromise();
- init_debug();
- init_instrumentation();
- init_utilityScriptSource();
- ExecutionContext = class extends SdkObject {
- constructor(parent, delegate, worldNameForTest, options) {
- super(parent, "execution-context");
- this._contextDestroyedScope = new LongStandingScope();
- this.worldNameForTest = worldNameForTest;
- this._noUtilityWorld = options?.noUtilityWorld;
- this.delegate = delegate;
- }
- contextDestroyed(reason) {
- this._contextDestroyedScope.close(new Error(reason));
- }
- async raceAgainstContextDestroyed(promise) {
- return this._contextDestroyedScope.race(promise);
- }
- rawEvaluateJSON(expression2) {
- return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateJSON(expression2));
- }
- rawEvaluateHandle(expression2) {
- return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression2));
- }
- async _evaluateWithArguments(expression2, returnByValue, values, handles) {
- const utilityScript = await this._utilityScript();
- return this.raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression2, returnByValue, utilityScript, values, handles));
- }
- getProperties(object) {
- return this.raceAgainstContextDestroyed(this.delegate.getProperties(object));
- }
- _releaseHandle(handle) {
- return this.delegate.releaseHandle(handle);
- }
- adoptIfNeeded(handle) {
- return null;
- }
- _utilityScript() {
- if (!this._utilityScriptPromise) {
- const globalsSnapshot = this._noUtilityWorld ? mainWorldGlobalsSnapshotSource : "";
- const source11 = `
- (() => {
- ${globalsSnapshot}
- const module = {};
- ${source3}
- return new (module.exports.UtilityScript())(globalThis, ${isUnderTest()});
- })();`;
- this._utilityScriptPromise = this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, source11)).then((handle) => {
- handle._setPreview("UtilityScript");
- return handle;
- });
- }
- return this._utilityScriptPromise;
- }
- };
- JSHandle = class extends SdkObject {
- constructor(context2, type3, preview, objectId, value2) {
- super(context2, "handle");
- this.__jshandle = true;
- this._disposed = false;
- this._context = context2;
- this._objectId = objectId;
- this._value = value2;
- this._objectType = type3;
- this._preview = this._objectId ? preview || `JSHandle@${this._objectType}` : String(value2);
- if (this._objectId && globalThis.leakedJSHandles)
- globalThis.leakedJSHandles.set(this, new Error("Leaked JSHandle"));
- }
- async evaluateExpression(progress2, expression2, options, arg) {
- return await progress2.race(this.internalEvaluateExpression(expression2, options, arg));
- }
- async evaluateExpressionHandle(progress2, expression2, options, arg) {
- return await progress2.race(this._evaluateExpressionHandle(expression2, options, arg));
- }
- async getProperty(progress2, propertyName) {
- return await progress2.race(this._getProperty(propertyName));
- }
- async getProperties(progress2) {
- return await progress2.race(this.internalGetProperties());
- }
- async jsonValue(progress2) {
- return await progress2.race(this._jsonValue());
- }
- async evaluate(pageFunction, arg) {
- return evaluate(this._context, true, pageFunction, this, arg);
- }
- async evaluateHandle(pageFunction, arg) {
- return evaluate(this._context, false, pageFunction, this, arg);
- }
- async internalEvaluateExpression(expression2, options, arg) {
- return await evaluateExpression(this._context, expression2, { ...options, returnByValue: true }, this, arg);
- }
- async _evaluateExpressionHandle(expression2, options, arg) {
- return await evaluateExpression(this._context, expression2, { ...options, returnByValue: false }, this, arg);
- }
- async _getProperty(propertyName) {
- const objectHandle = await this.evaluateHandle((object, propertyName2) => {
- const result3 = { __proto__: null };
- result3[propertyName2] = object[propertyName2];
- return result3;
- }, propertyName);
- const properties = await objectHandle.internalGetProperties();
- const result2 = properties.get(propertyName);
- objectHandle.dispose();
- return result2;
- }
- async internalGetProperties() {
- if (!this._objectId)
- return /* @__PURE__ */ new Map();
- return this._context.getProperties(this);
- }
- rawValue() {
- return this._value;
- }
- async _jsonValue() {
- if (!this._objectId)
- return this._value;
- const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`;
- return this._context._evaluateWithArguments(script, true, [true], [this]);
- }
- asElement() {
- return null;
- }
- dispose() {
- if (this._disposed)
- return;
- this._disposed = true;
- if (this._objectId) {
- this._context._releaseHandle(this).catch((e) => {
- });
- if (globalThis.leakedJSHandles)
- globalThis.leakedJSHandles.delete(this);
- }
- }
- toString() {
- return this._preview;
- }
- _setPreviewCallback(callback) {
- this._previewCallback = callback;
- }
- preview() {
- return this._preview;
- }
- worldNameForTest() {
- return this._context.worldNameForTest;
- }
- _setPreview(preview) {
- this._preview = preview;
- if (this._previewCallback)
- this._previewCallback(preview);
- }
- };
- JavaScriptErrorInEvaluate = class extends Error {
- };
- snapshottedFunctionBuiltins = [
- // DOM
- "Node",
- "Element",
- "NodeFilter",
- "HTMLElement",
- "Document",
- "ShadowRoot",
- "MutationObserver",
- "Event",
- "CustomEvent",
- "EventTarget",
- // JS standard
- "Map",
- "Set",
- "WeakMap",
- "WeakSet",
- "Promise",
- "Symbol",
- "Error",
- "TypeError",
- "RegExp",
- "Array",
- "Object"
- ];
- snapshottedObjectBuiltins = ["JSON", "Math"];
- snapshottedTimerBuiltins = ["setTimeout"];
- saveGlobalsSnapshotSource = `window.__pwSnapshotGlobals = {
-${[...snapshottedFunctionBuiltins, ...snapshottedObjectBuiltins, ...snapshottedTimerBuiltins].map((n) => ` ${n}: window.${n}`).join(",\n")}
-};`;
- mainWorldGlobalsSnapshotSource = `
- const __snap = globalThis.__pwSnapshotGlobals || {};
-${snapshottedFunctionBuiltins.map((n) => ` const ${n} = (typeof globalThis.${n} === 'function' ? globalThis.${n} : __snap.${n});`).join("\n")}
-${snapshottedObjectBuiltins.map((n) => ` const ${n} = (typeof globalThis.${n} === 'object' && globalThis.${n} ? globalThis.${n} : __snap.${n});`).join("\n")}
-`;
- }
-});
-
-// packages/playwright-core/src/server/fileUploadUtils.ts
-async function filesExceedUploadLimit(files) {
- const sizes = await Promise.all(files.map(async (file) => (await import_fs13.default.promises.stat(file)).size));
- return sizes.reduce((total, size) => total + size, 0) >= fileUploadSizeLimit;
-}
-async function prepareFilesForUpload(frame, params2) {
- const { payloads, streams, directoryStream } = params2;
- let { localPaths, localDirectory } = params2;
- if (localPaths && !frame.attribution.playwright.options.isClientCollocatedWithServer)
- throw new Error("localPaths are not allowed when the client is not local");
- if ([payloads, localPaths, localDirectory, streams, directoryStream].filter(Boolean).length !== 1)
- throw new Error("Exactly one of payloads, localPaths and streams must be provided");
- if (streams)
- localPaths = streams.map((c) => c.path());
- if (directoryStream)
- localDirectory = directoryStream.path();
- if (localPaths) {
- for (const p of localPaths)
- assert(import_path12.default.isAbsolute(p) && import_path12.default.resolve(p) === p, "Paths provided to localPaths must be absolute and fully resolved.");
- }
- let fileBuffers = payloads;
- if (!frame._page.browserContext._browser._isBrowserCollocatedWithServer) {
- if (localPaths) {
- if (await filesExceedUploadLimit(localPaths))
- throw new Error("Cannot transfer files larger than 50Mb to a browser not co-located with the server");
- fileBuffers = await Promise.all(localPaths.map(async (item) => {
- return {
- name: import_path12.default.basename(item),
- buffer: await import_fs13.default.promises.readFile(item),
- lastModifiedMs: (await import_fs13.default.promises.stat(item)).mtimeMs
- };
- }));
- localPaths = void 0;
- }
- }
- const filePayloads = fileBuffers?.map((payload) => ({
- name: payload.name,
- mimeType: payload.mimeType || mime4.getType(payload.name) || "application/octet-stream",
- buffer: payload.buffer.toString("base64"),
- lastModifiedMs: payload.lastModifiedMs
- }));
- return { localPaths, localDirectory, filePayloads };
-}
-var import_fs13, import_path12, mime4, fileUploadSizeLimit;
-var init_fileUploadUtils = __esm({
- "packages/playwright-core/src/server/fileUploadUtils.ts"() {
- "use strict";
- import_fs13 = __toESM(require("fs"));
- import_path12 = __toESM(require("path"));
- init_assert();
- mime4 = require("./utilsBundle").mime;
- fileUploadSizeLimit = 50 * 1024 * 1024;
- }
-});
-
-// packages/playwright-core/src/generated/injectedScriptSource.ts
-var source4;
-var init_injectedScriptSource = __esm({
- "packages/playwright-core/src/generated/injectedScriptSource.ts"() {
- "use strict";
- source4 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/injectedScript.ts\nvar injectedScript_exports = {};\n__export(injectedScript_exports, {\n InjectedScript: () => InjectedScript\n});\nmodule.exports = __toCommonJS(injectedScript_exports);\n\n// packages/isomorphic/ariaSnapshot.ts\nfunction ariaNodesEqual(a, b) {\n if (a.role !== b.role || a.name !== b.name)\n return false;\n if (!ariaPropsEqual(a, b) || hasPointerCursor(a) !== hasPointerCursor(b))\n return false;\n const aKeys = Object.keys(a.props);\n const bKeys = Object.keys(b.props);\n return aKeys.length === bKeys.length && aKeys.every((k) => a.props[k] === b.props[k]);\n}\nfunction hasPointerCursor(ariaNode) {\n return ariaNode.box.cursor === "pointer";\n}\nfunction ariaPropsEqual(a, b) {\n return a.active === b.active && a.checked === b.checked && a.disabled === b.disabled && a.expanded === b.expanded && a.invalid === b.invalid && a.selected === b.selected && a.level === b.level && a.pressed === b.pressed;\n}\nfunction parseAriaSnapshot(yaml, text, options = {}) {\n var _a;\n const lineCounter = new yaml.LineCounter();\n const parseOptions = {\n keepSourceTokens: true,\n lineCounter,\n ...options\n };\n const yamlDoc = yaml.parseDocument(text, parseOptions);\n const errors = [];\n const convertRange = (range) => {\n return [lineCounter.linePos(range[0]), lineCounter.linePos(range[1])];\n };\n const addError = (error) => {\n errors.push({\n message: error.message,\n range: [lineCounter.linePos(error.pos[0]), lineCounter.linePos(error.pos[1])]\n });\n };\n const convertSeq = (container, seq) => {\n for (const item of seq.items) {\n const itemIsString = item instanceof yaml.Scalar && typeof item.value === "string";\n if (itemIsString) {\n const childNode = KeyParser.parse(item, parseOptions, errors);\n if (childNode) {\n container.children = container.children || [];\n container.children.push(childNode);\n }\n continue;\n }\n const itemIsMap = item instanceof yaml.YAMLMap;\n if (itemIsMap) {\n convertMap(container, item);\n continue;\n }\n errors.push({\n message: "Sequence items should be strings or maps",\n range: convertRange(item.range || seq.range)\n });\n }\n };\n const convertMap = (container, map) => {\n var _a2;\n for (const entry of map.items) {\n container.children = container.children || [];\n const keyIsString = entry.key instanceof yaml.Scalar && typeof entry.key.value === "string";\n if (!keyIsString) {\n errors.push({\n message: "Only string keys are supported",\n range: convertRange(entry.key.range || map.range)\n });\n continue;\n }\n const key = entry.key;\n const value = entry.value;\n if (key.value === "text") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Text value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n kind: "text",\n text: textValue(value.value)\n });\n continue;\n }\n if (key.value === "/children") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString || value.value !== "contain" && value.value !== "equal" && value.value !== "deep-equal") {\n errors.push({\n message: \'Strict value should be "contain", "equal" or "deep-equal"\',\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.containerMode = value.value;\n continue;\n }\n if (key.value.startsWith("/")) {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Property value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.props = (_a2 = container.props) != null ? _a2 : {};\n container.props[key.value.slice(1)] = textValue(value.value);\n continue;\n }\n const childNode = KeyParser.parse(key, parseOptions, errors);\n if (!childNode)\n continue;\n const valueIsScalar = value instanceof yaml.Scalar;\n if (valueIsScalar) {\n const type = typeof value.value;\n if (type !== "string" && type !== "number" && type !== "boolean") {\n errors.push({\n message: "Node value should be a string or a sequence",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n ...childNode,\n children: [{\n kind: "text",\n text: textValue(String(value.value))\n }]\n });\n continue;\n }\n const valueIsSequence = value instanceof yaml.YAMLSeq;\n if (valueIsSequence) {\n container.children.push(childNode);\n convertSeq(childNode, value);\n continue;\n }\n errors.push({\n message: "Map values should be strings or sequences",\n range: convertRange(entry.value.range || map.range)\n });\n }\n };\n const fragment = { kind: "role", role: "fragment" };\n yamlDoc.errors.forEach(addError);\n if (errors.length)\n return { errors, fragment };\n if (!(yamlDoc.contents instanceof yaml.YAMLSeq)) {\n errors.push({\n message: \'Aria snapshot must be a YAML sequence, elements starting with " -"\',\n range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }]\n });\n }\n if (errors.length)\n return { errors, fragment };\n convertSeq(fragment, yamlDoc.contents);\n if (errors.length)\n return { errors, fragment: emptyFragment };\n if (((_a = fragment.children) == null ? void 0 : _a.length) === 1 && (!fragment.containerMode || fragment.containerMode === "contain"))\n return { fragment: fragment.children[0], errors: [] };\n return { fragment, errors: [] };\n}\nvar emptyFragment = { kind: "role", role: "fragment" };\nfunction normalizeWhitespace(text) {\n return text.replace(/[\\u200b\\u00ad]/g, "").replace(/[\\r\\n\\s\\t]+/g, " ").trim();\n}\nfunction textValue(value) {\n return {\n raw: value,\n normalized: normalizeWhitespace(value)\n };\n}\nvar KeyParser = class _KeyParser {\n static parse(text, options, errors) {\n try {\n return new _KeyParser(text.value)._parse();\n } catch (e) {\n if (e instanceof ParserError) {\n const message = options.prettyErrors === false ? e.message : e.message + ":\\n\\n" + text.value + "\\n" + " ".repeat(e.pos) + "^\\n";\n errors.push({\n message,\n range: [options.lineCounter.linePos(text.range[0]), options.lineCounter.linePos(text.range[0] + e.pos)]\n });\n return null;\n }\n throw e;\n }\n }\n constructor(input) {\n this._input = input;\n this._pos = 0;\n this._length = input.length;\n }\n _peek() {\n return this._input[this._pos] || "";\n }\n _next() {\n if (this._pos < this._length)\n return this._input[this._pos++];\n return null;\n }\n _eof() {\n return this._pos >= this._length;\n }\n _isWhitespace() {\n return !this._eof() && /\\s/.test(this._peek());\n }\n _skipWhitespace() {\n while (this._isWhitespace())\n this._pos++;\n }\n _readIdentifier(type) {\n if (this._eof())\n this._throwError(`Unexpected end of input when expecting ${type}`);\n const start = this._pos;\n while (!this._eof() && /[a-zA-Z]/.test(this._peek()))\n this._pos++;\n return this._input.slice(start, this._pos);\n }\n _readString() {\n let result = "";\n let escaped = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n } else if (ch === \'"\') {\n return result;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated string");\n }\n _throwError(message, offset = 0) {\n throw new ParserError(message, offset || this._pos);\n }\n _readRegex() {\n let result = "";\n let escaped = false;\n let insideClass = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n result += ch;\n } else if (ch === "/" && !insideClass) {\n return { pattern: result };\n } else if (ch === "[") {\n insideClass = true;\n result += ch;\n } else if (ch === "]" && insideClass) {\n result += ch;\n insideClass = false;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated regex");\n }\n _readStringOrRegex() {\n const ch = this._peek();\n if (ch === \'"\') {\n this._next();\n return normalizeWhitespace(this._readString());\n }\n if (ch === "/") {\n this._next();\n return this._readRegex();\n }\n return null;\n }\n _readAttributes(result) {\n let errorPos = this._pos;\n while (true) {\n this._skipWhitespace();\n if (this._peek() === "[") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n const flagName = this._readIdentifier("attribute");\n this._skipWhitespace();\n let flagValue = "";\n if (this._peek() === "=") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n while (this._peek() !== "]" && !this._isWhitespace() && !this._eof())\n flagValue += this._next();\n }\n this._skipWhitespace();\n if (this._peek() !== "]")\n this._throwError("Expected ]");\n this._next();\n this._applyAttribute(result, flagName, flagValue || "true", errorPos);\n } else {\n break;\n }\n }\n }\n _parse() {\n this._skipWhitespace();\n const role = this._readIdentifier("role");\n this._skipWhitespace();\n const name = this._readStringOrRegex() || "";\n const result = { kind: "role", role, name };\n this._readAttributes(result);\n this._skipWhitespace();\n if (!this._eof())\n this._throwError("Unexpected input");\n return result;\n }\n _applyAttribute(node, key, value, errorPos) {\n if (key === "checked") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "checked" attribute must be a boolean or "mixed"\', errorPos);\n node.checked = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "disabled") {\n this._assert(value === "true" || value === "false", \'Value of "disabled" attribute must be a boolean\', errorPos);\n node.disabled = value === "true";\n return;\n }\n if (key === "expanded") {\n this._assert(value === "true" || value === "false", \'Value of "expanded" attribute must be a boolean\', errorPos);\n node.expanded = value === "true";\n return;\n }\n if (key === "active") {\n this._assert(value === "true" || value === "false", \'Value of "active" attribute must be a boolean\', errorPos);\n node.active = value === "true";\n return;\n }\n if (key === "invalid") {\n this._assert(value === "true" || value === "false" || value === "grammar" || value === "spelling", \'Value of "invalid" attribute must be a boolean, "grammar" or "spelling"\', errorPos);\n node.invalid = value === "true" ? true : value === "false" ? false : value;\n return;\n }\n if (key === "level") {\n this._assert(!isNaN(Number(value)), \'Value of "level" attribute must be a number\', errorPos);\n node.level = Number(value);\n return;\n }\n if (key === "pressed") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "pressed" attribute must be a boolean or "mixed"\', errorPos);\n node.pressed = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "selected") {\n this._assert(value === "true" || value === "false", \'Value of "selected" attribute must be a boolean\', errorPos);\n node.selected = value === "true";\n return;\n }\n this._assert(false, `Unsupported attribute [${key}]`, errorPos);\n }\n _assert(value, message, valuePos) {\n if (!value)\n this._throwError(message || "Assertion error", valuePos);\n }\n};\nvar ParserError = class extends Error {\n constructor(message, pos) {\n super(message);\n this.pos = pos;\n }\n};\nfunction findNewNode(from, to) {\n var _a, _b;\n function fillMap(root, map, position) {\n let size = 1;\n let childPosition = position + size;\n for (const child of root.children || []) {\n if (typeof child === "string") {\n size++;\n childPosition++;\n } else {\n size += fillMap(child, map, childPosition);\n childPosition += size;\n }\n }\n if (!["none", "presentation", "fragment", "iframe", "generic"].includes(root.role) && root.name) {\n let byRole = map.get(root.role);\n if (!byRole) {\n byRole = /* @__PURE__ */ new Map();\n map.set(root.role, byRole);\n }\n const existing = byRole.get(root.name);\n const sizeAndPosition = size * 100 - position;\n if (!existing || existing.sizeAndPosition < sizeAndPosition)\n byRole.set(root.name, { node: root, sizeAndPosition });\n }\n return size;\n }\n const fromMap = /* @__PURE__ */ new Map();\n if (from)\n fillMap(from, fromMap, 0);\n const toMap = /* @__PURE__ */ new Map();\n fillMap(to, toMap, 0);\n const result = [];\n for (const [role, byRole] of toMap) {\n for (const [name, byName] of byRole) {\n const inFrom = (_a = fromMap.get(role)) == null ? void 0 : _a.get(name);\n if (!inFrom)\n result.push(byName);\n }\n }\n result.sort((a, b) => b.sizeAndPosition - a.sizeAndPosition);\n return (_b = result[0]) == null ? void 0 : _b.node;\n}\n\n// packages/isomorphic/cssTokenizer.ts\nvar between = function(num, first, last) {\n return num >= first && num <= last;\n};\nfunction digit(code) {\n return between(code, 48, 57);\n}\nfunction hexdigit(code) {\n return digit(code) || between(code, 65, 70) || between(code, 97, 102);\n}\nfunction uppercaseletter(code) {\n return between(code, 65, 90);\n}\nfunction lowercaseletter(code) {\n return between(code, 97, 122);\n}\nfunction letter(code) {\n return uppercaseletter(code) || lowercaseletter(code);\n}\nfunction nonascii(code) {\n return code >= 128;\n}\nfunction namestartchar(code) {\n return letter(code) || nonascii(code) || code === 95;\n}\nfunction namechar(code) {\n return namestartchar(code) || digit(code) || code === 45;\n}\nfunction nonprintable(code) {\n return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127;\n}\nfunction newline(code) {\n return code === 10;\n}\nfunction whitespace(code) {\n return newline(code) || code === 9 || code === 32;\n}\nvar maximumallowedcodepoint = 1114111;\nvar InvalidCharacterError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "InvalidCharacterError";\n }\n};\nfunction preprocess(str) {\n const codepoints = [];\n for (let i = 0; i < str.length; i++) {\n let code = str.charCodeAt(i);\n if (code === 13 && str.charCodeAt(i + 1) === 10) {\n code = 10;\n i++;\n }\n if (code === 13 || code === 12)\n code = 10;\n if (code === 0)\n code = 65533;\n if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) {\n const lead = code - 55296;\n const trail = str.charCodeAt(i + 1) - 56320;\n code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail;\n i++;\n }\n codepoints.push(code);\n }\n return codepoints;\n}\nfunction stringFromCode(code) {\n if (code <= 65535)\n return String.fromCharCode(code);\n code -= Math.pow(2, 16);\n const lead = Math.floor(code / Math.pow(2, 10)) + 55296;\n const trail = code % Math.pow(2, 10) + 56320;\n return String.fromCharCode(lead) + String.fromCharCode(trail);\n}\nfunction tokenize(str1) {\n const str = preprocess(str1);\n let i = -1;\n const tokens = [];\n let code;\n let line = 0;\n let column = 0;\n let lastLineLength = 0;\n const incrLineno = function() {\n line += 1;\n lastLineLength = column;\n column = 0;\n };\n const locStart = { line, column };\n const codepoint = function(i2) {\n if (i2 >= str.length)\n return -1;\n return str[i2];\n };\n const next = function(num) {\n if (num === void 0)\n num = 1;\n if (num > 3)\n throw "Spec Error: no more than three codepoints of lookahead.";\n return codepoint(i + num);\n };\n const consume = function(num) {\n if (num === void 0)\n num = 1;\n i += num;\n code = codepoint(i);\n if (newline(code))\n incrLineno();\n else\n column += num;\n return true;\n };\n const reconsume = function() {\n i -= 1;\n if (newline(code)) {\n line -= 1;\n column = lastLineLength;\n } else {\n column -= 1;\n }\n locStart.line = line;\n locStart.column = column;\n return true;\n };\n const eof = function(codepoint2) {\n if (codepoint2 === void 0)\n codepoint2 = code;\n return codepoint2 === -1;\n };\n const donothing = function() {\n };\n const parseerror = function() {\n };\n const consumeAToken = function() {\n consumeComments();\n consume();\n if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n return new WhitespaceToken();\n } else if (code === 34) {\n return consumeAStringToken();\n } else if (code === 35) {\n if (namechar(next()) || areAValidEscape(next(1), next(2))) {\n const token = new HashToken("");\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n token.type = "id";\n token.value = consumeAName();\n return token;\n } else {\n return new DelimToken(code);\n }\n } else if (code === 36) {\n if (next() === 61) {\n consume();\n return new SuffixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 39) {\n return consumeAStringToken();\n } else if (code === 40) {\n return new OpenParenToken();\n } else if (code === 41) {\n return new CloseParenToken();\n } else if (code === 42) {\n if (next() === 61) {\n consume();\n return new SubstringMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 43) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 44) {\n return new CommaToken();\n } else if (code === 45) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else if (next(1) === 45 && next(2) === 62) {\n consume(2);\n return new CDCToken();\n } else if (startsWithAnIdentifier()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 46) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 58) {\n return new ColonToken();\n } else if (code === 59) {\n return new SemicolonToken();\n } else if (code === 60) {\n if (next(1) === 33 && next(2) === 45 && next(3) === 45) {\n consume(3);\n return new CDOToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 64) {\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n return new AtKeywordToken(consumeAName());\n else\n return new DelimToken(code);\n } else if (code === 91) {\n return new OpenSquareToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n parseerror();\n return new DelimToken(code);\n }\n } else if (code === 93) {\n return new CloseSquareToken();\n } else if (code === 94) {\n if (next() === 61) {\n consume();\n return new PrefixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 123) {\n return new OpenCurlyToken();\n } else if (code === 124) {\n if (next() === 61) {\n consume();\n return new DashMatchToken();\n } else if (next() === 124) {\n consume();\n return new ColumnToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 125) {\n return new CloseCurlyToken();\n } else if (code === 126) {\n if (next() === 61) {\n consume();\n return new IncludeMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (digit(code)) {\n reconsume();\n return consumeANumericToken();\n } else if (namestartchar(code)) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else if (eof()) {\n return new EOFToken();\n } else {\n return new DelimToken(code);\n }\n };\n const consumeComments = function() {\n while (next(1) === 47 && next(2) === 42) {\n consume(2);\n while (true) {\n consume();\n if (code === 42 && next() === 47) {\n consume();\n break;\n } else if (eof()) {\n parseerror();\n return;\n }\n }\n }\n };\n const consumeANumericToken = function() {\n const num = consumeANumber();\n if (wouldStartAnIdentifier(next(1), next(2), next(3))) {\n const token = new DimensionToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n token.unit = consumeAName();\n return token;\n } else if (next() === 37) {\n consume();\n const token = new PercentageToken();\n token.value = num.value;\n token.repr = num.repr;\n return token;\n } else {\n const token = new NumberToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n return token;\n }\n };\n const consumeAnIdentlikeToken = function() {\n const str2 = consumeAName();\n if (str2.toLowerCase() === "url" && next() === 40) {\n consume();\n while (whitespace(next(1)) && whitespace(next(2)))\n consume();\n if (next() === 34 || next() === 39)\n return new FunctionToken(str2);\n else if (whitespace(next()) && (next(2) === 34 || next(2) === 39))\n return new FunctionToken(str2);\n else\n return consumeAURLToken();\n } else if (next() === 40) {\n consume();\n return new FunctionToken(str2);\n } else {\n return new IdentToken(str2);\n }\n };\n const consumeAStringToken = function(endingCodePoint) {\n if (endingCodePoint === void 0)\n endingCodePoint = code;\n let string = "";\n while (consume()) {\n if (code === endingCodePoint || eof()) {\n return new StringToken(string);\n } else if (newline(code)) {\n parseerror();\n reconsume();\n return new BadStringToken();\n } else if (code === 92) {\n if (eof(next()))\n donothing();\n else if (newline(next()))\n consume();\n else\n string += stringFromCode(consumeEscape());\n } else {\n string += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeAURLToken = function() {\n const token = new URLToken("");\n while (whitespace(next()))\n consume();\n if (eof(next()))\n return token;\n while (consume()) {\n if (code === 41 || eof()) {\n return token;\n } else if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n if (next() === 41 || eof(next())) {\n consume();\n return token;\n } else {\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n token.value += stringFromCode(consumeEscape());\n } else {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else {\n token.value += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeEscape = function() {\n consume();\n if (hexdigit(code)) {\n const digits = [code];\n for (let total = 0; total < 5; total++) {\n if (hexdigit(next())) {\n consume();\n digits.push(code);\n } else {\n break;\n }\n }\n if (whitespace(next()))\n consume();\n let value = parseInt(digits.map(function(x) {\n return String.fromCharCode(x);\n }).join(""), 16);\n if (value > maximumallowedcodepoint)\n value = 65533;\n return value;\n } else if (eof()) {\n return 65533;\n } else {\n return code;\n }\n };\n const areAValidEscape = function(c1, c2) {\n if (c1 !== 92)\n return false;\n if (newline(c2))\n return false;\n return true;\n };\n const startsWithAValidEscape = function() {\n return areAValidEscape(code, next());\n };\n const wouldStartAnIdentifier = function(c1, c2, c3) {\n if (c1 === 45)\n return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3);\n else if (namestartchar(c1))\n return true;\n else if (c1 === 92)\n return areAValidEscape(c1, c2);\n else\n return false;\n };\n const startsWithAnIdentifier = function() {\n return wouldStartAnIdentifier(code, next(1), next(2));\n };\n const wouldStartANumber = function(c1, c2, c3) {\n if (c1 === 43 || c1 === 45) {\n if (digit(c2))\n return true;\n if (c2 === 46 && digit(c3))\n return true;\n return false;\n } else if (c1 === 46) {\n if (digit(c2))\n return true;\n return false;\n } else if (digit(c1)) {\n return true;\n } else {\n return false;\n }\n };\n const startsWithANumber = function() {\n return wouldStartANumber(code, next(1), next(2));\n };\n const consumeAName = function() {\n let result = "";\n while (consume()) {\n if (namechar(code)) {\n result += stringFromCode(code);\n } else if (startsWithAValidEscape()) {\n result += stringFromCode(consumeEscape());\n } else {\n reconsume();\n return result;\n }\n }\n throw new Error("Internal parse error");\n };\n const consumeANumber = function() {\n let repr = "";\n let type = "integer";\n if (next() === 43 || next() === 45) {\n consume();\n repr += stringFromCode(code);\n }\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n if (next(1) === 46 && digit(next(2))) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const c1 = next(1);\n const c2 = next(2);\n const c3 = next(3);\n if ((c1 === 69 || c1 === 101) && digit(c2)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const value = convertAStringToANumber(repr);\n return { type, value, repr };\n };\n const convertAStringToANumber = function(string) {\n return +string;\n };\n const consumeTheRemnantsOfABadURL = function() {\n while (consume()) {\n if (code === 41 || eof()) {\n return;\n } else if (startsWithAValidEscape()) {\n consumeEscape();\n donothing();\n } else {\n donothing();\n }\n }\n };\n let iterationCount = 0;\n while (!eof(next())) {\n tokens.push(consumeAToken());\n iterationCount++;\n if (iterationCount > str.length * 2)\n throw new Error("I\'m infinite-looping!");\n }\n return tokens;\n}\nvar CSSParserToken = class {\n constructor() {\n this.tokenType = "";\n }\n toJSON() {\n return { token: this.tokenType };\n }\n toString() {\n return this.tokenType;\n }\n toSource() {\n return "" + this;\n }\n};\nvar BadStringToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADSTRING";\n }\n};\nvar BadURLToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADURL";\n }\n};\nvar WhitespaceToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "WHITESPACE";\n }\n toString() {\n return "WS";\n }\n toSource() {\n return " ";\n }\n};\nvar CDOToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "CDO";\n }\n toSource() {\n return "";\n }\n};\nvar ColonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ":";\n }\n};\nvar SemicolonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ";";\n }\n};\nvar CommaToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ",";\n }\n};\nvar GroupingToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n this.mirror = "";\n }\n};\nvar OpenCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "{";\n this.value = "{";\n this.mirror = "}";\n }\n};\nvar CloseCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "}";\n this.value = "}";\n this.mirror = "{";\n }\n};\nvar OpenSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "[";\n this.value = "[";\n this.mirror = "]";\n }\n};\nvar CloseSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "]";\n this.value = "]";\n this.mirror = "[";\n }\n};\nvar OpenParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "(";\n this.value = "(";\n this.mirror = ")";\n }\n};\nvar CloseParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = ")";\n this.value = ")";\n this.mirror = "(";\n }\n};\nvar IncludeMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "~=";\n }\n};\nvar DashMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "|=";\n }\n};\nvar PrefixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "^=";\n }\n};\nvar SuffixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "$=";\n }\n};\nvar SubstringMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "*=";\n }\n};\nvar ColumnToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "||";\n }\n};\nvar EOFToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "EOF";\n }\n toSource() {\n return "";\n }\n};\nvar DelimToken = class extends CSSParserToken {\n constructor(code) {\n super();\n this.tokenType = "DELIM";\n this.value = "";\n this.value = stringFromCode(code);\n }\n toString() {\n return "DELIM(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n toSource() {\n if (this.value === "\\\\")\n return "\\\\\\n";\n else\n return this.value;\n }\n};\nvar StringValuedToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n }\n ASCIIMatch(str) {\n return this.value.toLowerCase() === str.toLowerCase();\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n};\nvar IdentToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "IDENT";\n this.value = val;\n }\n toString() {\n return "IDENT(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value);\n }\n};\nvar FunctionToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "FUNCTION";\n this.value = val;\n this.mirror = ")";\n }\n toString() {\n return "FUNCTION(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value) + "(";\n }\n};\nvar AtKeywordToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "AT-KEYWORD";\n this.value = val;\n }\n toString() {\n return "AT(" + this.value + ")";\n }\n toSource() {\n return "@" + escapeIdent(this.value);\n }\n};\nvar HashToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "HASH";\n this.value = val;\n this.type = "unrestricted";\n }\n toString() {\n return "HASH(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n return json;\n }\n toSource() {\n if (this.type === "id")\n return "#" + escapeIdent(this.value);\n else\n return "#" + escapeHash(this.value);\n }\n};\nvar StringToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "STRING";\n this.value = val;\n }\n toString() {\n return \'"\' + escapeString(this.value) + \'"\';\n }\n};\nvar URLToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "URL";\n this.value = val;\n }\n toString() {\n return "URL(" + this.value + ")";\n }\n toSource() {\n return \'url("\' + escapeString(this.value) + \'")\';\n }\n};\nvar NumberToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "NUMBER";\n this.type = "integer";\n this.repr = "";\n }\n toString() {\n if (this.type === "integer")\n return "INT(" + this.value + ")";\n return "NUMBER(" + this.value + ")";\n }\n toJSON() {\n const json = super.toJSON();\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr;\n }\n};\nvar PercentageToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "PERCENTAGE";\n this.repr = "";\n }\n toString() {\n return "PERCENTAGE(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr + "%";\n }\n};\nvar DimensionToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "DIMENSION";\n this.type = "integer";\n this.repr = "";\n this.unit = "";\n }\n toString() {\n return "DIM(" + this.value + "," + this.unit + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n json.unit = this.unit;\n return json;\n }\n toSource() {\n const source = this.repr;\n let unit = escapeIdent(this.unit);\n if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) {\n unit = "\\\\65 " + unit.slice(1, unit.length);\n }\n return source + unit;\n }\n};\nfunction escapeIdent(string) {\n string = "" + string;\n let result = "";\n const firstcode = string.charCodeAt(0);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45)\n result += "\\\\" + code.toString(16) + " ";\n else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + string[i];\n }\n return result;\n}\nfunction escapeHash(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + code.toString(16) + " ";\n }\n return result;\n}\nfunction escapeString(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127)\n result += "\\\\" + code.toString(16) + " ";\n else if (code === 34 || code === 92)\n result += "\\\\" + string[i];\n else\n result += string[i];\n }\n return result;\n}\n\n// packages/isomorphic/cssParser.ts\nvar InvalidSelectorError = class extends Error {\n};\nfunction parseCSS(selector, customNames) {\n let tokens;\n try {\n tokens = tokenize(selector);\n if (!(tokens[tokens.length - 1] instanceof EOFToken))\n tokens.push(new EOFToken());\n } catch (e) {\n const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`;\n const index = (e.stack || "").indexOf(e.message);\n if (index !== -1)\n e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);\n e.message = newMessage;\n throw e;\n }\n const unsupportedToken = tokens.find((token) => {\n return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings.\n // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }\n // Or this way :xpath( {complex-xpath-goes-here("hello")} )\n token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings?\n token instanceof URLToken || token instanceof PercentageToken;\n });\n if (unsupportedToken)\n throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n let pos = 0;\n const names = /* @__PURE__ */ new Set();\n function unexpected() {\n return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n }\n function skipWhitespace() {\n while (tokens[pos] instanceof WhitespaceToken)\n pos++;\n }\n function isIdent(p = pos) {\n return tokens[p] instanceof IdentToken;\n }\n function isString(p = pos) {\n return tokens[p] instanceof StringToken;\n }\n function isNumber(p = pos) {\n return tokens[p] instanceof NumberToken;\n }\n function isComma(p = pos) {\n return tokens[p] instanceof CommaToken;\n }\n function isOpenParen(p = pos) {\n return tokens[p] instanceof OpenParenToken;\n }\n function isCloseParen(p = pos) {\n return tokens[p] instanceof CloseParenToken;\n }\n function isFunction(p = pos) {\n return tokens[p] instanceof FunctionToken;\n }\n function isStar(p = pos) {\n return tokens[p] instanceof DelimToken && tokens[p].value === "*";\n }\n function isEOF(p = pos) {\n return tokens[p] instanceof EOFToken;\n }\n function isClauseCombinator(p = pos) {\n return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value);\n }\n function isSelectorClauseEnd(p = pos) {\n return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken;\n }\n function consumeFunctionArguments() {\n const result2 = [consumeArgument()];\n while (true) {\n skipWhitespace();\n if (!isComma())\n break;\n pos++;\n result2.push(consumeArgument());\n }\n return result2;\n }\n function consumeArgument() {\n skipWhitespace();\n if (isNumber())\n return tokens[pos++].value;\n if (isString())\n return tokens[pos++].value;\n return consumeComplexSelector();\n }\n function consumeComplexSelector() {\n const result2 = { simples: [] };\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" });\n } else {\n result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" });\n }\n while (true) {\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value;\n skipWhitespace();\n } else if (isSelectorClauseEnd()) {\n break;\n }\n result2.simples.push({ combinator: "", selector: consumeSimpleSelector() });\n }\n return result2;\n }\n function consumeSimpleSelector() {\n let rawCSSString = "";\n const functions = [];\n while (!isSelectorClauseEnd()) {\n if (isIdent() || isStar()) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof HashToken) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") {\n pos++;\n if (isIdent())\n rawCSSString += "." + tokens[pos++].toSource();\n else\n throw unexpected();\n } else if (tokens[pos] instanceof ColonToken) {\n pos++;\n if (isIdent()) {\n if (!customNames.has(tokens[pos].value.toLowerCase())) {\n rawCSSString += ":" + tokens[pos++].toSource();\n } else {\n const name = tokens[pos++].value.toLowerCase();\n functions.push({ name, args: [] });\n names.add(name);\n }\n } else if (isFunction()) {\n const name = tokens[pos++].value.toLowerCase();\n if (!customNames.has(name)) {\n rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;\n } else {\n functions.push({ name, args: consumeFunctionArguments() });\n names.add(name);\n }\n skipWhitespace();\n if (!isCloseParen())\n throw unexpected();\n pos++;\n } else {\n throw unexpected();\n }\n } else if (tokens[pos] instanceof OpenSquareToken) {\n rawCSSString += "[";\n pos++;\n while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF())\n rawCSSString += tokens[pos++].toSource();\n if (!(tokens[pos] instanceof CloseSquareToken))\n throw unexpected();\n rawCSSString += "]";\n pos++;\n } else {\n throw unexpected();\n }\n }\n if (!rawCSSString && !functions.length)\n throw unexpected();\n return { css: rawCSSString || void 0, functions };\n }\n function consumeBuiltinFunctionArguments() {\n let s = "";\n let balance = 1;\n while (!isEOF()) {\n if (isOpenParen() || isFunction())\n balance++;\n if (isCloseParen())\n balance--;\n if (!balance)\n break;\n s += tokens[pos++].toSource();\n }\n return s;\n }\n const result = consumeFunctionArguments();\n if (!isEOF())\n throw unexpected();\n if (result.some((arg) => typeof arg !== "object" || !("simples" in arg)))\n throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n return { selector: result, names: Array.from(names) };\n}\n\n// packages/isomorphic/selectorParser.ts\nvar kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]);\nvar kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]);\nvar customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]);\nfunction parseSelector(selector) {\n const parsedStrings = parseSelectorString(selector);\n const parts = [];\n for (const part of parsedStrings.parts) {\n if (part.name === "css" || part.name === "css:light") {\n if (part.name === "css:light")\n part.body = ":light(" + part.body + ")";\n const parsedCSS = parseCSS(part.body, customCSSNames);\n parts.push({\n name: "css",\n body: parsedCSS.selector,\n source: part.body\n });\n continue;\n }\n if (kNestedSelectorNames.has(part.name)) {\n let innerSelector;\n let distance;\n try {\n const unescaped = JSON.parse("[" + part.body + "]");\n if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string")\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n innerSelector = unescaped[0];\n if (unescaped.length === 2) {\n if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name))\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n distance = unescaped[1];\n }\n } catch (e) {\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n }\n const nested = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } };\n const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame");\n const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1;\n if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), parts.slice(0, lastFrameIndex + 1)))\n nested.body.parsed.parts.splice(0, lastFrameIndex + 1);\n parts.push(nested);\n continue;\n }\n parts.push({ ...part, source: part.body });\n }\n if (kNestedSelectorNames.has(parts[0].name))\n throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`);\n return {\n capture: parsedStrings.capture,\n parts\n };\n}\nfunction selectorPartsEqual(list1, list2) {\n return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 });\n}\nfunction stringifySelector(selector, forceEngineName) {\n if (typeof selector === "string")\n return selector;\n return selector.parts.map((p, i) => {\n let includeEngine = true;\n if (!forceEngineName && i !== selector.capture) {\n if (p.name === "css")\n includeEngine = false;\n else if (p.name === "xpath" && p.source.startsWith("//") || p.source.startsWith(".."))\n includeEngine = false;\n }\n const prefix = includeEngine ? p.name + "=" : "";\n return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`;\n }).join(" >> ");\n}\nfunction visitAllSelectorParts(selector, visitor) {\n const visit = (selector2, nested) => {\n for (const part of selector2.parts) {\n visitor(part, nested);\n if (kNestedSelectorNames.has(part.name))\n visit(part.body.parsed, true);\n }\n };\n visit(selector, false);\n}\nfunction parseSelectorString(selector) {\n let index = 0;\n let quote;\n let start = 0;\n const result = { parts: [] };\n const append = () => {\n const part = selector.substring(start, index).trim();\n const eqIndex = part.indexOf("=");\n let name;\n let body;\n if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {\n name = part.substring(0, eqIndex).trim();\n body = part.substring(eqIndex + 1);\n } else if (part.length > 1 && part[0] === \'"\' && part[part.length - 1] === \'"\') {\n name = "text";\n body = part;\n } else if (part.length > 1 && part[0] === "\'" && part[part.length - 1] === "\'") {\n name = "text";\n body = part;\n } else if (/^\\(*\\/\\//.test(part) || part.startsWith("..")) {\n name = "xpath";\n body = part;\n } else {\n name = "css";\n body = part;\n }\n let capture = false;\n if (name[0] === "*") {\n capture = true;\n name = name.substring(1);\n }\n result.parts.push({ name, body });\n if (capture) {\n if (result.capture !== void 0)\n throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`);\n result.capture = result.parts.length - 1;\n }\n };\n if (!selector.includes(">>")) {\n index = selector.length;\n append();\n return result;\n }\n const shouldIgnoreTextSelectorQuote = () => {\n const prefix = selector.substring(start, index);\n const match = prefix.match(/^\\s*text\\s*=(.*)$/);\n return !!match && !!match[1];\n };\n while (index < selector.length) {\n const c = selector[index];\n if (c === "\\\\" && index + 1 < selector.length) {\n index += 2;\n } else if (c === quote) {\n quote = void 0;\n index++;\n } else if (!quote && (c === \'"\' || c === "\'" || c === "`") && !shouldIgnoreTextSelectorQuote()) {\n quote = c;\n index++;\n } else if (!quote && c === ">" && selector[index + 1] === ">") {\n append();\n index += 2;\n start = index;\n } else {\n index++;\n }\n }\n append();\n return result;\n}\nfunction parseAttributeSelector(selector, allowUnquotedStrings) {\n let wp = 0;\n let EOL = selector.length === 0;\n const next = () => selector[wp] || "";\n const eat1 = () => {\n const result2 = next();\n ++wp;\n EOL = wp >= selector.length;\n return result2;\n };\n const syntaxError = (stage) => {\n if (EOL)\n throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \\`${selector}\\``);\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : ""));\n };\n function skipSpaces() {\n while (!EOL && /\\s/.test(next()))\n eat1();\n }\n function isCSSNameChar(char) {\n return char >= "\\x80" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-";\n }\n function readIdentifier() {\n let result2 = "";\n skipSpaces();\n while (!EOL && isCSSNameChar(next()))\n result2 += eat1();\n return result2;\n }\n function readQuotedString(quote) {\n let result2 = eat1();\n if (result2 !== quote)\n syntaxError("parsing quoted string");\n while (!EOL && next() !== quote) {\n if (next() === "\\\\")\n eat1();\n result2 += eat1();\n }\n if (next() !== quote)\n syntaxError("parsing quoted string");\n result2 += eat1();\n return result2;\n }\n function readRegularExpression() {\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let source = "";\n let inClass = false;\n while (!EOL) {\n if (next() === "\\\\") {\n source += eat1();\n if (EOL)\n syntaxError("parsing regular expression");\n } else if (inClass && next() === "]") {\n inClass = false;\n } else if (!inClass && next() === "[") {\n inClass = true;\n } else if (!inClass && next() === "/") {\n break;\n }\n source += eat1();\n }\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let flags = "";\n while (!EOL && next().match(/[dgimsuy]/))\n flags += eat1();\n try {\n return new RegExp(source, flags);\n } catch (e) {\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\`: ${e.message}`);\n }\n }\n function readAttributeToken() {\n let token = "";\n skipSpaces();\n if (next() === `\'` || next() === `"`)\n token = readQuotedString(next()).slice(1, -1);\n else\n token = readIdentifier();\n if (!token)\n syntaxError("parsing property path");\n return token;\n }\n function readOperator() {\n skipSpaces();\n let op = "";\n if (!EOL)\n op += eat1();\n if (!EOL && op !== "=")\n op += eat1();\n if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op))\n syntaxError("parsing operator");\n return op;\n }\n function readAttribute() {\n eat1();\n const jsonPath = [];\n jsonPath.push(readAttributeToken());\n skipSpaces();\n while (next() === ".") {\n eat1();\n jsonPath.push(readAttributeToken());\n skipSpaces();\n }\n if (next() === "]") {\n eat1();\n return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false };\n }\n const operator = readOperator();\n let value = void 0;\n let caseSensitive = true;\n skipSpaces();\n if (next() === "/") {\n if (operator !== "=")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with regular expression`);\n value = readRegularExpression();\n } else if (next() === `\'` || next() === `"`) {\n value = readQuotedString(next()).slice(1, -1);\n skipSpaces();\n if (next() === "i" || next() === "I") {\n caseSensitive = false;\n eat1();\n } else if (next() === "s" || next() === "S") {\n caseSensitive = true;\n eat1();\n }\n } else {\n value = "";\n while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === "."))\n value += eat1();\n if (value === "true") {\n value = true;\n } else if (value === "false") {\n value = false;\n } else {\n if (!allowUnquotedStrings) {\n value = +value;\n if (Number.isNaN(value))\n syntaxError("parsing attribute value");\n }\n }\n }\n skipSpaces();\n if (next() !== "]")\n syntaxError("parsing attribute value");\n eat1();\n if (operator !== "=" && typeof value !== "string")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);\n return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive };\n }\n const result = {\n name: "",\n attributes: []\n };\n result.name = readIdentifier();\n skipSpaces();\n while (next() === "[") {\n result.attributes.push(readAttribute());\n skipSpaces();\n }\n if (!EOL)\n syntaxError(void 0);\n if (!result.name && !result.attributes.length)\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - selector cannot be empty`);\n return result;\n}\n\n// packages/isomorphic/stringUtils.ts\nfunction escapeWithQuotes(text, char = "\'") {\n const stringified = JSON.stringify(text);\n const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\\\"/g, \'"\');\n if (char === "\'")\n return char + escapedText.replace(/[\']/g, "\\\\\'") + char;\n if (char === \'"\')\n return char + escapedText.replace(/["]/g, \'\\\\"\') + char;\n if (char === "`")\n return char + escapedText.replace(/[`]/g, "\\\\`") + char;\n throw new Error("Invalid escape char");\n}\nfunction toTitleCase(name) {\n return name.charAt(0).toUpperCase() + name.substring(1);\n}\nfunction toSnakeCase(name) {\n return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();\n}\nfunction quoteCSSAttributeValue(text) {\n return `"${text.replace(/["\\\\]/g, (char) => "\\\\" + char)}"`;\n}\nvar normalizedWhitespaceCache;\nfunction cacheNormalizedWhitespaces() {\n normalizedWhitespaceCache = /* @__PURE__ */ new Map();\n}\nfunction normalizeWhiteSpace(text) {\n let result = normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.get(text);\n if (result === void 0) {\n result = text.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " ");\n normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.set(text, result);\n }\n return result;\n}\nfunction normalizeEscapedRegexQuotes(source) {\n return source.replace(/(^|[^\\\\])(\\\\\\\\)*\\\\([\'"`])/g, "$1$2$3");\n}\nfunction escapeRegexForSelector(re) {\n if (re.unicode || re.unicodeSets)\n return String(re);\n return String(re).replace(/(^|[^\\\\])(\\\\\\\\)*(["\'`])/g, "$1$2\\\\$3").replace(/>>/g, "\\\\>\\\\>");\n}\nfunction escapeForTextSelector(text, exact) {\n if (typeof text !== "string")\n return escapeRegexForSelector(text);\n return `${JSON.stringify(text)}${exact ? "s" : "i"}`;\n}\nfunction escapeForAttributeSelector(value, exact) {\n if (typeof value !== "string")\n return escapeRegexForSelector(value);\n return `"${value.replace(/\\\\/g, "\\\\\\\\").replace(/["]/g, \'\\\\"\')}"${exact ? "s" : "i"}`;\n}\nfunction trimString(input, cap, suffix = "") {\n if (input.length <= cap)\n return input;\n const chars = [...input];\n if (chars.length > cap)\n return chars.slice(0, cap - suffix.length).join("") + suffix;\n return chars.join("");\n}\nfunction trimStringWithEllipsis(input, cap) {\n return trimString(input, cap, "\\u2026");\n}\nfunction escapeRegExp(s) {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");\n}\nfunction longestCommonSubstring(s1, s2) {\n const n = s1.length;\n const m = s2.length;\n let maxLen = 0;\n let endingIndex = 0;\n const dp = Array(n + 1).fill(null).map(() => Array(m + 1).fill(0));\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (s1[i - 1] === s2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n if (dp[i][j] > maxLen) {\n maxLen = dp[i][j];\n endingIndex = i;\n }\n }\n }\n }\n return s1.slice(endingIndex - maxLen, endingIndex);\n}\nvar ansiRegex = new RegExp("([\\\\u001B\\\\u009B][[\\\\]()#?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)|(?:(?:\\\\d{0,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~])))", "g");\n\n// packages/isomorphic/locatorGenerators.ts\nfunction asLocator(lang, selector, isFrameLocator = false) {\n return asLocators(lang, selector, isFrameLocator, 1)[0];\n}\nfunction asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) {\n try {\n return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize);\n } catch (e) {\n return [selector];\n }\n}\nfunction innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) {\n const parts = [...parsed.parts];\n const tokens = [];\n let nextBase = isFrameLocator ? "frame-locator" : "page";\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const base = nextBase;\n nextBase = "locator";\n if (part.name === "internal:describe")\n continue;\n if (part.name === "nth") {\n if (part.body === "0")\n tokens.push([factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0")]);\n else if (part.body === "-1")\n tokens.push([factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1")]);\n else\n tokens.push([factory.generateLocator(base, "nth", part.body)]);\n continue;\n }\n if (part.name === "visible") {\n tokens.push([factory.generateLocator(base, "visible", part.body), factory.generateLocator(base, "default", `visible=${part.body}`)]);\n continue;\n }\n if (part.name === "internal:text") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "text", text, { exact })]);\n continue;\n }\n if (part.name === "internal:has-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has-not-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-not-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner)));\n continue;\n }\n if (part.name === "internal:has-not") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner)));\n continue;\n }\n if (part.name === "internal:and") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner)));\n continue;\n }\n if (part.name === "internal:or") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner)));\n continue;\n }\n if (part.name === "internal:chain") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner)));\n continue;\n }\n if (part.name === "internal:label") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "label", text, { exact })]);\n continue;\n }\n if (part.name === "internal:role") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const options = { attrs: [] };\n for (const attr of attrSelector.attributes) {\n if (attr.name === "name") {\n if (options.exact !== void 0 && options.exact !== attr.caseSensitive)\n throw new Error(`Conflicting exactness in internal:role selector: ${stringifySelector({ parts: [part] })}`);\n options.exact = attr.caseSensitive;\n options.name = attr.value;\n } else if (attr.name === "description") {\n if (options.exact !== void 0 && options.exact !== attr.caseSensitive)\n throw new Error(`Conflicting exactness in internal:role selector: ${stringifySelector({ parts: [part] })}`);\n options.exact = attr.caseSensitive;\n options.description = attr.value;\n } else {\n if (attr.name === "level" && typeof attr.value === "string")\n attr.value = +attr.value;\n options.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value });\n }\n }\n tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]);\n continue;\n }\n if (part.name === "internal:testid") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { value } = attrSelector.attributes[0];\n tokens.push([factory.generateLocator(base, "test-id", value)]);\n continue;\n }\n if (part.name === "internal:attr") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { name, value, caseSensitive } = attrSelector.attributes[0];\n const text = value;\n const exact = !!caseSensitive;\n if (name === "placeholder") {\n tokens.push([factory.generateLocator(base, "placeholder", text, { exact })]);\n continue;\n }\n if (name === "alt") {\n tokens.push([factory.generateLocator(base, "alt", text, { exact })]);\n continue;\n }\n if (name === "title") {\n tokens.push([factory.generateLocator(base, "title", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:control" && part.body === "enter-frame") {\n const lastTokens = tokens[tokens.length - 1];\n const lastPart = parts[index - 1];\n const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")]));\n if (["xpath", "css"].includes(lastPart.name)) {\n transformed.push(\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })),\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] }, true))\n );\n }\n lastTokens.splice(0, lastTokens.length, ...transformed);\n nextBase = "frame-locator";\n continue;\n }\n const nextPart = parts[index + 1];\n const selectorPart = stringifySelector({ parts: [part] });\n const locatorPart = factory.generateLocator(base, "default", selectorPart);\n if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) {\n const { exact, text } = detectExact(nextPart.body);\n if (!exact) {\n const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text, { exact });\n const options = {};\n if (nextPart.name === "internal:has-text")\n options.hasText = text;\n else\n options.hasNotText = text;\n const combinedPart = factory.generateLocator(base, "default", selectorPart, options);\n tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]);\n index++;\n continue;\n }\n }\n let locatorPartWithEngine;\n if (["xpath", "css"].includes(part.name)) {\n const selectorPart2 = stringifySelector(\n { parts: [part] },\n /* forceEngineName */\n true\n );\n locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart2);\n }\n tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean));\n }\n return combineTokens(factory, tokens, maxOutputSize);\n}\nfunction combineTokens(factory, tokens, maxOutputSize) {\n const currentTokens = tokens.map(() => "");\n const result = [];\n const visit = (index) => {\n if (index === tokens.length) {\n result.push(factory.chainLocators(currentTokens));\n return result.length < maxOutputSize;\n }\n for (const taken of tokens[index]) {\n currentTokens[index] = taken;\n if (!visit(index + 1))\n return false;\n }\n return true;\n };\n visit(0);\n return result;\n}\nfunction detectExact(text) {\n let exact = false;\n const match = text.match(/^\\/(.*)\\/([igm]*)$/);\n if (match)\n return { text: new RegExp(match[1], match[2]) };\n if (text.endsWith(\'"\')) {\n text = JSON.parse(text);\n exact = true;\n } else if (text.endsWith(\'"s\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = true;\n } else if (text.endsWith(\'"i\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = false;\n }\n return { exact, text };\n}\nvar JavaScriptLocatorFactory = class {\n constructor(preferredQuote) {\n this.preferredQuote = preferredQuote;\n }\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `filter({ visible: ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`name: ${this.regexToSourceString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`name: ${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`description: ${this.regexToSourceString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description: ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact: true`);\n for (const { name, value } of options.attrs)\n attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : "";\n return `getByRole(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter({ hasText: ${this.toHasText(body)} })`;\n case "has-not-text":\n return `filter({ hasNotText: ${this.toHasText(body)} })`;\n case "has":\n return `filter({ has: ${body} })`;\n case "hasNot":\n return `filter({ hasNot: ${body} })`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToSourceString(re) {\n return normalizeEscapedRegexQuotes(String(re));\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToSourceString(body)})`;\n return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToSourceString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToSourceString(value);\n return this.quote(value);\n }\n quote(text) {\n var _a;\n return escapeWithQuotes(text, (_a = this.preferredQuote) != null ? _a : "\'");\n }\n};\nvar PythonLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frame_locator(${this.quote(body)})`;\n case "frame":\n return `content_frame`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first`;\n case "last":\n return `last`;\n case "visible":\n return `filter(visible=${body === "true" ? "True" : "False"})`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`name=${this.regexToString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`name=${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`description=${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description=${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact=True`);\n for (const { name, value } of options.attrs) {\n let valueString = typeof value === "string" ? this.quote(value) : value;\n if (typeof value === "boolean")\n valueString = value ? "True" : "False";\n attrs.push(`${toSnakeCase(name)}=${valueString}`);\n }\n const attrString = attrs.length ? `, ${attrs.join(", ")}` : "";\n return `get_by_role(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter(has_text=${this.toHasText(body)})`;\n case "has-not-text":\n return `filter(has_not_text=${this.toHasText(body)})`;\n case "has":\n return `filter(has=${body})`;\n case "hasNot":\n return `filter(has_not=${body})`;\n case "and":\n return `and_(${body})`;\n case "or":\n return `or_(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `get_by_test_id(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("get_by_text", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("get_by_alt_text", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("get_by_placeholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("get_by_label", body, !!options.exact);\n case "title":\n return this.toCallWithExact("get_by_title", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", re.IGNORECASE" : "";\n return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\\\\//, "/").replace(/"/g, \'\\\\"\')}"${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, exact=True)`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return `${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JavaLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n let clazz;\n switch (base) {\n case "page":\n clazz = "Page";\n break;\n case "frame-locator":\n clazz = "FrameLocator";\n break;\n case "locator":\n clazz = "Locator";\n break;\n }\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`.setName(${this.regexToString(options.name)})`);\n else if (typeof options.name === "string")\n attrs.push(`.setName(${this.quote(options.name)})`);\n if (isRegExp(options.description))\n attrs.push(`.setDescription(${this.regexToString(options.description)})`);\n else if (typeof options.description === "string")\n attrs.push(`.setDescription(${this.quote(options.description)})`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`.setExact(true)`);\n for (const { name, value } of options.attrs)\n attrs.push(`.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`);\n const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : "";\n return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`;\n case "has-text":\n return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`;\n case "has-not-text":\n return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`;\n case "has":\n return `filter(new ${clazz}.FilterOptions().setHas(${body}))`;\n case "hasNot":\n return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact(clazz, "getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", Pattern.CASE_INSENSITIVE" : "";\n return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(clazz, method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar CSharpLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`;\n return `Locator(${this.quote(body)})`;\n case "frame-locator":\n return `FrameLocator(${this.quote(body)})`;\n case "frame":\n return `ContentFrame`;\n case "nth":\n return `Nth(${body})`;\n case "first":\n return `First`;\n case "last":\n return `Last`;\n case "visible":\n return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`NameRegex = ${this.regexToString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`Name = ${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`DescriptionRegex = ${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`Description = ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`Exact = true`);\n for (const { name, value } of options.attrs)\n attrs.push(`${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : "";\n return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`;\n case "has-text":\n return `Filter(new() { ${this.toHasText(body)} })`;\n case "has-not-text":\n return `Filter(new() { ${this.toHasNotText(body)} })`;\n case "has":\n return `Filter(new() { Has = ${body} })`;\n case "hasNot":\n return `Filter(new() { HasNot = ${body} })`;\n case "and":\n return `And(${body})`;\n case "or":\n return `Or(${body})`;\n case "chain":\n return `Locator(${body})`;\n case "test-id":\n return `GetByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("GetByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("GetByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("GetByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("GetByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("GetByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", RegexOptions.IgnoreCase" : "";\n return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new() { Exact = true })`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return `HasTextRegex = ${this.regexToString(body)}`;\n return `HasText = ${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n toHasNotText(body) {\n if (isRegExp(body))\n return `HasNotTextRegex = ${this.regexToString(body)}`;\n return `HasNotText = ${this.quote(body)}`;\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JsonlLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n return JSON.stringify({\n kind,\n body,\n options\n });\n }\n chainLocators(locators) {\n const objects = locators.map((l) => JSON.parse(l));\n for (let i = 0; i < objects.length - 1; ++i)\n objects[i].next = objects[i + 1];\n return JSON.stringify(objects[0]);\n }\n};\nvar generators = {\n javascript: JavaScriptLocatorFactory,\n python: PythonLocatorFactory,\n java: JavaLocatorFactory,\n csharp: CSharpLocatorFactory,\n jsonl: JsonlLocatorFactory\n};\nfunction isRegExp(obj) {\n return obj instanceof RegExp;\n}\n\n// packages/isomorphic/locatorUtils.ts\nfunction getByAttributeTextSelector(attrName, text, options) {\n return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, (options == null ? void 0 : options.exact) || false)}]`;\n}\nfunction splitTestIdAttributeNames(testIdAttributeName) {\n return testIdAttributeName.split(",");\n}\nfunction encodeTestIdAttributeName(testIdAttributeName) {\n return testIdAttributeName.includes(",") ? JSON.stringify(testIdAttributeName) : testIdAttributeName;\n}\nfunction getByTestIdSelector(testIdAttributeName, testId) {\n return `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=${escapeForAttributeSelector(testId, true)}]`;\n}\nfunction getByLabelSelector(text, options) {\n return "internal:label=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByAltTextSelector(text, options) {\n return getByAttributeTextSelector("alt", text, options);\n}\nfunction getByTitleSelector(text, options) {\n return getByAttributeTextSelector("title", text, options);\n}\nfunction getByPlaceholderSelector(text, options) {\n return getByAttributeTextSelector("placeholder", text, options);\n}\nfunction getByTextSelector(text, options) {\n return "internal:text=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByRoleSelector(role, options = {}) {\n const props = [];\n if (options.checked !== void 0)\n props.push(["checked", String(options.checked)]);\n if (options.disabled !== void 0)\n props.push(["disabled", String(options.disabled)]);\n if (options.selected !== void 0)\n props.push(["selected", String(options.selected)]);\n if (options.expanded !== void 0)\n props.push(["expanded", String(options.expanded)]);\n if (options.includeHidden !== void 0)\n props.push(["include-hidden", String(options.includeHidden)]);\n if (options.level !== void 0)\n props.push(["level", String(options.level)]);\n if (options.name !== void 0)\n props.push(["name", escapeForAttributeSelector(options.name, !!options.exact)]);\n if (options.description !== void 0)\n props.push(["description", escapeForAttributeSelector(options.description, !!options.exact)]);\n if (options.pressed !== void 0)\n props.push(["pressed", String(options.pressed)]);\n return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`;\n}\n\n// packages/isomorphic/yaml.ts\nfunction yamlEscapeKeyIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return `\'` + str.replace(/\'/g, `\'\'`) + `\'`;\n}\nfunction yamlEscapeValueIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return \'"\' + str.replace(/[\\\\"\\x00-\\x1f\\x7f-\\x9f]/g, (c) => {\n switch (c) {\n case "\\\\":\n return "\\\\\\\\";\n case \'"\':\n return \'\\\\"\';\n case "\\b":\n return "\\\\b";\n case "\\f":\n return "\\\\f";\n case "\\n":\n return "\\\\n";\n case "\\r":\n return "\\\\r";\n case " ":\n return "\\\\t";\n default:\n const code = c.charCodeAt(0);\n return "\\\\x" + code.toString(16).padStart(2, "0");\n }\n }) + \'"\';\n}\nfunction yamlStringNeedsQuotes(str) {\n if (str.length === 0)\n return true;\n if (/^\\s|\\s$/.test(str))\n return true;\n if (/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f]/.test(str))\n return true;\n if (/^-/.test(str))\n return true;\n if (/[\\n:](\\s|$)/.test(str))\n return true;\n if (/\\s#/.test(str))\n return true;\n if (/[\\n\\r]/.test(str))\n return true;\n if (/^[&*\\],?!>|@"\'#%]/.test(str))\n return true;\n if (/[{}`]/.test(str))\n return true;\n if (/^\\[/.test(str))\n return true;\n if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null"].includes(str.toLowerCase()))\n return true;\n return false;\n}\n\n// packages/injected/src/domUtils.ts\nvar globalOptions = {};\nfunction setGlobalOptions(options) {\n globalOptions = options;\n}\nfunction isInsideScope(scope, element) {\n while (element) {\n if (scope.contains(element))\n return true;\n element = enclosingShadowHost(element);\n }\n return false;\n}\nfunction parentElementOrShadowHost(element) {\n if (element.parentElement)\n return element.parentElement;\n if (!element.parentNode)\n return;\n if (element.parentNode.nodeType === 11 && element.parentNode.host)\n return element.parentNode.host;\n}\nfunction enclosingShadowRootOrDocument(element) {\n let node = element;\n while (node.parentNode)\n node = node.parentNode;\n if (node.nodeType === 11 || node.nodeType === 9)\n return node;\n}\nfunction enclosingShadowHost(element) {\n while (element.parentElement)\n element = element.parentElement;\n return parentElementOrShadowHost(element);\n}\nfunction closestCrossShadow(element, css, scope) {\n while (element) {\n const closest = element.closest(css);\n if (scope && closest !== scope && (closest == null ? void 0 : closest.contains(scope)))\n return;\n if (closest)\n return closest;\n element = enclosingShadowHost(element);\n }\n}\nfunction getElementComputedStyle(element, pseudo) {\n const cache = pseudo === "::before" ? cacheStyleBefore : pseudo === "::after" ? cacheStyleAfter : cacheStyle;\n if (cache && cache.has(element))\n return cache.get(element);\n const style = element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : void 0;\n cache == null ? void 0 : cache.set(element, style);\n return style;\n}\nfunction isElementStyleVisibilityVisible(element, style) {\n style = style != null ? style : getElementComputedStyle(element);\n if (!style)\n return true;\n if (Element.prototype.checkVisibility && globalOptions.browserNameForWorkarounds !== "webkit") {\n if (!element.checkVisibility())\n return false;\n } else {\n const detailsOrSummary = element.closest("details,summary");\n if (detailsOrSummary !== element && (detailsOrSummary == null ? void 0 : detailsOrSummary.nodeName) === "DETAILS" && !detailsOrSummary.open)\n return false;\n }\n if (style.visibility !== "visible")\n return false;\n return true;\n}\nfunction computeBox(element) {\n const style = getElementComputedStyle(element);\n if (!style)\n return { visible: true, inline: false };\n const cursor = style.cursor;\n if (style.display === "contents") {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && isElementVisible(child))\n return { visible: true, inline: false, cursor };\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return { visible: true, inline: true, cursor };\n }\n return { visible: false, inline: false, cursor };\n }\n if (!isElementStyleVisibilityVisible(element, style))\n return { cursor, visible: false, inline: false };\n const rect = element.getBoundingClientRect();\n return { cursor, visible: rect.width > 0 && rect.height > 0, inline: style.display === "inline" };\n}\nfunction isElementVisible(element) {\n return computeBox(element).visible;\n}\nfunction isVisibleTextNode(node) {\n const range = node.ownerDocument.createRange();\n range.selectNode(node);\n const rect = range.getBoundingClientRect();\n return rect.width > 0 && rect.height > 0;\n}\nfunction elementSafeTagName(element) {\n const tagName = element.tagName;\n if (typeof tagName === "string")\n return tagName.toUpperCase();\n if (element instanceof HTMLFormElement)\n return "FORM";\n return element.tagName.toUpperCase();\n}\nvar cacheStyle;\nvar cacheStyleBefore;\nvar cacheStyleAfter;\nvar cachesCounter = 0;\nfunction beginDOMCaches() {\n ++cachesCounter;\n cacheStyle != null ? cacheStyle : cacheStyle = /* @__PURE__ */ new Map();\n cacheStyleBefore != null ? cacheStyleBefore : cacheStyleBefore = /* @__PURE__ */ new Map();\n cacheStyleAfter != null ? cacheStyleAfter : cacheStyleAfter = /* @__PURE__ */ new Map();\n}\nfunction endDOMCaches() {\n if (!--cachesCounter) {\n cacheStyle = void 0;\n cacheStyleBefore = void 0;\n cacheStyleAfter = void 0;\n }\n}\n\n// packages/injected/src/roleUtils.ts\nfunction hasExplicitAccessibleName(e) {\n return e.hasAttribute("aria-label") || e.hasAttribute("aria-labelledby");\n}\nvar kAncestorPreventingLandmark = "article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]";\nvar kGlobalAriaAttributes = [\n ["aria-atomic", void 0],\n ["aria-busy", void 0],\n ["aria-controls", void 0],\n ["aria-current", void 0],\n ["aria-describedby", void 0],\n ["aria-details", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-disabled\', undefined],\n ["aria-dropeffect", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-errormessage\', undefined],\n ["aria-flowto", void 0],\n ["aria-grabbed", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-haspopup\', undefined],\n ["aria-hidden", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-invalid\', undefined],\n ["aria-keyshortcuts", void 0],\n ["aria-label", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-labelledby", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-live", void 0],\n ["aria-owns", void 0],\n ["aria-relevant", void 0],\n ["aria-roledescription", ["generic"]]\n];\nfunction hasGlobalAriaAttribute(element, forRole) {\n return kGlobalAriaAttributes.some(([attr, prohibited]) => {\n return !(prohibited == null ? void 0 : prohibited.includes(forRole || "")) && element.hasAttribute(attr);\n });\n}\nfunction hasTabIndex(element) {\n return !Number.isNaN(Number(String(element.getAttribute("tabindex"))));\n}\nfunction isFocusable(element) {\n return !isNativelyDisabled(element) && (isNativelyFocusable(element) || hasTabIndex(element));\n}\nfunction isNativelyFocusable(element) {\n const tagName = elementSafeTagName(element);\n if (["BUTTON", "DETAILS", "SELECT", "TEXTAREA"].includes(tagName))\n return true;\n if (tagName === "A" || tagName === "AREA")\n return element.hasAttribute("href");\n if (tagName === "INPUT")\n return !element.hidden;\n return false;\n}\nvar kImplicitRoleByTagName = {\n "A": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "AREA": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "ARTICLE": () => "article",\n "ASIDE": () => "complementary",\n "BLOCKQUOTE": () => "blockquote",\n "BUTTON": () => "button",\n "CAPTION": () => "caption",\n "CODE": () => "code",\n "DATALIST": () => "listbox",\n "DD": () => "definition",\n "DEL": () => "deletion",\n "DETAILS": () => "group",\n "DFN": () => "term",\n "DIALOG": () => "dialog",\n "DT": () => "term",\n "EM": () => "emphasis",\n "FIELDSET": () => "group",\n "FIGURE": () => "figure",\n "FOOTER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "contentinfo",\n "FORM": (e) => hasExplicitAccessibleName(e) ? "form" : null,\n "H1": () => "heading",\n "H2": () => "heading",\n "H3": () => "heading",\n "H4": () => "heading",\n "H5": () => "heading",\n "H6": () => "heading",\n "HEADER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "banner",\n "HR": () => "separator",\n "HTML": () => "document",\n "IMG": (e) => e.getAttribute("alt") === "" && !e.getAttribute("title") && !hasGlobalAriaAttribute(e) && !hasTabIndex(e) ? "presentation" : "img",\n "INPUT": (e) => {\n const type = e.type.toLowerCase();\n if (type === "search")\n return e.hasAttribute("list") ? "combobox" : "searchbox";\n if (["email", "tel", "text", "url", ""].includes(type)) {\n const list = getIdRefs(e, e.getAttribute("list"))[0];\n return list && elementSafeTagName(list) === "DATALIST" ? "combobox" : "textbox";\n }\n if (type === "hidden")\n return null;\n if (type === "file")\n return "button";\n return inputTypeToRole[type] || "textbox";\n },\n "INS": () => "insertion",\n "LI": () => "listitem",\n "MAIN": () => "main",\n "MARK": () => "mark",\n "MATH": () => "math",\n "MENU": () => "list",\n "METER": () => "meter",\n "NAV": () => "navigation",\n "OL": () => "list",\n "OPTGROUP": () => "group",\n "OPTION": () => "option",\n "OUTPUT": () => "status",\n "P": () => "paragraph",\n "PROGRESS": () => "progressbar",\n "SEARCH": () => "search",\n "SECTION": (e) => hasExplicitAccessibleName(e) ? "region" : null,\n "SELECT": (e) => e.hasAttribute("multiple") || e.size > 1 ? "listbox" : "combobox",\n "STRONG": () => "strong",\n "SUB": () => "subscript",\n "SUP": () => "superscript",\n // For we default to Chrome behavior:\n // - Chrome reports \'img\'.\n // - Firefox reports \'diagram\' that is not in official ARIA spec yet.\n // - Safari reports \'no role\', but still computes accessible name.\n "SVG": () => "img",\n "TABLE": () => "table",\n "TBODY": () => "rowgroup",\n "TD": (e) => {\n const table = closestCrossShadow(e, "table");\n const role = table ? getExplicitAriaRole(table) : "";\n return role === "grid" || role === "treegrid" ? "gridcell" : "cell";\n },\n "TEXTAREA": () => "textbox",\n "TFOOT": () => "rowgroup",\n "TH": (e) => {\n const scope = e.getAttribute("scope");\n if (scope === "col" || scope === "colgroup")\n return "columnheader";\n if (scope === "row" || scope === "rowgroup")\n return "rowheader";\n const nextSibling = e.nextElementSibling;\n const prevSibling = e.previousElementSibling;\n const row = !!e.parentElement && elementSafeTagName(e.parentElement) === "TR" ? e.parentElement : void 0;\n if (!nextSibling && !prevSibling) {\n if (row) {\n const table = closestCrossShadow(row, "table");\n if (table && table.rows.length <= 1)\n return null;\n }\n return "columnheader";\n }\n if (isHeaderCell(nextSibling) && isHeaderCell(prevSibling))\n return "columnheader";\n if (isNonEmptyDataCell(nextSibling) || isNonEmptyDataCell(prevSibling))\n return "rowheader";\n return "columnheader";\n },\n "THEAD": () => "rowgroup",\n "TIME": () => "time",\n "TR": () => "row",\n "UL": () => "list"\n};\nfunction isHeaderCell(element) {\n return !!element && elementSafeTagName(element) === "TH";\n}\nfunction isNonEmptyDataCell(element) {\n var _a;\n if (!element || elementSafeTagName(element) !== "TD")\n return false;\n return !!(((_a = element.textContent) == null ? void 0 : _a.trim()) || element.children.length > 0);\n}\nvar kPresentationInheritanceParents = {\n "DD": ["DL", "DIV"],\n "DIV": ["DL"],\n "DT": ["DL", "DIV"],\n "LI": ["OL", "UL"],\n "TBODY": ["TABLE"],\n "TD": ["TR"],\n "TFOOT": ["TABLE"],\n "TH": ["TR"],\n "THEAD": ["TABLE"],\n "TR": ["THEAD", "TBODY", "TFOOT", "TABLE"]\n};\nfunction getImplicitAriaRole(element) {\n var _a;\n const implicitRole = ((_a = kImplicitRoleByTagName[elementSafeTagName(element)]) == null ? void 0 : _a.call(kImplicitRoleByTagName, element)) || "";\n if (!implicitRole)\n return null;\n let ancestor = element;\n while (ancestor) {\n const parent = parentElementOrShadowHost(ancestor);\n const parents = kPresentationInheritanceParents[elementSafeTagName(ancestor)];\n if (!parents || !parent || !parents.includes(elementSafeTagName(parent)))\n break;\n const parentExplicitRole = getExplicitAriaRole(parent);\n if ((parentExplicitRole === "none" || parentExplicitRole === "presentation") && !hasPresentationConflictResolution(parent, parentExplicitRole))\n return parentExplicitRole;\n ancestor = parent;\n }\n return implicitRole;\n}\nvar validRoles = [\n "alert",\n "alertdialog",\n "application",\n "article",\n "banner",\n "blockquote",\n "button",\n "caption",\n "cell",\n "checkbox",\n "code",\n "columnheader",\n "combobox",\n "complementary",\n "contentinfo",\n "definition",\n "deletion",\n "dialog",\n "directory",\n "document",\n "emphasis",\n "feed",\n "figure",\n "form",\n "generic",\n "grid",\n "gridcell",\n "group",\n "heading",\n "img",\n "insertion",\n "link",\n "list",\n "listbox",\n "listitem",\n "log",\n "main",\n "mark",\n "marquee",\n "math",\n "meter",\n "menu",\n "menubar",\n "menuitem",\n "menuitemcheckbox",\n "menuitemradio",\n "navigation",\n "none",\n "note",\n "option",\n "paragraph",\n "presentation",\n "progressbar",\n "radio",\n "radiogroup",\n "region",\n "row",\n "rowgroup",\n "rowheader",\n "scrollbar",\n "search",\n "searchbox",\n "separator",\n "slider",\n "spinbutton",\n "status",\n "strong",\n "subscript",\n "superscript",\n "switch",\n "tab",\n "table",\n "tablist",\n "tabpanel",\n "term",\n "textbox",\n "time",\n "timer",\n "toolbar",\n "tooltip",\n "tree",\n "treegrid",\n "treeitem"\n];\nfunction getExplicitAriaRole(element) {\n const roles = (element.getAttribute("role") || "").split(" ").map((role) => role.trim());\n return roles.find((role) => validRoles.includes(role)) || null;\n}\nfunction hasPresentationConflictResolution(element, role) {\n return hasGlobalAriaAttribute(element, role) || isFocusable(element);\n}\nfunction getAriaRole(element) {\n const explicitRole = getExplicitAriaRole(element);\n if (!explicitRole)\n return getImplicitAriaRole(element);\n if (explicitRole === "none" || explicitRole === "presentation") {\n const implicitRole = getImplicitAriaRole(element);\n if (hasPresentationConflictResolution(element, implicitRole))\n return implicitRole;\n }\n return explicitRole;\n}\nfunction getAriaBoolean(attr) {\n return attr === null ? void 0 : attr.toLowerCase() === "true";\n}\nfunction isElementIgnoredForAria(element) {\n return ["STYLE", "SCRIPT", "NOSCRIPT", "TEMPLATE"].includes(elementSafeTagName(element));\n}\nfunction isElementHiddenForAria(element) {\n if (isElementIgnoredForAria(element))\n return true;\n const style = getElementComputedStyle(element);\n const isSlot = element.nodeName === "SLOT";\n if ((style == null ? void 0 : style.display) === "contents" && !isSlot) {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && !isElementHiddenForAria(child))\n return false;\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return false;\n }\n return true;\n }\n const isOptionInsideSelect = element.nodeName === "OPTION" && !!element.closest("select");\n if (!isOptionInsideSelect && !isSlot && !isElementStyleVisibilityVisible(element, style))\n return true;\n return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element);\n}\nfunction belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element) {\n let hidden = cacheIsHidden == null ? void 0 : cacheIsHidden.get(element);\n if (hidden === void 0) {\n hidden = false;\n if (element.parentElement && element.parentElement.shadowRoot && !element.assignedSlot)\n hidden = true;\n if (!hidden) {\n const style = getElementComputedStyle(element);\n hidden = !style || style.display === "none" || getAriaBoolean(element.getAttribute("aria-hidden")) === true;\n }\n if (!hidden) {\n const parent = parentElementOrShadowHost(element);\n if (parent)\n hidden = belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent);\n }\n cacheIsHidden == null ? void 0 : cacheIsHidden.set(element, hidden);\n }\n return hidden;\n}\nfunction getIdRefs(element, ref) {\n if (!ref)\n return [];\n const root = enclosingShadowRootOrDocument(element);\n if (!root)\n return [];\n try {\n const ids = ref.split(" ").filter((id) => !!id);\n const result = [];\n for (const id of ids) {\n const firstElement = root.querySelector("#" + CSS.escape(id));\n if (firstElement && !result.includes(firstElement))\n result.push(firstElement);\n }\n return result;\n } catch (e) {\n return [];\n }\n}\nfunction trimFlatString(s) {\n return s.trim();\n}\nfunction asFlatString(s) {\n return s.split("\\xA0").map((chunk) => chunk.replace(/\\r\\n/g, "\\n").replace(/[\\u200b\\u00ad]/g, "").replace(/\\s\\s*/g, " ")).join("\\xA0").trim();\n}\nfunction queryInAriaOwned(element, selector) {\n const result = [...element.querySelectorAll(selector)];\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns"))) {\n if (owned.matches(selector))\n result.push(owned);\n result.push(...owned.querySelectorAll(selector));\n }\n return result;\n}\nfunction getCSSContent(element, pseudo) {\n const cache = pseudo === "::before" ? cachePseudoContentBefore : pseudo === "::after" ? cachePseudoContentAfter : cachePseudoContent;\n if (cache == null ? void 0 : cache.has(element))\n return cache == null ? void 0 : cache.get(element);\n const style = getElementComputedStyle(element, pseudo);\n let content;\n if (style) {\n const contentValue = style.content;\n if (contentValue && contentValue !== "none" && contentValue !== "normal") {\n if (style.display !== "none" && style.visibility !== "hidden") {\n content = parseCSSContentPropertyAsString(element, contentValue, !!pseudo);\n }\n }\n }\n if (pseudo && content !== void 0) {\n const display = (style == null ? void 0 : style.display) || "inline";\n if (display !== "inline")\n content = " " + content + " ";\n }\n if (cache)\n cache.set(element, content);\n return content;\n}\nfunction parseCSSContentPropertyAsString(element, content, isPseudo) {\n if (!content || content === "none" || content === "normal") {\n return;\n }\n try {\n let tokens = tokenize(content).filter((token) => !(token instanceof WhitespaceToken));\n const delimIndex = tokens.findIndex((token) => token instanceof DelimToken && token.value === "/");\n if (delimIndex !== -1) {\n tokens = tokens.slice(delimIndex + 1);\n } else if (!isPseudo) {\n return;\n }\n const accumulated = [];\n let index = 0;\n while (index < tokens.length) {\n if (tokens[index] instanceof StringToken) {\n accumulated.push(tokens[index].value);\n index++;\n } else if (index + 2 < tokens.length && tokens[index] instanceof FunctionToken && tokens[index].value === "attr" && tokens[index + 1] instanceof IdentToken && tokens[index + 2] instanceof CloseParenToken) {\n const attrName = tokens[index + 1].value;\n accumulated.push(element.getAttribute(attrName) || "");\n index += 3;\n } else {\n return;\n }\n }\n return accumulated.join("");\n } catch {\n }\n}\nfunction getAriaLabelledByElements(element) {\n const ref = element.getAttribute("aria-labelledby");\n if (ref === null)\n return null;\n const refs = getIdRefs(element, ref);\n return refs.length ? refs : null;\n}\nfunction allowsNameFromContent(role, targetDescendant) {\n const alwaysAllowsNameFromContent = ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem"].includes(role);\n const descendantAllowsNameFromContent = targetDescendant && ["", "caption", "code", "contentinfo", "definition", "deletion", "emphasis", "insertion", "list", "listitem", "mark", "none", "paragraph", "presentation", "region", "row", "rowgroup", "section", "strong", "subscript", "superscript", "table", "term", "time"].includes(role);\n return alwaysAllowsNameFromContent || descendantAllowsNameFromContent;\n}\nfunction getElementAccessibleName(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleNameHidden : cacheAccessibleName;\n let accessibleName = cache == null ? void 0 : cache.get(element);\n if (accessibleName === void 0) {\n accessibleName = "";\n const elementProhibitsNaming = ["caption", "code", "definition", "deletion", "emphasis", "generic", "insertion", "mark", "paragraph", "presentation", "strong", "subscript", "suggestion", "superscript", "term", "time"].includes(getAriaRole(element) || "");\n if (!elementProhibitsNaming) {\n accessibleName = asFlatString(getTextAlternativeInternal(element, {\n includeHidden,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInTargetElement: "self"\n }));\n }\n cache == null ? void 0 : cache.set(element, accessibleName);\n }\n return accessibleName;\n}\nfunction getElementAccessibleDescription(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleDescriptionHidden : cacheAccessibleDescription;\n let accessibleDescription = cache == null ? void 0 : cache.get(element);\n if (accessibleDescription === void 0) {\n accessibleDescription = "";\n if (element.hasAttribute("aria-describedby")) {\n const describedBy = getIdRefs(element, element.getAttribute("aria-describedby"));\n accessibleDescription = asFlatString(describedBy.map((ref) => getTextAlternativeInternal(ref, {\n includeHidden,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: ref, hidden: isElementHiddenForAria(ref) }\n })).join(" "));\n } else if (element.hasAttribute("aria-description")) {\n accessibleDescription = asFlatString(element.getAttribute("aria-description") || "");\n } else {\n accessibleDescription = asFlatString(element.getAttribute("title") || "");\n }\n cache == null ? void 0 : cache.set(element, accessibleDescription);\n }\n return accessibleDescription;\n}\nvar kAriaInvalidRoles = [\n "application",\n "checkbox",\n "columnheader",\n "combobox",\n "gridcell",\n "listbox",\n "radiogroup",\n "rowheader",\n "searchbox",\n "slider",\n "spinbutton",\n "switch",\n "textbox",\n "tree"\n];\nfunction getAriaInvalid(element) {\n const ariaInvalid = element.getAttribute("aria-invalid");\n if (!ariaInvalid || ariaInvalid.trim() === "" || ariaInvalid.toLocaleLowerCase() === "false")\n return "false";\n if (ariaInvalid === "true" || ariaInvalid === "grammar" || ariaInvalid === "spelling")\n return ariaInvalid;\n return "true";\n}\nfunction getValidityInvalid(element) {\n if ("validity" in element) {\n const validity = element.validity;\n return (validity == null ? void 0 : validity.valid) === false;\n }\n return false;\n}\nfunction getElementAccessibleErrorMessage(element) {\n const cache = cacheAccessibleErrorMessage;\n let accessibleErrorMessage = cacheAccessibleErrorMessage == null ? void 0 : cacheAccessibleErrorMessage.get(element);\n if (accessibleErrorMessage === void 0) {\n accessibleErrorMessage = "";\n const isAriaInvalid = getAriaInvalid(element) !== "false";\n const isValidityInvalid = getValidityInvalid(element);\n if (isAriaInvalid || isValidityInvalid) {\n const errorMessageId = element.getAttribute("aria-errormessage");\n const errorMessages = getIdRefs(element, errorMessageId);\n const parts = errorMessages.map((errorMessage) => asFlatString(\n getTextAlternativeInternal(errorMessage, {\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: errorMessage, hidden: isElementHiddenForAria(errorMessage) }\n })\n ));\n accessibleErrorMessage = parts.join(" ").trim();\n }\n cache == null ? void 0 : cache.set(element, accessibleErrorMessage);\n }\n return accessibleErrorMessage;\n}\nfunction getTextAlternativeInternal(element, options) {\n var _a, _b, _c, _d;\n if (options.visitedElements.has(element))\n return "";\n const childOptions = {\n ...options,\n embeddedInTargetElement: options.embeddedInTargetElement === "self" ? "descendant" : options.embeddedInTargetElement\n };\n if (!options.includeHidden) {\n const isEmbeddedInHiddenReferenceTraversal = !!((_a = options.embeddedInLabelledBy) == null ? void 0 : _a.hidden) || !!((_b = options.embeddedInDescribedBy) == null ? void 0 : _b.hidden) || !!((_c = options.embeddedInNativeTextAlternative) == null ? void 0 : _c.hidden) || !!((_d = options.embeddedInLabel) == null ? void 0 : _d.hidden);\n if (isElementIgnoredForAria(element) || !isEmbeddedInHiddenReferenceTraversal && isElementHiddenForAria(element)) {\n options.visitedElements.add(element);\n return "";\n }\n }\n const labelledBy = getAriaLabelledByElements(element);\n if (!options.embeddedInLabelledBy) {\n const accessibleName = (labelledBy || []).map((ref) => getTextAlternativeInternal(ref, {\n ...options,\n embeddedInLabelledBy: { element: ref, hidden: isElementHiddenForAria(ref) },\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0,\n embeddedInLabel: void 0,\n embeddedInNativeTextAlternative: void 0\n })).join(" ");\n if (accessibleName)\n return accessibleName;\n }\n const role = getAriaRole(element) || "";\n const tagName = elementSafeTagName(element);\n if (!!options.embeddedInLabel || !!options.embeddedInLabelledBy || options.embeddedInTargetElement === "descendant") {\n const isOwnLabel = [...element.labels || []].includes(element);\n const isOwnLabelledBy = (labelledBy || []).includes(element);\n if (!isOwnLabel && !isOwnLabelledBy) {\n if (role === "textbox") {\n options.visitedElements.add(element);\n if (tagName === "INPUT" || tagName === "TEXTAREA")\n return element.value;\n return element.textContent || "";\n }\n if (["combobox", "listbox"].includes(role)) {\n options.visitedElements.add(element);\n let selectedOptions;\n if (tagName === "SELECT") {\n selectedOptions = [...element.selectedOptions];\n if (!selectedOptions.length && element.options.length)\n selectedOptions.push(element.options[0]);\n } else {\n const listbox = role === "combobox" ? queryInAriaOwned(element, "*").find((e) => getAriaRole(e) === "listbox") : element;\n selectedOptions = listbox ? queryInAriaOwned(listbox, \'[aria-selected="true"]\').filter((e) => getAriaRole(e) === "option") : [];\n }\n if (!selectedOptions.length && tagName === "INPUT") {\n return element.value;\n }\n return selectedOptions.map((option) => getTextAlternativeInternal(option, childOptions)).join(" ");\n }\n if (["progressbar", "scrollbar", "slider", "spinbutton", "meter"].includes(role)) {\n options.visitedElements.add(element);\n if (element.hasAttribute("aria-valuetext"))\n return element.getAttribute("aria-valuetext") || "";\n if (element.hasAttribute("aria-valuenow"))\n return element.getAttribute("aria-valuenow") || "";\n return element.getAttribute("value") || "";\n }\n if (["menu"].includes(role)) {\n options.visitedElements.add(element);\n return "";\n }\n }\n }\n const ariaLabel = element.getAttribute("aria-label") || "";\n if (trimFlatString(ariaLabel)) {\n options.visitedElements.add(element);\n return ariaLabel;\n }\n if (!["presentation", "none"].includes(role)) {\n if (tagName === "INPUT" && ["button", "submit", "reset"].includes(element.type)) {\n options.visitedElements.add(element);\n const value = element.value || "";\n if (trimFlatString(value))\n return value;\n if (element.type === "submit")\n return "Submit";\n if (element.type === "reset")\n return "Reset";\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "INPUT" && element.type === "file") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return "Choose File";\n }\n if (tagName === "INPUT" && element.type === "image") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return alt;\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return title;\n return "Submit";\n }\n if (!labelledBy && tagName === "BUTTON") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n }\n if (!labelledBy && tagName === "OUTPUT") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return element.getAttribute("title") || "";\n }\n if (!labelledBy && (tagName === "TEXTAREA" || tagName === "SELECT" || tagName === "INPUT")) {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const usePlaceholder = tagName === "INPUT" && ["text", "password", "search", "tel", "email", "url"].includes(element.type) || tagName === "TEXTAREA";\n const placeholder = element.getAttribute("placeholder") || "";\n const title = element.getAttribute("title") || "";\n if (!usePlaceholder || title)\n return title;\n return placeholder;\n }\n if (!labelledBy && tagName === "FIELDSET") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "LEGEND") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (!labelledBy && tagName === "FIGURE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "FIGCAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "IMG") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return alt;\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "TABLE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "CAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const summary = element.getAttribute("summary") || "";\n if (summary)\n return summary;\n }\n if (tagName === "AREA") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return alt;\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "SVG" || element.ownerSVGElement) {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "TITLE" && child.ownerSVGElement) {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInLabelledBy: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n }\n if (element.ownerSVGElement && tagName === "A") {\n const title = element.getAttribute("xlink:title") || "";\n if (trimFlatString(title)) {\n options.visitedElements.add(element);\n return title;\n }\n }\n }\n const shouldNameFromContentForSummary = tagName === "SUMMARY" && !["presentation", "none"].includes(role);\n if (allowsNameFromContent(role, options.embeddedInTargetElement === "descendant") || shouldNameFromContentForSummary || !!options.embeddedInLabelledBy || !!options.embeddedInDescribedBy || !!options.embeddedInLabel || !!options.embeddedInNativeTextAlternative) {\n options.visitedElements.add(element);\n const accessibleName = innerAccumulatedElementText(element, childOptions);\n const maybeTrimmedAccessibleName = options.embeddedInTargetElement === "self" ? trimFlatString(accessibleName) : accessibleName;\n if (maybeTrimmedAccessibleName)\n return accessibleName;\n }\n if (!["presentation", "none"].includes(role) || tagName === "IFRAME") {\n options.visitedElements.add(element);\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return title;\n }\n options.visitedElements.add(element);\n return "";\n}\nfunction innerAccumulatedElementText(element, options) {\n const tokens = [];\n const visit = (node, skipSlotted) => {\n var _a;\n if (skipSlotted && node.assignedSlot)\n return;\n if (node.nodeType === 1) {\n const display = ((_a = getElementComputedStyle(node)) == null ? void 0 : _a.display) || "inline";\n let token = getTextAlternativeInternal(node, options);\n if (display !== "inline" || node.nodeName === "BR")\n token = " " + token + " ";\n tokens.push(token);\n } else if (node.nodeType === 3) {\n tokens.push(node.textContent || "");\n }\n };\n tokens.push(getCSSContent(element, "::before") || "");\n const content = getCSSContent(element);\n if (content !== void 0) {\n tokens.push(content);\n } else {\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(child, false);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling)\n visit(child, true);\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(child, true);\n }\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns")))\n visit(owned, true);\n }\n }\n tokens.push(getCSSContent(element, "::after") || "");\n return tokens.join("");\n}\nvar kAriaSelectedRoles = ["gridcell", "option", "row", "tab", "rowheader", "columnheader", "treeitem"];\nfunction getAriaSelected(element) {\n if (elementSafeTagName(element) === "OPTION")\n return element.selected;\n if (kAriaSelectedRoles.includes(getAriaRole(element) || ""))\n return getAriaBoolean(element.getAttribute("aria-selected")) === true;\n return false;\n}\nvar kAriaCheckedRoles = ["checkbox", "menuitemcheckbox", "option", "radio", "switch", "menuitemradio", "treeitem"];\nfunction getAriaChecked(element) {\n const result = getChecked(element, true);\n return result === "error" ? false : result;\n}\nfunction getCheckedAllowMixed(element) {\n return getChecked(element, true);\n}\nfunction getCheckedWithoutMixed(element) {\n const result = getChecked(element, false);\n return result;\n}\nfunction getChecked(element, allowMixed) {\n const tagName = elementSafeTagName(element);\n if (allowMixed && tagName === "INPUT" && element.indeterminate)\n return "mixed";\n if (tagName === "INPUT" && ["checkbox", "radio"].includes(element.type))\n return element.checked;\n if (kAriaCheckedRoles.includes(getAriaRole(element) || "")) {\n const checked = element.getAttribute("aria-checked");\n if (checked === "true")\n return true;\n if (allowMixed && checked === "mixed")\n return "mixed";\n return false;\n }\n return "error";\n}\nvar kAriaReadonlyRoles = ["checkbox", "combobox", "grid", "gridcell", "listbox", "radiogroup", "slider", "spinbutton", "textbox", "columnheader", "rowheader", "searchbox", "switch", "treegrid"];\nfunction getReadonly(element) {\n const tagName = elementSafeTagName(element);\n if (["INPUT", "TEXTAREA", "SELECT"].includes(tagName))\n return element.hasAttribute("readonly");\n if (kAriaReadonlyRoles.includes(getAriaRole(element) || ""))\n return element.getAttribute("aria-readonly") === "true";\n if (element.isContentEditable)\n return false;\n return "error";\n}\nvar kAriaPressedRoles = ["button"];\nfunction getAriaPressed(element) {\n if (kAriaPressedRoles.includes(getAriaRole(element) || "")) {\n const pressed = element.getAttribute("aria-pressed");\n if (pressed === "true")\n return true;\n if (pressed === "mixed")\n return "mixed";\n }\n return false;\n}\nvar kAriaExpandedRoles = ["application", "button", "checkbox", "combobox", "gridcell", "link", "listbox", "menuitem", "row", "rowheader", "tab", "treeitem", "columnheader", "menuitemcheckbox", "menuitemradio", "rowheader", "switch"];\nfunction getAriaExpanded(element) {\n if (elementSafeTagName(element) === "DETAILS")\n return element.open;\n if (kAriaExpandedRoles.includes(getAriaRole(element) || "")) {\n const expanded = element.getAttribute("aria-expanded");\n if (expanded === null)\n return void 0;\n if (expanded === "true")\n return true;\n return false;\n }\n return void 0;\n}\nvar kAriaLevelRoles = ["heading", "listitem", "row", "treeitem"];\nfunction getAriaLevel(element) {\n const native = { "H1": 1, "H2": 2, "H3": 3, "H4": 4, "H5": 5, "H6": 6 }[elementSafeTagName(element)];\n if (native)\n return native;\n if (kAriaLevelRoles.includes(getAriaRole(element) || "")) {\n const attr = element.getAttribute("aria-level");\n const value = attr === null ? Number.NaN : Number(attr);\n if (Number.isInteger(value) && value >= 1)\n return value;\n }\n return 0;\n}\nvar kAriaDisabledRoles = ["application", "button", "composite", "gridcell", "group", "input", "link", "menuitem", "scrollbar", "separator", "tab", "checkbox", "columnheader", "combobox", "grid", "listbox", "menu", "menubar", "menuitemcheckbox", "menuitemradio", "option", "radio", "radiogroup", "row", "rowheader", "searchbox", "select", "slider", "spinbutton", "switch", "tablist", "textbox", "toolbar", "tree", "treegrid", "treeitem"];\nfunction getAriaDisabled(element) {\n return isNativelyDisabled(element) || hasExplicitAriaDisabled(element);\n}\nfunction isNativelyDisabled(element) {\n const isNativeFormControl = ["BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "OPTGROUP"].includes(elementSafeTagName(element));\n return isNativeFormControl && (element.hasAttribute("disabled") || belongsToDisabledOptGroup(element) || belongsToDisabledFieldSet(element));\n}\nfunction belongsToDisabledOptGroup(element) {\n return elementSafeTagName(element) === "OPTION" && !!element.closest("OPTGROUP[DISABLED]");\n}\nfunction belongsToDisabledFieldSet(element) {\n const fieldSetElement = element == null ? void 0 : element.closest("FIELDSET[DISABLED]");\n if (!fieldSetElement)\n return false;\n const legendElement = fieldSetElement.querySelector(":scope > LEGEND");\n return !legendElement || !legendElement.contains(element);\n}\nfunction hasExplicitAriaDisabled(element, isAncestor = false) {\n if (!element)\n return false;\n if (isAncestor || kAriaDisabledRoles.includes(getAriaRole(element) || "")) {\n const attribute = (element.getAttribute("aria-disabled") || "").toLowerCase();\n if (attribute === "true")\n return true;\n if (attribute === "false")\n return false;\n return hasExplicitAriaDisabled(parentElementOrShadowHost(element), true);\n }\n return false;\n}\nfunction getAccessibleNameFromAssociatedLabels(labels, options) {\n return [...labels].map((label) => getTextAlternativeInternal(label, {\n ...options,\n embeddedInLabel: { element: label, hidden: isElementHiddenForAria(label) },\n embeddedInNativeTextAlternative: void 0,\n embeddedInLabelledBy: void 0,\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0\n })).filter((accessibleName) => !!accessibleName).join(" ");\n}\nfunction receivesPointerEvents(element) {\n const cache = cachePointerEvents;\n let e = element;\n let result;\n const parents = [];\n for (; e; e = parentElementOrShadowHost(e)) {\n const cached = cache.get(e);\n if (cached !== void 0) {\n result = cached;\n break;\n }\n parents.push(e);\n const style = getElementComputedStyle(e);\n if (!style) {\n result = true;\n break;\n }\n const value = style.pointerEvents;\n if (value) {\n result = value !== "none";\n break;\n }\n }\n if (result === void 0)\n result = true;\n for (const parent of parents)\n cache.set(parent, result);\n return result;\n}\nvar cacheAccessibleName;\nvar cacheAccessibleNameHidden;\nvar cacheAccessibleDescription;\nvar cacheAccessibleDescriptionHidden;\nvar cacheAccessibleErrorMessage;\nvar cacheIsHidden;\nvar cachePseudoContent;\nvar cachePseudoContentBefore;\nvar cachePseudoContentAfter;\nvar cachePointerEvents;\nvar cachesCounter2 = 0;\nfunction beginAriaCaches() {\n beginDOMCaches();\n ++cachesCounter2;\n cacheAccessibleName != null ? cacheAccessibleName : cacheAccessibleName = /* @__PURE__ */ new Map();\n cacheAccessibleNameHidden != null ? cacheAccessibleNameHidden : cacheAccessibleNameHidden = /* @__PURE__ */ new Map();\n cacheAccessibleDescription != null ? cacheAccessibleDescription : cacheAccessibleDescription = /* @__PURE__ */ new Map();\n cacheAccessibleDescriptionHidden != null ? cacheAccessibleDescriptionHidden : cacheAccessibleDescriptionHidden = /* @__PURE__ */ new Map();\n cacheAccessibleErrorMessage != null ? cacheAccessibleErrorMessage : cacheAccessibleErrorMessage = /* @__PURE__ */ new Map();\n cacheIsHidden != null ? cacheIsHidden : cacheIsHidden = /* @__PURE__ */ new Map();\n cachePseudoContent != null ? cachePseudoContent : cachePseudoContent = /* @__PURE__ */ new Map();\n cachePseudoContentBefore != null ? cachePseudoContentBefore : cachePseudoContentBefore = /* @__PURE__ */ new Map();\n cachePseudoContentAfter != null ? cachePseudoContentAfter : cachePseudoContentAfter = /* @__PURE__ */ new Map();\n cachePointerEvents != null ? cachePointerEvents : cachePointerEvents = /* @__PURE__ */ new Map();\n}\nfunction endAriaCaches() {\n if (!--cachesCounter2) {\n cacheAccessibleName = void 0;\n cacheAccessibleNameHidden = void 0;\n cacheAccessibleDescription = void 0;\n cacheAccessibleDescriptionHidden = void 0;\n cacheAccessibleErrorMessage = void 0;\n cacheIsHidden = void 0;\n cachePseudoContent = void 0;\n cachePseudoContentBefore = void 0;\n cachePseudoContentAfter = void 0;\n cachePointerEvents = void 0;\n }\n endDOMCaches();\n}\nvar inputTypeToRole = {\n "button": "button",\n "checkbox": "checkbox",\n "image": "button",\n "number": "spinbutton",\n "radio": "radio",\n "range": "slider",\n "reset": "button",\n "submit": "button"\n};\n\n// packages/injected/src/ariaSnapshot.ts\nvar lastRef = 0;\nfunction toInternalOptions(options) {\n const renderBoxes = options.boxes;\n if (options.mode === "ai") {\n return {\n visibility: "ariaOrVisible",\n refs: "interactable",\n refPrefix: options.refPrefix,\n includeGenericRole: true,\n renderActive: !options.doNotRenderActive,\n renderCursorPointer: true,\n renderBoxes\n };\n }\n if (options.mode === "autoexpect") {\n return { visibility: "ariaAndVisible", refs: "none", renderBoxes };\n }\n if (options.mode === "codegen") {\n return { visibility: "aria", refs: "none", renderStringsAsRegex: true, renderBoxes };\n }\n return { visibility: "aria", refs: "none", renderBoxes };\n}\nfunction generateAriaTree(rootElement, publicOptions) {\n const options = toInternalOptions(publicOptions);\n const visited = /* @__PURE__ */ new Set();\n const snapshot = {\n root: { role: "fragment", name: "", children: [], props: {}, box: computeBox(rootElement), receivesPointerEvents: true },\n elements: /* @__PURE__ */ new Map(),\n refs: /* @__PURE__ */ new Map(),\n iframeRefs: []\n };\n setAriaNodeElement(snapshot.root, rootElement);\n const visit = (ariaNode, node, parentElementVisible) => {\n if (visited.has(node))\n return;\n visited.add(node);\n if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {\n if (!parentElementVisible)\n return;\n const text = node.nodeValue;\n if (ariaNode.role !== "textbox" && text)\n ariaNode.children.push(node.nodeValue || "");\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE)\n return;\n const element = node;\n const isElementVisibleForAria = !isElementHiddenForAria(element);\n let visible = isElementVisibleForAria;\n if (options.visibility === "ariaOrVisible")\n visible = isElementVisibleForAria || isElementVisible(element);\n if (options.visibility === "ariaAndVisible")\n visible = isElementVisibleForAria && isElementVisible(element);\n if (options.visibility === "aria" && !visible)\n return;\n const ariaChildren = [];\n if (element.hasAttribute("aria-owns")) {\n const ids = element.getAttribute("aria-owns").split(/\\s+/);\n for (const id of ids) {\n const ownedElement = rootElement.ownerDocument.getElementById(id);\n if (ownedElement)\n ariaChildren.push(ownedElement);\n }\n }\n const childAriaNode = visible ? toAriaNode(element, options) : null;\n if (childAriaNode) {\n if (childAriaNode.ref) {\n snapshot.elements.set(childAriaNode.ref, element);\n snapshot.refs.set(element, childAriaNode.ref);\n if (childAriaNode.role === "iframe")\n snapshot.iframeRefs.push(childAriaNode.ref);\n }\n ariaNode.children.push(childAriaNode);\n }\n processElement(childAriaNode || ariaNode, element, ariaChildren, visible);\n };\n function processElement(ariaNode, element, ariaChildren, parentElementVisible) {\n var _a;\n const display = ((_a = getElementComputedStyle(element)) == null ? void 0 : _a.display) || "inline";\n const treatAsBlock = display !== "inline" || element.nodeName === "BR" ? " " : "";\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n ariaNode.children.push(getCSSContent(element, "::before") || "");\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(ariaNode, child, parentElementVisible);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (!child.assignedSlot)\n visit(ariaNode, child, parentElementVisible);\n }\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(ariaNode, child, parentElementVisible);\n }\n }\n for (const child of ariaChildren)\n visit(ariaNode, child, parentElementVisible);\n ariaNode.children.push(getCSSContent(element, "::after") || "");\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n if (ariaNode.children.length === 1 && ariaNode.name === ariaNode.children[0])\n ariaNode.children = [];\n if (ariaNode.role === "link" && element.hasAttribute("href")) {\n const href = element.getAttribute("href");\n ariaNode.props["url"] = href;\n }\n if (ariaNode.role === "textbox" && element.hasAttribute("placeholder") && element.getAttribute("placeholder") !== ariaNode.name) {\n const placeholder = element.getAttribute("placeholder");\n ariaNode.props["placeholder"] = placeholder;\n }\n }\n beginAriaCaches();\n try {\n visit(snapshot.root, rootElement, true);\n } finally {\n endAriaCaches();\n }\n normalizeStringChildren(snapshot.root);\n normalizeGenericRoles(snapshot.root);\n return snapshot;\n}\nfunction computeAriaRef(ariaNode, options) {\n var _a;\n if (options.refs === "none")\n return;\n if (options.refs === "interactable" && (!ariaNode.box.visible || !ariaNode.receivesPointerEvents))\n return;\n const element = ariaNodeElement(ariaNode);\n let ariaRef = element._ariaRef;\n if (!ariaRef || ariaRef.role !== ariaNode.role || ariaRef.name !== ariaNode.name) {\n ariaRef = { role: ariaNode.role, name: ariaNode.name, ref: ((_a = options.refPrefix) != null ? _a : "") + "e" + ++lastRef };\n element._ariaRef = ariaRef;\n }\n ariaNode.ref = ariaRef.ref;\n}\nfunction toAriaNode(element, options) {\n var _a;\n const active = element.ownerDocument.activeElement === element;\n if (element.nodeName === "IFRAME") {\n const ariaNode = {\n role: "iframe",\n name: "",\n children: [],\n props: {},\n box: computeBox(element),\n receivesPointerEvents: true,\n active\n };\n setAriaNodeElement(ariaNode, element);\n computeAriaRef(ariaNode, options);\n return ariaNode;\n }\n const defaultRole = options.includeGenericRole ? "generic" : null;\n const role = (_a = getAriaRole(element)) != null ? _a : defaultRole;\n if (!role || role === "presentation" || role === "none")\n return null;\n const name = normalizeWhiteSpace(getElementAccessibleName(element, false) || "");\n const receivesPointerEvents2 = receivesPointerEvents(element);\n const box = computeBox(element);\n if (role === "generic" && box.inline && element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE)\n return null;\n const result = {\n role,\n name,\n children: [],\n props: {},\n box,\n receivesPointerEvents: receivesPointerEvents2,\n active\n };\n setAriaNodeElement(result, element);\n computeAriaRef(result, options);\n if (kAriaCheckedRoles.includes(role))\n result.checked = getAriaChecked(element);\n if (kAriaDisabledRoles.includes(role))\n result.disabled = getAriaDisabled(element);\n if (kAriaExpandedRoles.includes(role))\n result.expanded = getAriaExpanded(element);\n if (kAriaInvalidRoles.includes(role)) {\n const invalid = getAriaInvalid(element);\n result.invalid = invalid === "false" ? false : invalid === "true" ? true : invalid;\n }\n if (kAriaLevelRoles.includes(role))\n result.level = getAriaLevel(element);\n if (kAriaPressedRoles.includes(role))\n result.pressed = getAriaPressed(element);\n if (kAriaSelectedRoles.includes(role))\n result.selected = getAriaSelected(element);\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n if (element.type !== "checkbox" && element.type !== "radio" && element.type !== "file")\n result.children = [element.value];\n }\n return result;\n}\nfunction normalizeGenericRoles(node) {\n const normalizeChildren = (node2) => {\n const result = [];\n for (const child of node2.children || []) {\n if (typeof child === "string") {\n result.push(child);\n continue;\n }\n const normalized = normalizeChildren(child);\n result.push(...normalized);\n }\n const removeSelf = node2.role === "generic" && !node2.name && result.length <= 1 && result.every((c) => typeof c !== "string" && !!c.ref);\n if (removeSelf)\n return result;\n node2.children = result;\n return [node2];\n };\n normalizeChildren(node);\n}\nfunction normalizeStringChildren(rootA11yNode) {\n const flushChildren = (buffer, normalizedChildren) => {\n if (!buffer.length)\n return;\n const text = normalizeWhiteSpace(buffer.join(""));\n if (text)\n normalizedChildren.push(text);\n buffer.length = 0;\n };\n const visit = (ariaNode) => {\n const normalizedChildren = [];\n const buffer = [];\n for (const child of ariaNode.children || []) {\n if (typeof child === "string") {\n buffer.push(child);\n } else {\n flushChildren(buffer, normalizedChildren);\n visit(child);\n normalizedChildren.push(child);\n }\n }\n flushChildren(buffer, normalizedChildren);\n ariaNode.children = normalizedChildren.length ? normalizedChildren : [];\n if (ariaNode.children.length === 1 && ariaNode.children[0] === ariaNode.name)\n ariaNode.children = [];\n };\n visit(rootA11yNode);\n}\nfunction matchesStringOrRegex(text, template) {\n if (!template)\n return true;\n if (!text)\n return false;\n if (typeof template === "string")\n return text === template;\n return !!text.match(new RegExp(template.pattern));\n}\nfunction matchesTextValue(text, template) {\n if (!(template == null ? void 0 : template.normalized))\n return true;\n if (!text)\n return false;\n if (text === template.normalized)\n return true;\n if (text === template.raw)\n return true;\n const regex = cachedRegex(template);\n if (regex)\n return !!text.match(regex);\n return false;\n}\nvar cachedRegexSymbol = Symbol("cachedRegex");\nfunction cachedRegex(template) {\n if (template[cachedRegexSymbol] !== void 0)\n return template[cachedRegexSymbol];\n const { raw } = template;\n const canBeRegex = raw.startsWith("/") && raw.endsWith("/") && raw.length > 1;\n let regex;\n try {\n regex = canBeRegex ? new RegExp(raw.slice(1, -1)) : null;\n } catch (e) {\n regex = null;\n }\n template[cachedRegexSymbol] = regex;\n return regex;\n}\nfunction matchesExpectAriaTemplate(rootElement, template) {\n const snapshot = generateAriaTree(rootElement, { mode: "default" });\n const matches = matchesNodeDeep(snapshot.root, template, false, false);\n return {\n matches,\n received: {\n raw: renderAriaTree(snapshot, { mode: "default" }).text,\n regex: renderAriaTree(snapshot, { mode: "codegen" }).text\n }\n };\n}\nfunction getAllElementsMatchingExpectAriaTemplate(rootElement, template) {\n const root = generateAriaTree(rootElement, { mode: "default" }).root;\n const matches = matchesNodeDeep(root, template, true, false);\n return matches.map((n) => ariaNodeElement(n));\n}\nfunction matchesNode(node, template, isDeepEqual) {\n var _a;\n if (typeof node === "string" && template.kind === "text")\n return matchesTextValue(node, template.text);\n if (node === null || typeof node !== "object" || template.kind !== "role")\n return false;\n if (template.role !== "fragment" && template.role !== node.role)\n return false;\n if (template.checked !== void 0 && template.checked !== node.checked)\n return false;\n if (template.disabled !== void 0 && template.disabled !== node.disabled)\n return false;\n if (template.expanded !== void 0 && template.expanded !== node.expanded)\n return false;\n if (template.invalid !== void 0 && template.invalid !== node.invalid)\n return false;\n if (template.level !== void 0 && template.level !== node.level)\n return false;\n if (template.pressed !== void 0 && template.pressed !== node.pressed)\n return false;\n if (template.selected !== void 0 && template.selected !== node.selected)\n return false;\n if (!matchesStringOrRegex(node.name, template.name))\n return false;\n if (!matchesTextValue(node.props.url, (_a = template.props) == null ? void 0 : _a.url))\n return false;\n if (template.containerMode === "contain")\n return containsList(node.children || [], template.children || []);\n if (template.containerMode === "equal")\n return listEqual(node.children || [], template.children || [], false);\n if (template.containerMode === "deep-equal" || isDeepEqual)\n return listEqual(node.children || [], template.children || [], true);\n return containsList(node.children || [], template.children || []);\n}\nfunction listEqual(children, template, isDeepEqual) {\n if (template.length !== children.length)\n return false;\n for (let i = 0; i < template.length; ++i) {\n if (!matchesNode(children[i], template[i], isDeepEqual))\n return false;\n }\n return true;\n}\nfunction containsList(children, template) {\n if (template.length > children.length)\n return false;\n const cc = children.slice();\n const tt = template.slice();\n for (const t of tt) {\n let c = cc.shift();\n while (c) {\n if (matchesNode(c, t, false))\n break;\n c = cc.shift();\n }\n if (!c)\n return false;\n }\n return true;\n}\nfunction matchesNodeDeep(root, template, collectAll, isDeepEqual) {\n const results = [];\n const visit = (node, parent) => {\n if (matchesNode(node, template, isDeepEqual)) {\n const result = typeof node === "string" ? parent : node;\n if (result)\n results.push(result);\n return !collectAll;\n }\n if (typeof node === "string")\n return false;\n for (const child of node.children || []) {\n if (visit(child, node))\n return true;\n }\n return false;\n };\n visit(root, null);\n return results;\n}\nfunction buildByRefMap(root, map = /* @__PURE__ */ new Map()) {\n if (root == null ? void 0 : root.ref)\n map.set(root.ref, root);\n for (const child of (root == null ? void 0 : root.children) || []) {\n if (typeof child !== "string")\n buildByRefMap(child, map);\n }\n return map;\n}\nfunction compareSnapshots(ariaSnapshot, previousSnapshot) {\n var _a;\n const previousByRef = buildByRefMap(previousSnapshot == null ? void 0 : previousSnapshot.root);\n const result = /* @__PURE__ */ new Map();\n const visit = (ariaNode, previousNode) => {\n let same = ariaNode.children.length === (previousNode == null ? void 0 : previousNode.children.length) && ariaNodesEqual(ariaNode, previousNode);\n let canBeSkipped = same;\n for (let childIndex = 0; childIndex < ariaNode.children.length; childIndex++) {\n const child = ariaNode.children[childIndex];\n const previousChild = previousNode == null ? void 0 : previousNode.children[childIndex];\n if (typeof child === "string") {\n same && (same = child === previousChild);\n canBeSkipped && (canBeSkipped = child === previousChild);\n } else {\n let previous = typeof previousChild !== "string" ? previousChild : void 0;\n if (child.ref)\n previous = previousByRef.get(child.ref);\n const sameChild = visit(child, previous);\n if (!previous || !sameChild && !child.ref || previous !== previousChild)\n canBeSkipped = false;\n same && (same = sameChild && previous === previousChild);\n }\n }\n result.set(ariaNode, same ? "same" : canBeSkipped ? "skip" : "changed");\n return same;\n };\n visit(ariaSnapshot.root, previousByRef.get((_a = previousSnapshot == null ? void 0 : previousSnapshot.root) == null ? void 0 : _a.ref));\n return result;\n}\nfunction filterSnapshotDiff(nodes, statusMap) {\n const result = [];\n const visit = (ariaNode) => {\n const status = statusMap.get(ariaNode);\n if (status === "same") {\n } else if (status === "skip") {\n for (const child of ariaNode.children) {\n if (typeof child !== "string")\n visit(child);\n }\n } else {\n result.push(ariaNode);\n }\n };\n for (const node of nodes) {\n if (typeof node === "string")\n result.push(node);\n else\n visit(node);\n }\n return result;\n}\nfunction indent(depth) {\n return " ".repeat(depth);\n}\nfunction renderAriaTree(ariaSnapshot, publicOptions, previousSnapshot) {\n const options = toInternalOptions(publicOptions);\n const lines = [];\n const iframeDepths = {};\n const includeText = options.renderStringsAsRegex ? textContributesInfo : () => true;\n const renderString = options.renderStringsAsRegex ? convertToBestGuessRegex : (str) => str;\n let nodesToRender = ariaSnapshot.root.role === "fragment" ? ariaSnapshot.root.children : [ariaSnapshot.root];\n const statusMap = compareSnapshots(ariaSnapshot, previousSnapshot);\n if (previousSnapshot)\n nodesToRender = filterSnapshotDiff(nodesToRender, statusMap);\n const visitText = (text, depth) => {\n if (publicOptions.depth && depth > publicOptions.depth)\n return;\n const escaped = yamlEscapeValueIfNeeded(renderString(text));\n if (escaped)\n lines.push(indent(depth) + "- text: " + escaped);\n };\n const createKey = (ariaNode, renderCursorPointer) => {\n let key = ariaNode.role;\n if (ariaNode.name && ariaNode.name.length <= 900) {\n const name = renderString(ariaNode.name);\n if (name) {\n const stringifiedName = name.startsWith("/") && name.endsWith("/") ? name : JSON.stringify(name);\n key += " " + stringifiedName;\n }\n }\n if (ariaNode.checked === "mixed")\n key += ` [checked=mixed]`;\n if (ariaNode.checked === true)\n key += ` [checked]`;\n if (ariaNode.disabled)\n key += ` [disabled]`;\n if (ariaNode.expanded)\n key += ` [expanded]`;\n if (ariaNode.active && options.renderActive)\n key += ` [active]`;\n if (ariaNode.invalid === "grammar" || ariaNode.invalid === "spelling")\n key += ` [invalid=${ariaNode.invalid}]`;\n if (ariaNode.invalid === true)\n key += ` [invalid]`;\n if (ariaNode.level)\n key += ` [level=${ariaNode.level}]`;\n if (ariaNode.pressed === "mixed")\n key += ` [pressed=mixed]`;\n if (ariaNode.pressed === true)\n key += ` [pressed]`;\n if (ariaNode.selected === true)\n key += ` [selected]`;\n if (ariaNode.ref) {\n key += ` [ref=${ariaNode.ref}]`;\n if (renderCursorPointer && hasPointerCursor(ariaNode))\n key += " [cursor=pointer]";\n }\n if (options.renderBoxes) {\n const element = ariaNodeElement(ariaNode);\n if (element) {\n const r = element.getBoundingClientRect();\n key += ` [box=${Math.round(r.x)},${Math.round(r.y)},${Math.round(r.width)},${Math.round(r.height)}]`;\n }\n }\n return key;\n };\n const getSingleInlinedTextChild = (ariaNode) => {\n return (ariaNode == null ? void 0 : ariaNode.children.length) === 1 && typeof ariaNode.children[0] === "string" && !Object.keys(ariaNode.props).length ? ariaNode.children[0] : void 0;\n };\n const visit = (ariaNode, depth, renderCursorPointer) => {\n if (publicOptions.depth && depth > publicOptions.depth)\n return;\n if (ariaNode.role === "iframe" && ariaNode.ref)\n iframeDepths[ariaNode.ref] = depth;\n if (statusMap.get(ariaNode) === "same" && ariaNode.ref) {\n lines.push(indent(depth) + `- ref=${ariaNode.ref} [unchanged]`);\n return;\n }\n const isDiffRoot = !!previousSnapshot && !depth;\n const escapedKey = indent(depth) + "- " + (isDiffRoot ? " " : "") + yamlEscapeKeyIfNeeded(createKey(ariaNode, renderCursorPointer));\n const singleInlinedTextChild = getSingleInlinedTextChild(ariaNode);\n const isAtDepthLimit = !!publicOptions.depth && depth === publicOptions.depth;\n const hasNoChildren = !singleInlinedTextChild && (!ariaNode.children.length || isAtDepthLimit);\n if (hasNoChildren && !Object.keys(ariaNode.props).length) {\n lines.push(escapedKey);\n } else if (singleInlinedTextChild !== void 0) {\n const shouldInclude = includeText(ariaNode, singleInlinedTextChild);\n if (shouldInclude)\n lines.push(escapedKey + ": " + yamlEscapeValueIfNeeded(renderString(singleInlinedTextChild)));\n else\n lines.push(escapedKey);\n } else {\n lines.push(escapedKey + ":");\n for (const [name, value] of Object.entries(ariaNode.props))\n lines.push(indent(depth + 1) + "- /" + name + ": " + yamlEscapeValueIfNeeded(value));\n const inCursorPointer = !!ariaNode.ref && renderCursorPointer && hasPointerCursor(ariaNode);\n for (const child of ariaNode.children) {\n if (typeof child === "string")\n visitText(includeText(ariaNode, child) ? child : "", depth + 1);\n else\n visit(child, depth + 1, renderCursorPointer && !inCursorPointer);\n }\n }\n };\n for (const nodeToRender of nodesToRender) {\n if (typeof nodeToRender === "string")\n visitText(nodeToRender, 0);\n else\n visit(nodeToRender, 0, !!options.renderCursorPointer);\n }\n return { text: lines.join("\\n"), iframeDepths };\n}\nfunction convertToBestGuessRegex(text) {\n const dynamicContent = [\n // 550e8400-e29b-41d4-a716-446655440000\n { regex: /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/, replacement: "[0-9a-fA-F-]+" },\n // 2mb\n { regex: /\\b[\\d,.]+[bkmBKM]+\\b/, replacement: "[\\\\d,.]+[bkmBKM]+" },\n // 2ms, 20s\n { regex: /\\b\\d+[hmsp]+\\b/, replacement: "\\\\d+[hmsp]+" },\n { regex: /\\b[\\d,.]+[hmsp]+\\b/, replacement: "[\\\\d,.]+[hmsp]+" },\n // Do not replace single digits with regex by default.\n // 2+ digits: [Issue 22, 22.3, 2.33, 2,333]\n { regex: /\\b\\d+,\\d+\\b/, replacement: "\\\\d+,\\\\d+" },\n { regex: /\\b\\d+\\.\\d{2,}\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\.\\d+\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\b/, replacement: "\\\\d+" }\n ];\n let pattern = "";\n let lastIndex = 0;\n const combinedRegex = new RegExp(dynamicContent.map((r) => "(" + r.regex.source + ")").join("|"), "g");\n text.replace(combinedRegex, (match, ...args) => {\n const offset = args[args.length - 2];\n const groups = args.slice(0, -2);\n pattern += escapeRegExp(text.slice(lastIndex, offset));\n for (let i = 0; i < groups.length; i++) {\n if (groups[i]) {\n const { replacement } = dynamicContent[i];\n pattern += replacement;\n break;\n }\n }\n lastIndex = offset + match.length;\n return match;\n });\n if (!pattern)\n return text;\n pattern += escapeRegExp(text.slice(lastIndex));\n return String(new RegExp(pattern));\n}\nfunction textContributesInfo(node, text) {\n if (!text.length)\n return false;\n if (!node.name)\n return true;\n const substr = text.length <= 200 && node.name.length <= 200 ? longestCommonSubstring(text, node.name) : "";\n let filtered = text;\n while (substr && filtered.includes(substr))\n filtered = filtered.replace(substr, "");\n return filtered.trim().length / text.length > 0.1;\n}\nvar elementSymbol = Symbol("element");\nfunction ariaNodeElement(ariaNode) {\n return ariaNode[elementSymbol];\n}\nfunction setAriaNodeElement(ariaNode, element) {\n ariaNode[elementSymbol] = element;\n}\nfunction findNewElement(from, to) {\n const node = findNewNode(from, to);\n return node ? ariaNodeElement(node) : void 0;\n}\n\n// packages/injected/src/highlight.css?inline\nvar highlight_default = ":host{font-size:13px;font-family:system-ui,Ubuntu,Droid Sans,sans-serif;color:#333;color-scheme:light}svg{position:absolute;height:0}x-pw-tooltip{backdrop-filter:blur(5px);background-color:#fff;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:none;font-size:12.8px;font-weight:400;left:0;line-height:1.5;max-width:600px;position:absolute;top:0;padding:0;flex-direction:column;overflow:hidden}x-pw-tooltip-line{display:flex;max-width:600px;padding:6px;user-select:none;cursor:pointer}x-pw-tooltip-footer{display:flex;max-width:600px;padding:6px;user-select:none;color:#777}x-pw-dialog{background-color:#fff;pointer-events:auto;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:flex;flex-direction:column;position:absolute;z-index:10;font-size:13px}x-pw-dialog:not(.autosize){width:400px;height:150px}x-pw-dialog-body{display:flex;flex-direction:column;flex:auto}x-pw-dialog-body label{margin:5px 8px;display:flex;flex-direction:row;align-items:center}x-pw-highlight{position:absolute;top:0;left:0;width:0;height:0}x-pw-action-point{position:absolute;width:20px;height:20px;background:red;border-radius:10px;margin:-10px 0 0 -10px;z-index:2}x-pw-action-cursor{position:absolute;width:18px;height:22px;pointer-events:none;z-index:4;filter:drop-shadow(0 1px 2px rgba(0,0,0,.4))}x-pw-action-cursor svg{width:100%;height:100%;position:static}x-pw-title{position:absolute;backdrop-filter:blur(5px);background-color:#00000080;color:#fff;border-radius:6px;padding:6px;font-size:24px;line-height:1.4;white-space:nowrap;user-select:none;z-index:3}x-pw-user-overlays,x-pw-user-overlay{position:absolute;inset:0}@keyframes pw-fade-out{0%{opacity:1}to{opacity:0}}x-pw-separator{height:1px;margin:6px 9px;background:#949494e5}x-pw-tool-gripper{height:28px;width:24px;margin:2px 0;cursor:grab}x-pw-tool-gripper:active{cursor:grabbing}x-pw-tool-gripper>x-div{width:16px;height:16px;margin:6px 4px;clip-path:url(#icon-gripper);background-color:#555}x-pw-tools-list>label{display:flex;align-items:center;margin:0 10px;user-select:none}x-pw-tools-list{display:flex;width:100%;border-bottom:1px solid #dddddd}x-pw-tool-item{pointer-events:auto;height:28px;width:28px;border-radius:3px}x-pw-tool-item:not(.disabled){cursor:pointer}x-pw-tool-item:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.toggled{background-color:#8acae480}x-pw-tool-item.toggled:not(.disabled):hover{background-color:#8acae4c4}x-pw-tool-item>x-div{width:16px;height:16px;margin:6px;background-color:#3a3a3a}x-pw-tool-item.disabled>x-div{background-color:#61616180;cursor:default}x-pw-tool-item.record.toggled{background-color:transparent}x-pw-tool-item.record.toggled:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.record.toggled>x-div{background-color:#a1260d}x-pw-tool-item.record.disabled.toggled>x-div{opacity:.8}x-pw-tool-item.accept>x-div{background-color:#388a34}x-pw-tool-item.record>x-div{clip-path:url(#icon-circle-large-filled)}x-pw-tool-item.record.toggled>x-div{clip-path:url(#icon-stop-circle)}x-pw-tool-item.pick-locator>x-div{clip-path:url(#icon-inspect)}x-pw-tool-item.text>x-div{clip-path:url(#icon-whole-word)}x-pw-tool-item.visibility>x-div{clip-path:url(#icon-eye)}x-pw-tool-item.value>x-div{clip-path:url(#icon-symbol-constant)}x-pw-tool-item.snapshot>x-div{clip-path:url(#icon-gist)}x-pw-tool-item.accept>x-div{clip-path:url(#icon-check)}x-pw-tool-item.cancel>x-div{clip-path:url(#icon-close)}x-pw-tool-item.succeeded>x-div{clip-path:url(#icon-pass);background-color:#388a34!important}x-pw-overlay{position:absolute;top:0;max-width:min-content;z-index:2147483647;background:transparent;pointer-events:auto}x-pw-overlay x-pw-tools-list{background-color:#fffd;box-shadow:#0000001a 0 5px 5px;border-radius:3px;border-bottom:none}x-pw-overlay x-pw-tool-item{margin:2px}textarea.text-editor{font-family:system-ui,Ubuntu,Droid Sans,sans-serif;flex:auto;border:none;margin:6px 10px;color:#333;outline:1px solid transparent!important;resize:none;padding:0;font-size:13px}textarea.text-editor.does-not-match{outline:1px solid red!important}x-div{display:block}x-spacer{flex:auto}*{box-sizing:border-box}*[hidden]{display:none!important}x-locator-editor{flex:none;width:100%;height:60px;padding:4px;border-bottom:1px solid #dddddd;outline:1px solid transparent}x-locator-editor.does-not-match{outline:1px solid red}.CodeMirror{width:100%!important;height:100%!important}x-pw-action-list{flex:auto;display:flex;flex-direction:column;user-select:none}x-pw-action-item{padding:6px 10px;cursor:pointer;overflow:hidden}x-pw-action-item:hover{background-color:#f2f2f2}x-pw-action-item:last-child{border-bottom-left-radius:6px;border-bottom-right-radius:6px}\\n";\n\n// packages/injected/src/highlight.ts\nvar Highlight = class {\n constructor(injectedScript) {\n this._renderedEntries = [];\n this._userOverlays = /* @__PURE__ */ new Map();\n this._userOverlayHidden = false;\n this._language = "javascript";\n this._elementHighlightSelectors = /* @__PURE__ */ new Map();\n this._injectedScript = injectedScript;\n const document = injectedScript.document;\n this._isUnderTest = injectedScript.isUnderTest;\n this._glassPaneElement = document.createElement("x-pw-glass");\n this._glassPaneElement.setAttribute("popover", "manual");\n this._glassPaneElement.style.inset = "0";\n this._glassPaneElement.style.width = "100%";\n this._glassPaneElement.style.height = "100%";\n this._glassPaneElement.style.maxWidth = "none";\n this._glassPaneElement.style.maxHeight = "none";\n this._glassPaneElement.style.padding = "0";\n this._glassPaneElement.style.margin = "0";\n this._glassPaneElement.style.border = "none";\n this._glassPaneElement.style.overflow = "visible";\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.display = "flex";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._actionPointElement = document.createElement("x-pw-action-point");\n this._actionPointElement.setAttribute("hidden", "true");\n this._actionCursorElement = document.createElement("x-pw-action-cursor");\n this._actionCursorElement.style.visibility = "hidden";\n this._actionCursorElement.appendChild(this._createCursorSvg(document));\n this._titleElement = document.createElement("x-pw-title");\n this._titleElement.setAttribute("hidden", "true");\n this._userOverlayContainer = document.createElement("x-pw-user-overlays");\n this._userOverlayContainer.setAttribute("hidden", "true");\n this._glassPaneShadow = this._glassPaneElement.attachShadow({ mode: this._isUnderTest ? "open" : "closed" });\n if (typeof this._glassPaneShadow.adoptedStyleSheets.push === "function") {\n const sheet = new this._injectedScript.window.CSSStyleSheet();\n sheet.replaceSync(highlight_default);\n this._glassPaneShadow.adoptedStyleSheets.push(sheet);\n } else {\n const styleElement = this._injectedScript.document.createElement("style");\n styleElement.textContent = highlight_default;\n this._glassPaneShadow.appendChild(styleElement);\n }\n this._glassPaneShadow.appendChild(this._actionPointElement);\n this._glassPaneShadow.appendChild(this._actionCursorElement);\n this._glassPaneShadow.appendChild(this._titleElement);\n this._glassPaneShadow.appendChild(this._userOverlayContainer);\n }\n install() {\n if (!this._injectedScript.document.documentElement)\n return;\n if (!this._injectedScript.document.documentElement.contains(this._glassPaneElement) || this._glassPaneElement.nextElementSibling)\n this._injectedScript.document.documentElement.appendChild(this._glassPaneElement);\n this._bringToFront();\n }\n _bringToFront() {\n this._glassPaneElement.hidePopover();\n this._glassPaneElement.showPopover();\n }\n setLanguage(language) {\n this._language = language;\n }\n addElementHighlight(selector, cssStyle) {\n const key = stringifySelector(selector);\n this._elementHighlightSelectors.set(key, { selector, cssStyle });\n this._ensureElementHighlightRaf();\n }\n removeElementHighlight(selector) {\n const key = stringifySelector(selector);\n if (!this._elementHighlightSelectors.delete(key))\n return;\n if (this._elementHighlightSelectors.size === 0) {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this.clearHighlight();\n }\n }\n _ensureElementHighlightRaf() {\n if (this._rafRequest)\n return;\n const tick = () => {\n const entries = [];\n for (const { selector, cssStyle } of this._elementHighlightSelectors.values()) {\n const elements = this._injectedScript.querySelectorAll(selector, this._injectedScript.document.documentElement);\n const locator = asLocator(this._language, stringifySelector(selector));\n const color = elements.length > 1 ? "#f6b26b7f" : "#6fa8dc7f";\n for (let i = 0; i < elements.length; ++i) {\n const suffix = elements.length > 1 ? ` [${i + 1} of ${elements.length}]` : "";\n entries.push({ element: elements[i], color, tooltipText: locator + suffix, cssStyle });\n }\n }\n this.updateHighlight(entries);\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n };\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n }\n uninstall() {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this._elementHighlightSelectors.clear();\n this._glassPaneElement.remove();\n }\n showActionPoint(x, y, fadeDuration) {\n this._actionPointElement.style.top = y + "px";\n this._actionPointElement.style.left = x + "px";\n this._actionPointElement.hidden = false;\n if (fadeDuration)\n this._actionPointElement.style.animation = `pw-fade-out ${fadeDuration}ms ease-out forwards`;\n else\n this._actionPointElement.style.animation = "";\n }\n hideActionPoint() {\n this._actionPointElement.hidden = true;\n }\n moveActionCursor(x, y, fadeDuration) {\n const moveDuration = fadeDuration ? Math.max(80, Math.min(fadeDuration * 0.6, 400)) : 0;\n this._actionCursorElement.style.transition = `top ${moveDuration}ms ease, left ${moveDuration}ms ease`;\n this._actionCursorElement.style.left = x + "px";\n this._actionCursorElement.style.top = y + "px";\n this._actionCursorElement.style.visibility = "visible";\n }\n hideActionCursor() {\n this._actionCursorElement.style.visibility = "hidden";\n }\n _createCursorSvg(document) {\n const svgNs = "http://www.w3.org/2000/svg";\n const svg = document.createElementNS(svgNs, "svg");\n svg.setAttribute("viewBox", "0 0 18 22");\n const path = document.createElementNS(svgNs, "path");\n path.setAttribute("d", "M1 1 L1 17 L5.5 13 L8 20.5 L11 19.5 L8.5 12 L15 12 Z");\n path.setAttribute("fill", "white");\n path.setAttribute("stroke", "black");\n path.setAttribute("stroke-width", "1.5");\n path.setAttribute("stroke-linejoin", "round");\n svg.appendChild(path);\n return svg;\n }\n showActionTitle(text, fadeDuration, position, fontSize) {\n this._titleElement.textContent = text;\n this._titleElement.hidden = false;\n if (fadeDuration) {\n const fadeTime = fadeDuration / 4;\n this._titleElement.style.animation = `pw-fade-out ${fadeTime}ms ease-out ${fadeDuration - fadeTime}ms forwards`;\n } else {\n this._titleElement.style.animation = "";\n }\n this._titleElement.style.top = "";\n this._titleElement.style.bottom = "";\n this._titleElement.style.left = "";\n this._titleElement.style.right = "";\n this._titleElement.style.transform = "";\n switch (position) {\n case "top-left":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "top":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-left":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "bottom":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-right":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.right = "6px";\n break;\n case "top-right":\n default:\n this._titleElement.style.top = "6px";\n this._titleElement.style.right = "6px";\n break;\n }\n if (fontSize)\n this._titleElement.style.fontSize = fontSize + "px";\n }\n hideActionTitle() {\n this._titleElement.hidden = true;\n }\n addUserOverlay(id, html) {\n const element = this._injectedScript.document.createElement("div");\n element.className = "x-pw-user-overlay";\n element.innerHTML = html;\n for (const script of element.querySelectorAll("script"))\n script.remove();\n for (const el of element.querySelectorAll("*")) {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith("on"))\n el.removeAttribute(attr.name);\n }\n }\n this._userOverlays.set(id, element);\n this._userOverlayContainer.appendChild(element);\n this._userOverlayContainer.hidden = this._userOverlayHidden;\n return id;\n }\n getUserOverlay(id) {\n return this._userOverlays.get(id);\n }\n removeUserOverlay(id) {\n const element = this._userOverlays.get(id);\n if (element) {\n element.remove();\n this._userOverlays.delete(id);\n }\n if (this._userOverlays.size === 0)\n this._userOverlayContainer.hidden = true;\n }\n setUserOverlaysVisible(visible) {\n this._userOverlayHidden = !visible;\n this._userOverlayContainer.hidden = !visible || this._userOverlays.size === 0;\n }\n clearHighlight() {\n var _a, _b;\n for (const entry of this._renderedEntries) {\n (_a = entry.highlightElement) == null ? void 0 : _a.remove();\n (_b = entry.tooltipElement) == null ? void 0 : _b.remove();\n }\n this._renderedEntries = [];\n }\n maskElements(elements, color) {\n this.updateHighlight(elements.map((element) => ({ element, color })));\n }\n updateHighlight(entries) {\n if (this._highlightIsUpToDate(entries))\n return;\n this.clearHighlight();\n for (const entry of entries) {\n const highlightElement = this._createHighlightElement();\n this._glassPaneShadow.appendChild(highlightElement);\n let tooltipElement;\n if (entry.tooltipText) {\n tooltipElement = this._injectedScript.document.createElement("x-pw-tooltip");\n this._glassPaneShadow.appendChild(tooltipElement);\n tooltipElement.style.top = "0";\n tooltipElement.style.left = "0";\n tooltipElement.style.display = "flex";\n const lineElement = this._injectedScript.document.createElement("x-pw-tooltip-line");\n lineElement.textContent = entry.tooltipText;\n tooltipElement.appendChild(lineElement);\n }\n this._renderedEntries.push({ targetElement: entry.element, box: toDOMRect(entry.box), color: entry.color, borderColor: entry.borderColor, fadeDuration: entry.fadeDuration, cssStyle: entry.cssStyle, tooltipElement, highlightElement });\n }\n for (const entry of this._renderedEntries) {\n if (!entry.box && !entry.targetElement)\n continue;\n entry.box = entry.box || entry.targetElement.getBoundingClientRect();\n if (!entry.tooltipElement)\n continue;\n const { anchorLeft, anchorTop } = this.tooltipPosition(entry.box, entry.tooltipElement);\n entry.tooltipTop = anchorTop;\n entry.tooltipLeft = anchorLeft;\n }\n for (const entry of this._renderedEntries) {\n if (entry.tooltipElement) {\n entry.tooltipElement.style.top = entry.tooltipTop + "px";\n entry.tooltipElement.style.left = entry.tooltipLeft + "px";\n }\n const box = entry.box;\n entry.highlightElement.style.backgroundColor = entry.color;\n entry.highlightElement.style.left = box.x + "px";\n entry.highlightElement.style.top = box.y + "px";\n entry.highlightElement.style.width = box.width + "px";\n entry.highlightElement.style.height = box.height + "px";\n entry.highlightElement.style.display = "block";\n if (entry.borderColor)\n entry.highlightElement.style.border = "2px solid " + entry.borderColor;\n if (entry.fadeDuration)\n entry.highlightElement.style.animation = `pw-fade-out ${entry.fadeDuration}ms ease-out forwards`;\n if (entry.cssStyle)\n entry.highlightElement.style.cssText += ";" + entry.cssStyle;\n if (this._isUnderTest)\n console.error("Highlight box for test: " + JSON.stringify({ x: box.x, y: box.y, width: box.width, height: box.height }));\n }\n }\n firstBox() {\n var _a;\n return (_a = this._renderedEntries[0]) == null ? void 0 : _a.box;\n }\n firstTooltipBox() {\n const entry = this._renderedEntries[0];\n if (!entry || !entry.tooltipElement || entry.tooltipLeft === void 0 || entry.tooltipTop === void 0)\n return;\n return {\n x: entry.tooltipLeft,\n y: entry.tooltipTop,\n left: entry.tooltipLeft,\n top: entry.tooltipTop,\n width: entry.tooltipElement.offsetWidth,\n height: entry.tooltipElement.offsetHeight,\n bottom: entry.tooltipTop + entry.tooltipElement.offsetHeight,\n right: entry.tooltipLeft + entry.tooltipElement.offsetWidth,\n toJSON: () => {\n }\n };\n }\n // Note: there is a copy of this method in dialog.tsx. Please fix bugs in both places.\n tooltipPosition(box, tooltipElement) {\n const tooltipWidth = tooltipElement.offsetWidth;\n const tooltipHeight = tooltipElement.offsetHeight;\n const totalWidth = this._glassPaneElement.offsetWidth;\n const totalHeight = this._glassPaneElement.offsetHeight;\n let anchorLeft = Math.max(5, box.left);\n if (anchorLeft + tooltipWidth > totalWidth - 5)\n anchorLeft = totalWidth - tooltipWidth - 5;\n let anchorTop = Math.max(0, box.bottom) + 5;\n if (anchorTop + tooltipHeight > totalHeight - 5) {\n if (Math.max(0, box.top) > tooltipHeight + 5) {\n anchorTop = Math.max(0, box.top) - tooltipHeight - 5;\n } else {\n anchorTop = totalHeight - 5 - tooltipHeight;\n }\n }\n return { anchorLeft, anchorTop };\n }\n _highlightIsUpToDate(entries) {\n if (entries.length !== this._renderedEntries.length)\n return false;\n for (let i = 0; i < this._renderedEntries.length; ++i) {\n if (entries[i].element !== this._renderedEntries[i].targetElement)\n return false;\n if (entries[i].color !== this._renderedEntries[i].color)\n return false;\n if (entries[i].cssStyle !== this._renderedEntries[i].cssStyle)\n return false;\n const oldBox = this._renderedEntries[i].box;\n if (!oldBox)\n return false;\n const box = entries[i].box ? toDOMRect(entries[i].box) : entries[i].element.getBoundingClientRect();\n if (box.top !== oldBox.top || box.right !== oldBox.right || box.bottom !== oldBox.bottom || box.left !== oldBox.left)\n return false;\n }\n return true;\n }\n _createHighlightElement() {\n return this._injectedScript.document.createElement("x-pw-highlight");\n }\n appendChild(element) {\n this._glassPaneShadow.appendChild(element);\n }\n onGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "auto";\n this._glassPaneElement.style.backgroundColor = "rgba(0, 0, 0, 0.3)";\n this._glassPaneElement.addEventListener("click", handler);\n }\n offGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._glassPaneElement.removeEventListener("click", handler);\n }\n};\nfunction toDOMRect(box) {\n if (!box)\n return void 0;\n return new DOMRect(box.x, box.y, box.width, box.height);\n}\n\n// packages/injected/src/layoutSelectorUtils.ts\nfunction boxRightOf(box1, box2, maxDistance) {\n const distance = box1.left - box2.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxLeftOf(box1, box2, maxDistance) {\n const distance = box2.left - box1.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxAbove(box1, box2, maxDistance) {\n const distance = box2.top - box1.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxBelow(box1, box2, maxDistance) {\n const distance = box1.top - box2.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxNear(box1, box2, maxDistance) {\n const kThreshold = maxDistance === void 0 ? 50 : maxDistance;\n let score = 0;\n if (box1.left - box2.right >= 0)\n score += box1.left - box2.right;\n if (box2.left - box1.right >= 0)\n score += box2.left - box1.right;\n if (box2.top - box1.bottom >= 0)\n score += box2.top - box1.bottom;\n if (box1.top - box2.bottom >= 0)\n score += box1.top - box2.bottom;\n return score > kThreshold ? void 0 : score;\n}\nvar kLayoutSelectorNames = ["left-of", "right-of", "above", "below", "near"];\nfunction layoutSelectorScore(name, element, inner, maxDistance) {\n const box = element.getBoundingClientRect();\n const scorer = { "left-of": boxLeftOf, "right-of": boxRightOf, "above": boxAbove, "below": boxBelow, "near": boxNear }[name];\n let bestScore;\n for (const e of inner) {\n if (e === element)\n continue;\n const score = scorer(box, e.getBoundingClientRect(), maxDistance);\n if (score === void 0)\n continue;\n if (bestScore === void 0 || score < bestScore)\n bestScore = score;\n }\n return bestScore;\n}\n\n// packages/injected/src/selectorUtils.ts\nfunction matchesAttributePart(value, attr) {\n const objValue = typeof value === "string" && !attr.caseSensitive ? value.toUpperCase() : value;\n const attrValue = typeof attr.value === "string" && !attr.caseSensitive ? attr.value.toUpperCase() : attr.value;\n if (attr.op === "")\n return !!objValue;\n if (attr.op === "=") {\n if (attrValue instanceof RegExp)\n return typeof objValue === "string" && !!objValue.match(attrValue);\n return objValue === attrValue;\n }\n if (typeof objValue !== "string" || typeof attrValue !== "string")\n return false;\n if (attr.op === "*=")\n return objValue.includes(attrValue);\n if (attr.op === "^=")\n return objValue.startsWith(attrValue);\n if (attr.op === "$=")\n return objValue.endsWith(attrValue);\n if (attr.op === "|=")\n return objValue === attrValue || objValue.startsWith(attrValue + "-");\n if (attr.op === "~=")\n return objValue.split(" ").includes(attrValue);\n return false;\n}\nfunction shouldSkipForTextMatching(element) {\n const document = element.ownerDocument;\n return element.nodeName === "SCRIPT" || element.nodeName === "NOSCRIPT" || element.nodeName === "STYLE" || document.head && document.head.contains(element);\n}\nfunction elementText(cache, root) {\n let value = cache.get(root);\n if (value === void 0) {\n value = { full: "", normalized: "", immediate: [] };\n if (!shouldSkipForTextMatching(root)) {\n let currentImmediate = "";\n if (root instanceof HTMLInputElement && (root.type === "submit" || root.type === "button")) {\n value = { full: root.value, normalized: normalizeWhiteSpace(root.value), immediate: [root.value] };\n } else {\n for (let child = root.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.TEXT_NODE) {\n value.full += child.nodeValue || "";\n currentImmediate += child.nodeValue || "";\n } else if (child.nodeType === Node.COMMENT_NODE) {\n continue;\n } else {\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n currentImmediate = "";\n if (child.nodeType === Node.ELEMENT_NODE)\n value.full += elementText(cache, child).full;\n }\n }\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n if (root.shadowRoot)\n value.full += elementText(cache, root.shadowRoot).full;\n if (value.full)\n value.normalized = normalizeWhiteSpace(value.full);\n }\n }\n cache.set(root, value);\n }\n return value;\n}\nfunction elementMatchesText(cache, element, matcher) {\n if (shouldSkipForTextMatching(element))\n return "none";\n if (!matcher(elementText(cache, element)))\n return "none";\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.ELEMENT_NODE && matcher(elementText(cache, child)))\n return "selfAndChildren";\n }\n if (element.shadowRoot && matcher(elementText(cache, element.shadowRoot)))\n return "selfAndChildren";\n return "self";\n}\nfunction getElementLabels(textCache, element) {\n const labels = getAriaLabelledByElements(element);\n if (labels)\n return labels.map((label) => elementText(textCache, label));\n const ariaLabel = element.getAttribute("aria-label");\n if (ariaLabel !== null && !!ariaLabel.trim())\n return [{ full: ariaLabel, normalized: normalizeWhiteSpace(ariaLabel), immediate: [ariaLabel] }];\n const isNonHiddenInput = element.nodeName === "INPUT" && element.type !== "hidden";\n if (["BUTTON", "METER", "OUTPUT", "PROGRESS", "SELECT", "TEXTAREA"].includes(element.nodeName) || isNonHiddenInput) {\n const labels2 = element.labels;\n if (labels2)\n return [...labels2].map((label) => elementText(textCache, label));\n }\n return [];\n}\n\n// packages/injected/src/roleSelectorEngine.ts\nvar kSupportedAttributes = ["selected", "checked", "pressed", "expanded", "level", "disabled", "name", "description", "include-hidden"];\nkSupportedAttributes.sort();\nfunction validateSupportedRole(attr, roles, role) {\n if (!roles.includes(role))\n throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map((role2) => `"${role2}"`).join(", ")}`);\n}\nfunction validateSupportedValues(attr, values) {\n if (attr.op !== "" && !values.includes(attr.value))\n throw new Error(`"${attr.name}" must be one of ${values.map((v) => JSON.stringify(v)).join(", ")}`);\n}\nfunction validateSupportedOp(attr, ops) {\n if (!ops.includes(attr.op))\n throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);\n}\nfunction validateAttributes(attrs, role) {\n const options = { role };\n for (const attr of attrs) {\n switch (attr.name) {\n case "checked": {\n validateSupportedRole(attr.name, kAriaCheckedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.checked = attr.op === "" ? true : attr.value;\n break;\n }\n case "pressed": {\n validateSupportedRole(attr.name, kAriaPressedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.pressed = attr.op === "" ? true : attr.value;\n break;\n }\n case "selected": {\n validateSupportedRole(attr.name, kAriaSelectedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.selected = attr.op === "" ? true : attr.value;\n break;\n }\n case "expanded": {\n validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.expanded = attr.op === "" ? true : attr.value;\n break;\n }\n case "level": {\n validateSupportedRole(attr.name, kAriaLevelRoles, role);\n if (typeof attr.value === "string")\n attr.value = +attr.value;\n if (attr.op !== "=" || typeof attr.value !== "number" || Number.isNaN(attr.value))\n throw new Error(`"level" attribute must be compared to a number`);\n options.level = attr.value;\n break;\n }\n case "disabled": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.disabled = attr.op === "" ? true : attr.value;\n break;\n }\n case "name": {\n if (attr.op === "")\n throw new Error(`"name" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"name" attribute must be a string or a regular expression`);\n options.name = attr.value;\n options.nameOp = attr.op;\n options.nameExact = attr.caseSensitive;\n break;\n }\n case "description": {\n if (attr.op === "")\n throw new Error(`"description" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"description" attribute must be a string or a regular expression`);\n options.description = attr.value;\n options.descriptionOp = attr.op;\n options.descriptionExact = attr.caseSensitive;\n break;\n }\n case "include-hidden": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.includeHidden = attr.op === "" ? true : attr.value;\n break;\n }\n default: {\n throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map((a) => `"${a}"`).join(", ")}.`);\n }\n }\n }\n return options;\n}\nfunction queryRole(scope, options, internal) {\n const result = [];\n const match = (element) => {\n if (getAriaRole(element) !== options.role)\n return;\n if (options.selected !== void 0 && getAriaSelected(element) !== options.selected)\n return;\n if (options.checked !== void 0 && getAriaChecked(element) !== options.checked)\n return;\n if (options.pressed !== void 0 && getAriaPressed(element) !== options.pressed)\n return;\n if (options.expanded !== void 0 && getAriaExpanded(element) !== options.expanded)\n return;\n if (options.level !== void 0 && getAriaLevel(element) !== options.level)\n return;\n if (options.disabled !== void 0 && getAriaDisabled(element) !== options.disabled)\n return;\n if (!options.includeHidden) {\n const isHidden = isElementHiddenForAria(element);\n if (isHidden)\n return;\n }\n if (options.name !== void 0) {\n const accessibleName = normalizeWhiteSpace(getElementAccessibleName(element, !!options.includeHidden));\n if (typeof options.name === "string")\n options.name = normalizeWhiteSpace(options.name);\n if (internal && !options.nameExact && options.nameOp === "=")\n options.nameOp = "*=";\n if (!matchesAttributePart(accessibleName, { name: "", jsonPath: [], op: options.nameOp || "=", value: options.name, caseSensitive: !!options.nameExact }))\n return;\n }\n if (options.description !== void 0) {\n const accessibleDescription = normalizeWhiteSpace(getElementAccessibleDescription(element, !!options.includeHidden));\n if (typeof options.description === "string")\n options.description = normalizeWhiteSpace(options.description);\n if (internal && !options.descriptionExact && options.descriptionOp === "=")\n options.descriptionOp = "*=";\n if (!matchesAttributePart(accessibleDescription, { name: "", jsonPath: [], op: options.descriptionOp || "=", value: options.description, caseSensitive: !!options.descriptionExact }))\n return;\n }\n result.push(element);\n };\n const query = (root) => {\n const shadows = [];\n if (root.shadowRoot)\n shadows.push(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n match(element);\n if (element.shadowRoot)\n shadows.push(element.shadowRoot);\n }\n shadows.forEach(query);\n };\n query(scope);\n return result;\n}\nfunction createRoleEngine(internal) {\n return {\n queryAll: (scope, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n const role = parsed.name.toLowerCase();\n if (!role)\n throw new Error(`Role must not be empty`);\n const options = validateAttributes(parsed.attributes, role);\n beginAriaCaches();\n try {\n return queryRole(scope, options, internal);\n } finally {\n endAriaCaches();\n }\n }\n };\n}\n\n// packages/injected/src/selectorEvaluator.ts\nvar SelectorEvaluatorImpl = class {\n constructor() {\n this._retainCacheCounter = 0;\n this._cacheText = /* @__PURE__ */ new Map();\n this._cacheQueryCSS = /* @__PURE__ */ new Map();\n this._cacheMatches = /* @__PURE__ */ new Map();\n this._cacheQuery = /* @__PURE__ */ new Map();\n this._cacheMatchesSimple = /* @__PURE__ */ new Map();\n this._cacheMatchesParents = /* @__PURE__ */ new Map();\n this._cacheCallMatches = /* @__PURE__ */ new Map();\n this._cacheCallQuery = /* @__PURE__ */ new Map();\n this._cacheQuerySimple = /* @__PURE__ */ new Map();\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("not", notEngine);\n this._engines.set("is", isEngine);\n this._engines.set("where", isEngine);\n this._engines.set("has", hasEngine);\n this._engines.set("scope", scopeEngine);\n this._engines.set("light", lightEngine);\n this._engines.set("visible", visibleEngine);\n this._engines.set("text", textEngine);\n this._engines.set("text-is", textIsEngine);\n this._engines.set("text-matches", textMatchesEngine);\n this._engines.set("has-text", hasTextEngine);\n this._engines.set("right-of", createLayoutEngine("right-of"));\n this._engines.set("left-of", createLayoutEngine("left-of"));\n this._engines.set("above", createLayoutEngine("above"));\n this._engines.set("below", createLayoutEngine("below"));\n this._engines.set("near", createLayoutEngine("near"));\n this._engines.set("nth-match", nthMatchEngine);\n const allNames = [...this._engines.keys()];\n allNames.sort();\n const parserNames = [...customCSSNames];\n parserNames.sort();\n if (allNames.join("|") !== parserNames.join("|"))\n throw new Error(`Please keep customCSSNames in sync with evaluator engines: ${allNames.join("|")} vs ${parserNames.join("|")}`);\n }\n begin() {\n ++this._retainCacheCounter;\n }\n end() {\n --this._retainCacheCounter;\n if (!this._retainCacheCounter) {\n this._cacheQueryCSS.clear();\n this._cacheMatches.clear();\n this._cacheQuery.clear();\n this._cacheMatchesSimple.clear();\n this._cacheMatchesParents.clear();\n this._cacheCallMatches.clear();\n this._cacheCallQuery.clear();\n this._cacheQuerySimple.clear();\n this._cacheText.clear();\n }\n }\n _cached(cache, main, rest, cb) {\n if (!cache.has(main))\n cache.set(main, []);\n const entries = cache.get(main);\n const entry = entries.find((e) => rest.every((value, index) => e.rest[index] === value));\n if (entry)\n return entry.result;\n const result = cb();\n entries.push({ rest, result });\n return result;\n }\n _checkSelector(s) {\n const wellFormed = typeof s === "object" && s && (Array.isArray(s) || "simples" in s && s.simples.length);\n if (!wellFormed)\n throw new Error(`Malformed selector "${s}"`);\n return s;\n }\n matches(element, s, context) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheMatches, element, [selector, context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._matchesEngine(isEngine, element, selector, context);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n if (!this._matchesSimple(element, selector.simples[selector.simples.length - 1].selector, context))\n return false;\n return this._matchesParents(element, selector, selector.simples.length - 2, context);\n });\n } finally {\n this.end();\n }\n }\n query(context, s) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheQuery, selector, [context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._queryEngine(isEngine, context, selector);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n const previousScoreMap = this._scoreMap;\n this._scoreMap = /* @__PURE__ */ new Map();\n let elements = this._querySimple(context, selector.simples[selector.simples.length - 1].selector);\n elements = elements.filter((element) => this._matchesParents(element, selector, selector.simples.length - 2, context));\n if (this._scoreMap.size) {\n elements.sort((a, b) => {\n const aScore = this._scoreMap.get(a);\n const bScore = this._scoreMap.get(b);\n if (aScore === bScore)\n return 0;\n if (aScore === void 0)\n return 1;\n if (bScore === void 0)\n return -1;\n return aScore - bScore;\n });\n }\n this._scoreMap = previousScoreMap;\n return elements;\n });\n } finally {\n this.end();\n }\n }\n _markScore(element, score) {\n if (this._scoreMap)\n this._scoreMap.set(element, score);\n }\n _hasScopeClause(selector) {\n return selector.simples.some((simple) => simple.selector.functions.some((f) => f.name === "scope"));\n }\n _expandContextForScopeMatching(context) {\n if (context.scope.nodeType !== 1)\n return context;\n const scope = parentElementOrShadowHost(context.scope);\n if (!scope)\n return context;\n return { ...context, scope, originalScope: context.originalScope || context.scope };\n }\n _matchesSimple(element, simple, context) {\n return this._cached(this._cacheMatchesSimple, element, [simple, context.scope, context.pierceShadow, context.originalScope], () => {\n if (element === context.scope)\n return false;\n if (simple.css && !this._matchesCSS(element, simple.css))\n return false;\n for (const func of simple.functions) {\n if (!this._matchesEngine(this._getEngine(func.name), element, func.args, context))\n return false;\n }\n return true;\n });\n }\n _querySimple(context, simple) {\n if (!simple.functions.length)\n return this._queryCSS(context, simple.css || "*");\n return this._cached(this._cacheQuerySimple, simple, [context.scope, context.pierceShadow, context.originalScope], () => {\n let css = simple.css;\n const funcs = simple.functions;\n if (css === "*" && funcs.length)\n css = void 0;\n let elements;\n let firstIndex = -1;\n if (css !== void 0) {\n elements = this._queryCSS(context, css);\n } else {\n firstIndex = funcs.findIndex((func) => this._getEngine(func.name).query !== void 0);\n if (firstIndex === -1)\n firstIndex = 0;\n elements = this._queryEngine(this._getEngine(funcs[firstIndex].name), context, funcs[firstIndex].args);\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches !== void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches === void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n return elements;\n });\n }\n _matchesParents(element, complex, index, context) {\n if (index < 0)\n return true;\n return this._cached(this._cacheMatchesParents, element, [complex, index, context.scope, context.pierceShadow, context.originalScope], () => {\n const { selector: simple, combinator } = complex.simples[index];\n if (combinator === ">") {\n const parent = parentElementOrShadowHostInContext(element, context);\n if (!parent || !this._matchesSimple(parent, simple, context))\n return false;\n return this._matchesParents(parent, complex, index - 1, context);\n }\n if (combinator === "+") {\n const previousSibling = previousSiblingInContext(element, context);\n if (!previousSibling || !this._matchesSimple(previousSibling, simple, context))\n return false;\n return this._matchesParents(previousSibling, complex, index - 1, context);\n }\n if (combinator === "") {\n let parent = parentElementOrShadowHostInContext(element, context);\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n if (combinator === "~") {\n let previousSibling = previousSiblingInContext(element, context);\n while (previousSibling) {\n if (this._matchesSimple(previousSibling, simple, context)) {\n if (this._matchesParents(previousSibling, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "~")\n break;\n }\n previousSibling = previousSiblingInContext(previousSibling, context);\n }\n return false;\n }\n if (combinator === ">=") {\n let parent = element;\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n throw new Error(`Unsupported combinator "${combinator}"`);\n });\n }\n _matchesEngine(engine, element, args, context) {\n if (engine.matches)\n return this._callMatches(engine, element, args, context);\n if (engine.query)\n return this._callQuery(engine, args, context).includes(element);\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _queryEngine(engine, context, args) {\n if (engine.query)\n return this._callQuery(engine, args, context);\n if (engine.matches)\n return this._queryCSS(context, "*").filter((element) => this._callMatches(engine, element, args, context));\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _callMatches(engine, element, args, context) {\n return this._cached(this._cacheCallMatches, element, [engine, context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.matches(element, args, context, this);\n });\n }\n _callQuery(engine, args, context) {\n return this._cached(this._cacheCallQuery, engine, [context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.query(context, args, this);\n });\n }\n _matchesCSS(element, css) {\n return element.matches(css);\n }\n _queryCSS(context, css) {\n return this._cached(this._cacheQueryCSS, css, [context.scope, context.pierceShadow, context.originalScope], () => {\n let result = [];\n function query(root) {\n result = result.concat([...root.querySelectorAll(css)]);\n if (!context.pierceShadow)\n return;\n if (root.shadowRoot)\n query(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n if (element.shadowRoot)\n query(element.shadowRoot);\n }\n }\n query(context.scope);\n return result;\n });\n }\n _getEngine(name) {\n const engine = this._engines.get(name);\n if (!engine)\n throw new Error(`Unknown selector engine "${name}"`);\n return engine;\n }\n};\nvar isEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n return args.some((selector) => evaluator.matches(element, selector, context));\n },\n query(context, args, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n let elements = [];\n for (const arg of args)\n elements = elements.concat(evaluator.query(context, arg));\n return args.length === 1 ? elements : sortInDOMOrder(elements);\n }\n};\nvar hasEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"has" engine expects non-empty selector list`);\n return evaluator.query({ ...context, scope: element }, args).length > 0;\n }\n // TODO: we can implement efficient "query" by matching "args" and returning\n // all parents/descendants, just have to be careful with the ":scope" matching.\n};\nvar scopeEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9)\n return element === actualScope.documentElement;\n return element === actualScope;\n },\n query(context, args, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9) {\n const root = actualScope.documentElement;\n return root ? [root] : [];\n }\n if (actualScope.nodeType === 1)\n return [actualScope];\n return [];\n }\n};\nvar notEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"not" engine expects non-empty selector list`);\n return !evaluator.matches(element, args, context);\n }\n};\nvar lightEngine = {\n query(context, args, evaluator) {\n return evaluator.query({ ...context, pierceShadow: false }, args);\n },\n matches(element, args, context, evaluator) {\n return evaluator.matches(element, args, { ...context, pierceShadow: false });\n }\n};\nvar visibleEngine = {\n matches(element, args, context, evaluator) {\n if (args.length)\n throw new Error(`"visible" engine expects no arguments`);\n return isElementVisible(element);\n }\n};\nvar textEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar textIsEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text-is" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]);\n const matcher = (elementText2) => {\n if (!text && !elementText2.immediate.length)\n return true;\n return elementText2.immediate.some((s) => normalizeWhiteSpace(s) === text);\n };\n return elementMatchesText(evaluator._cacheText, element, matcher) !== "none";\n }\n};\nvar textMatchesEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0 || typeof args[0] !== "string" || args.length > 2 || args.length === 2 && typeof args[1] !== "string")\n throw new Error(`"text-matches" engine expects a regexp body and optional regexp flags`);\n const re = new RegExp(args[0], args.length === 2 ? args[1] : void 0);\n const matcher = (elementText2) => re.test(elementText2.full);\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar hasTextEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"has-text" engine expects a single string`);\n if (shouldSkipForTextMatching(element))\n return false;\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return matcher(elementText(evaluator._cacheText, element));\n }\n};\nfunction createLayoutEngine(name) {\n return {\n matches(element, args, context, evaluator) {\n const maxDistance = args.length && typeof args[args.length - 1] === "number" ? args[args.length - 1] : void 0;\n const queryArgs = maxDistance === void 0 ? args : args.slice(0, args.length - 1);\n if (args.length < 1 + (maxDistance === void 0 ? 0 : 1))\n throw new Error(`"${name}" engine expects a selector list and optional maximum distance in pixels`);\n const inner = evaluator.query(context, queryArgs);\n const score = layoutSelectorScore(name, element, inner, maxDistance);\n if (score === void 0)\n return false;\n evaluator._markScore(element, score);\n return true;\n }\n };\n}\nvar nthMatchEngine = {\n query(context, args, evaluator) {\n let index = args[args.length - 1];\n if (args.length < 2)\n throw new Error(`"nth-match" engine expects non-empty selector list and an index argument`);\n if (typeof index !== "number" || index < 1)\n throw new Error(`"nth-match" engine expects a one-based index as the last argument`);\n const elements = isEngine.query(context, args.slice(0, args.length - 1), evaluator);\n index--;\n return index < elements.length ? [elements[index]] : [];\n }\n};\nfunction parentElementOrShadowHostInContext(element, context) {\n if (element === context.scope)\n return;\n if (!context.pierceShadow)\n return element.parentElement || void 0;\n return parentElementOrShadowHost(element);\n}\nfunction previousSiblingInContext(element, context) {\n if (element === context.scope)\n return;\n return element.previousElementSibling || void 0;\n}\nfunction sortInDOMOrder(elements) {\n const elementToEntry = /* @__PURE__ */ new Map();\n const roots = [];\n const result = [];\n function append(element) {\n let entry = elementToEntry.get(element);\n if (entry)\n return entry;\n const parent = parentElementOrShadowHost(element);\n if (parent) {\n const parentEntry = append(parent);\n parentEntry.children.push(element);\n } else {\n roots.push(element);\n }\n entry = { children: [], taken: false };\n elementToEntry.set(element, entry);\n return entry;\n }\n for (const e of elements)\n append(e).taken = true;\n function visit(element) {\n const entry = elementToEntry.get(element);\n if (entry.taken)\n result.push(element);\n if (entry.children.length > 1) {\n const set = new Set(entry.children);\n entry.children = [];\n let child = element.firstElementChild;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n child = element.shadowRoot ? element.shadowRoot.firstElementChild : null;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n }\n entry.children.forEach(visit);\n }\n roots.forEach(visit);\n return result;\n}\n\n// packages/injected/src/selectorGenerator.ts\nvar kTextScoreRange = 10;\nvar kExactPenalty = kTextScoreRange / 2;\nvar kTestIdScore = 1;\nvar kOtherTestIdScore = 2;\nvar kIframeByAttributeScore = 10;\nvar kBeginPenalizedScore = 50;\nvar kRoleWithNameScore = 100;\nvar kPlaceholderScore = 120;\nvar kLabelScore = 140;\nvar kAltTextScore = 160;\nvar kTextScore = 180;\nvar kTitleScore = 200;\nvar kTextScoreRegex = 250;\nvar kPlaceholderScoreExact = kPlaceholderScore + kExactPenalty;\nvar kLabelScoreExact = kLabelScore + kExactPenalty;\nvar kRoleWithNameScoreExact = kRoleWithNameScore + kExactPenalty;\nvar kAltTextScoreExact = kAltTextScore + kExactPenalty;\nvar kTextScoreExact = kTextScore + kExactPenalty;\nvar kTitleScoreExact = kTitleScore + kExactPenalty;\nvar kEndPenalizedScore = 300;\nvar kCSSIdScore = 500;\nvar kRoleWithoutNameScore = 510;\nvar kCSSInputTypeNameScore = 520;\nvar kCSSTagNameScore = 530;\nvar kNthScore = 1e4;\nvar kCSSFallbackScore = 1e7;\nvar kScoreThresholdForTextExpect = 1e3;\nfunction generateSelector(injectedScript, targetElement, options) {\n var _a;\n injectedScript._evaluator.begin();\n const cache = { allowText: /* @__PURE__ */ new Map(), disallowText: /* @__PURE__ */ new Map() };\n beginAriaCaches();\n beginDOMCaches();\n try {\n let selectors = [];\n if (options.forTextExpect) {\n let targetTokens = cssFallback(injectedScript, targetElement.ownerDocument.documentElement, options);\n for (let element = targetElement; element; element = parentElementOrShadowHost(element)) {\n const tokens = generateSelectorFor(cache, injectedScript, element, { ...options, noText: true });\n if (!tokens)\n continue;\n const score = combineScores(tokens);\n if (score <= kScoreThresholdForTextExpect) {\n targetTokens = tokens;\n break;\n }\n }\n selectors = [joinTokens(targetTokens)];\n } else {\n if (!targetElement.matches("input,textarea,select") && !targetElement.isContentEditable) {\n const interactiveParent = closestCrossShadow(targetElement, "button,select,input,[role=button],[role=checkbox],[role=radio],a,[role=link]", options.root);\n if (interactiveParent && isElementVisible(interactiveParent))\n targetElement = interactiveParent;\n }\n if (options.multiple) {\n const withText = generateSelectorFor(cache, injectedScript, targetElement, options);\n const withoutText = generateSelectorFor(cache, injectedScript, targetElement, { ...options, noText: true });\n let tokens = [withText, withoutText];\n cache.allowText.clear();\n cache.disallowText.clear();\n if (withText && hasCSSIdToken(withText))\n tokens.push(generateSelectorFor(cache, injectedScript, targetElement, { ...options, noCSSId: true }));\n if (withoutText && hasCSSIdToken(withoutText))\n tokens.push(generateSelectorFor(cache, injectedScript, targetElement, { ...options, noText: true, noCSSId: true }));\n tokens = tokens.filter(Boolean);\n if (!tokens.length) {\n const css = cssFallback(injectedScript, targetElement, options);\n tokens.push(css);\n if (hasCSSIdToken(css))\n tokens.push(cssFallback(injectedScript, targetElement, { ...options, noCSSId: true }));\n }\n selectors = [...new Set(tokens.map((t) => joinTokens(t)))];\n } else {\n const targetTokens = generateSelectorFor(cache, injectedScript, targetElement, options) || cssFallback(injectedScript, targetElement, options);\n selectors = [joinTokens(targetTokens)];\n }\n }\n const selector = selectors[0];\n const parsedSelector = injectedScript.parseSelector(selector);\n return {\n selector,\n selectors,\n elements: injectedScript.querySelectorAll(parsedSelector, (_a = options.root) != null ? _a : targetElement.ownerDocument)\n };\n } finally {\n endDOMCaches();\n endAriaCaches();\n injectedScript._evaluator.end();\n }\n}\nfunction generateSelectorFor(cache, injectedScript, targetElement, options) {\n var _a;\n if (options.root && !isInsideScope(options.root, targetElement))\n throw new Error(`Target element must belong to the root\'s subtree`);\n if (targetElement === options.root)\n return [{ engine: "css", selector: ":scope", score: 1 }];\n if (targetElement.ownerDocument.documentElement === targetElement)\n return [{ engine: "css", selector: "html", score: 1 }];\n let result = null;\n const updateResult = (candidate) => {\n if (!result || combineScores(candidate) < combineScores(result))\n result = candidate;\n };\n const candidates = [];\n if (!options.noText) {\n for (const candidate of buildTextCandidates(injectedScript, targetElement, !options.isRecursive))\n candidates.push({ candidate, isTextCandidate: true });\n }\n for (const token of buildNoTextCandidates(injectedScript, targetElement, options)) {\n if (options.omitInternalEngines && token.engine.startsWith("internal:"))\n continue;\n candidates.push({ candidate: [token], isTextCandidate: false });\n }\n candidates.sort((a, b) => combineScores(a.candidate) - combineScores(b.candidate));\n for (const { candidate, isTextCandidate } of candidates) {\n const elements = injectedScript.querySelectorAll(injectedScript.parseSelector(joinTokens(candidate)), (_a = options.root) != null ? _a : targetElement.ownerDocument);\n if (!elements.includes(targetElement)) {\n continue;\n }\n if (elements.length === 1) {\n updateResult(candidate);\n break;\n }\n const index = elements.indexOf(targetElement);\n if (index > 5) {\n continue;\n }\n updateResult([...candidate, { engine: "nth", selector: String(index), score: kNthScore }]);\n if (options.isRecursive) {\n continue;\n }\n for (let parent = parentElementOrShadowHost(targetElement); parent && parent !== options.root; parent = parentElementOrShadowHost(parent)) {\n const filtered = elements.filter((e) => isInsideScope(parent, e) && e !== parent);\n const newIndex = filtered.indexOf(targetElement);\n if (filtered.length > 5 || newIndex === -1 || newIndex === index && filtered.length > 1) {\n continue;\n }\n const inParent = filtered.length === 1 ? candidate : [...candidate, { engine: "nth", selector: String(newIndex), score: kNthScore }];\n const idealSelectorForParent = { engine: "", selector: "", score: 1 };\n if (result && combineScores([idealSelectorForParent, ...inParent]) >= combineScores(result)) {\n continue;\n }\n const noText = !!options.noText || isTextCandidate;\n const cacheMap = noText ? cache.disallowText : cache.allowText;\n let parentTokens = cacheMap.get(parent);\n if (parentTokens === void 0) {\n parentTokens = generateSelectorFor(cache, injectedScript, parent, { ...options, isRecursive: true, noText }) || cssFallback(injectedScript, parent, options);\n cacheMap.set(parent, parentTokens);\n }\n if (!parentTokens)\n continue;\n updateResult([...parentTokens, ...inParent]);\n }\n }\n return result;\n}\nfunction buildNoTextCandidates(injectedScript, element, options) {\n const candidates = [];\n const testIdAttributeNames = splitTestIdAttributeNames(options.testIdAttributeName);\n {\n for (const attr of ["data-testid", "data-test-id", "data-test"]) {\n if (!testIdAttributeNames.includes(attr) && element.getAttribute(attr))\n candidates.push({ engine: "css", selector: `[${attr}=${quoteCSSAttributeValue(element.getAttribute(attr))}]`, score: kOtherTestIdScore });\n }\n if (!options.noCSSId) {\n const idAttr = element.getAttribute("id");\n if (idAttr && !isGuidLike(idAttr))\n candidates.push({ engine: "css", selector: makeSelectorForId(idAttr), score: kCSSIdScore });\n }\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore });\n }\n if (element.nodeName === "IFRAME") {\n for (const attribute of ["name", "title"]) {\n if (element.getAttribute(attribute))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[${attribute}=${quoteCSSAttributeValue(element.getAttribute(attribute))}]`, score: kIframeByAttributeScore });\n }\n for (const testIdAttr of testIdAttributeNames) {\n if (element.getAttribute(testIdAttr))\n candidates.push({ engine: "css", selector: `[${testIdAttr}=${quoteCSSAttributeValue(element.getAttribute(testIdAttr))}]`, score: kTestIdScore });\n }\n penalizeScoreForLength([candidates]);\n return candidates;\n }\n for (const testIdAttr of testIdAttributeNames) {\n if (element.getAttribute(testIdAttr))\n candidates.push({ engine: "internal:testid", selector: `[${testIdAttr}=${escapeForAttributeSelector(element.getAttribute(testIdAttr), true)}]`, score: kTestIdScore });\n }\n if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") {\n const input = element;\n if (input.placeholder) {\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(input.placeholder, true)}]`, score: kPlaceholderScoreExact });\n for (const alternative of suitableTextAlternatives(input.placeholder))\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(alternative.text, false)}]`, score: kPlaceholderScore - alternative.scoreBonus });\n }\n }\n const labels = getElementLabels(injectedScript._evaluator._cacheText, element);\n for (const label of labels) {\n const labelText = label.normalized;\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(labelText, true), score: kLabelScoreExact });\n for (const alternative of suitableTextAlternatives(labelText))\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(alternative.text, false), score: kLabelScore - alternative.scoreBonus });\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole))\n candidates.push({ engine: "internal:role", selector: ariaRole, score: kRoleWithoutNameScore });\n if (element.getAttribute("name") && ["BUTTON", "FORM", "FIELDSET", "FRAME", "IFRAME", "INPUT", "KEYGEN", "OBJECT", "OUTPUT", "SELECT", "TEXTAREA", "MAP", "META", "PARAM"].includes(element.nodeName))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[name=${quoteCSSAttributeValue(element.getAttribute("name"))}]`, score: kCSSInputTypeNameScore });\n if (["INPUT", "TEXTAREA"].includes(element.nodeName) && element.getAttribute("type") !== "hidden") {\n if (element.getAttribute("type"))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[type=${quoteCSSAttributeValue(element.getAttribute("type"))}]`, score: kCSSInputTypeNameScore });\n }\n if (["INPUT", "TEXTAREA", "SELECT"].includes(element.nodeName) && element.getAttribute("type") !== "hidden")\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSInputTypeNameScore + 1 });\n penalizeScoreForLength([candidates]);\n return candidates;\n}\nfunction buildTextCandidates(injectedScript, element, isTargetNode) {\n if (element.nodeName === "SELECT")\n return [];\n const candidates = [];\n const title = element.getAttribute("title");\n if (title) {\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(title, true)}]`, score: kTitleScoreExact }]);\n for (const alternative of suitableTextAlternatives(title))\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(alternative.text, false)}]`, score: kTitleScore - alternative.scoreBonus }]);\n }\n const alt = element.getAttribute("alt");\n if (alt && ["APPLET", "AREA", "IMG", "INPUT"].includes(element.nodeName)) {\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alt, true)}]`, score: kAltTextScoreExact }]);\n for (const alternative of suitableTextAlternatives(alt))\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alternative.text, false)}]`, score: kAltTextScore - alternative.scoreBonus }]);\n }\n const text = elementText(injectedScript._evaluator._cacheText, element).normalized;\n const textAlternatives = text ? suitableTextAlternatives(text) : [];\n if (text) {\n if (isTargetNode) {\n if (text.length <= 80)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(text, true), score: kTextScoreExact }]);\n for (const alternative of textAlternatives)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n }\n const cssToken = { engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore };\n for (const alternative of textAlternatives)\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (isTargetNode && text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole)) {\n const ariaName = getElementAccessibleName(element, false);\n if (ariaName && !ariaName.match(/^\\p{Co}+$/u)) {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}]`, score: kRoleWithNameScoreExact };\n candidates.push([roleToken]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus }]);\n const ariaDescription = getElementAccessibleDescription(element, false);\n if (ariaDescription) {\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}][description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithNameScoreExact + 1 }]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}][description=${escapeForAttributeSelector(ariaDescription, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus + 1 }]);\n }\n } else {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}`, score: kRoleWithoutNameScore };\n const ariaDescription = getElementAccessibleDescription(element, false);\n if (ariaDescription)\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithoutNameScore + 1 }]);\n for (const alternative of textAlternatives)\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (isTargetNode && text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n }\n penalizeScoreForLength(candidates);\n return candidates;\n}\nfunction makeSelectorForId(id) {\n return /^[a-zA-Z][a-zA-Z0-9\\-\\_]+$/.test(id) ? "#" + id : `[id=${quoteCSSAttributeValue(id)}]`;\n}\nfunction hasCSSIdToken(tokens) {\n return tokens.some((token) => token.engine === "css" && (token.selector.startsWith("#") || token.selector.startsWith(\'[id="\')));\n}\nfunction cssFallback(injectedScript, targetElement, options) {\n var _a;\n const root = (_a = options.root) != null ? _a : targetElement.ownerDocument;\n const tokens = [];\n function uniqueCSSSelector(prefix) {\n const path = tokens.slice();\n if (prefix)\n path.unshift(prefix);\n const selector = path.join(" > ");\n const parsedSelector = injectedScript.parseSelector(selector);\n const node = injectedScript.querySelector(parsedSelector, root, false);\n return node === targetElement ? selector : void 0;\n }\n function makeStrict(selector) {\n const token = { engine: "css", selector, score: kCSSFallbackScore };\n const parsedSelector = injectedScript.parseSelector(selector);\n const elements = injectedScript.querySelectorAll(parsedSelector, root);\n if (elements.length === 1)\n return [token];\n const nth = { engine: "nth", selector: String(elements.indexOf(targetElement)), score: kNthScore };\n return [token, nth];\n }\n for (let element = targetElement; element && element !== root; element = parentElementOrShadowHost(element)) {\n let bestTokenForLevel = "";\n if (element.id && !options.noCSSId) {\n const token = makeSelectorForId(element.id);\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n bestTokenForLevel = token;\n }\n const parent = element.parentNode;\n const classes = [...element.classList].map(escapeClassName);\n for (let i = 0; i < classes.length; ++i) {\n const token = "." + classes.slice(0, i + 1).join(".");\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel && parent) {\n const sameClassSiblings = parent.querySelectorAll(token);\n if (sameClassSiblings.length === 1)\n bestTokenForLevel = token;\n }\n }\n if (parent) {\n const siblings = [...parent.children];\n const nodeName = element.nodeName;\n const sameTagSiblings = siblings.filter((sibling) => sibling.nodeName === nodeName);\n const token = sameTagSiblings.indexOf(element) === 0 ? escapeNodeName(element) : `${escapeNodeName(element)}:nth-child(${1 + siblings.indexOf(element)})`;\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel)\n bestTokenForLevel = token;\n } else if (!bestTokenForLevel) {\n bestTokenForLevel = escapeNodeName(element);\n }\n tokens.unshift(bestTokenForLevel);\n }\n return makeStrict(uniqueCSSSelector());\n}\nfunction penalizeScoreForLength(groups) {\n for (const group of groups) {\n for (const token of group) {\n if (token.score > kBeginPenalizedScore && token.score < kEndPenalizedScore)\n token.score += Math.min(kTextScoreRange, token.selector.length / 10 | 0);\n }\n }\n}\nfunction joinTokens(tokens) {\n const parts = [];\n let lastEngine = "";\n for (const { engine, selector } of tokens) {\n if (parts.length && (lastEngine !== "css" || engine !== "css" || selector.startsWith(":nth-match(")))\n parts.push(">>");\n lastEngine = engine;\n if (engine === "css")\n parts.push(selector);\n else\n parts.push(`${engine}=${selector}`);\n }\n return parts.join(" ");\n}\nfunction combineScores(tokens) {\n let score = 0;\n for (let i = 0; i < tokens.length; i++)\n score += tokens[i].score * (tokens.length - i);\n return score;\n}\nfunction isGuidLike(id) {\n let lastCharacterType;\n let transitionCount = 0;\n for (let i = 0; i < id.length; ++i) {\n const c = id[i];\n let characterType;\n if (c === "-" || c === "_")\n continue;\n if (c >= "a" && c <= "z")\n characterType = "lower";\n else if (c >= "A" && c <= "Z")\n characterType = "upper";\n else if (c >= "0" && c <= "9")\n characterType = "digit";\n else\n characterType = "other";\n if (characterType === "lower" && lastCharacterType === "upper") {\n lastCharacterType = characterType;\n continue;\n }\n if (lastCharacterType && lastCharacterType !== characterType)\n ++transitionCount;\n lastCharacterType = characterType;\n }\n return transitionCount >= id.length / 4;\n}\nfunction trimWordBoundary(text, maxLength) {\n if (text.length <= maxLength)\n return text;\n text = text.substring(0, maxLength);\n const match = text.match(/^(.*)\\b(.+?)$/);\n if (!match)\n return "";\n return match[1].trimEnd();\n}\nfunction suitableTextAlternatives(text) {\n let result = [];\n {\n const match = text.match(/^([\\d.,]+)[^.,\\w]/);\n const leadingNumberLength = match ? match[1].length : 0;\n if (leadingNumberLength) {\n const alt = trimWordBoundary(text.substring(leadingNumberLength).trimStart(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n {\n const match = text.match(/[^.,\\w]([\\d.,]+)$/);\n const trailingNumberLength = match ? match[1].length : 0;\n if (trailingNumberLength) {\n const alt = trimWordBoundary(text.substring(0, text.length - trailingNumberLength).trimEnd(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n if (text.length <= 30) {\n result.push({ text, scoreBonus: 0 });\n } else {\n result.push({ text: trimWordBoundary(text, 80), scoreBonus: 0 });\n result.push({ text: trimWordBoundary(text, 30), scoreBonus: 1 });\n }\n result = result.filter((r) => r.text);\n if (!result.length)\n result.push({ text: text.substring(0, 80), scoreBonus: 0 });\n return result;\n}\nfunction escapeNodeName(node) {\n return node.nodeName.toLocaleLowerCase().replace(/[:\\.]/g, (char) => "\\\\" + char);\n}\nfunction escapeClassName(className) {\n let result = "";\n for (let i = 0; i < className.length; i++)\n result += cssEscapeCharacter(className, i);\n return result;\n}\nfunction cssEscapeCharacter(s, i) {\n const c = s.charCodeAt(i);\n if (c === 0)\n return "\\uFFFD";\n if (c >= 1 && c <= 31 || c >= 48 && c <= 57 && (i === 0 || i === 1 && s.charCodeAt(0) === 45))\n return "\\\\" + c.toString(16) + " ";\n if (i === 0 && c === 45 && s.length === 1)\n return "\\\\" + s.charAt(i);\n if (c >= 128 || c === 45 || c === 95 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122)\n return s.charAt(i);\n return "\\\\" + s.charAt(i);\n}\n\n// packages/injected/src/xpathSelectorEngine.ts\nvar XPathEngine = {\n queryAll(root, selector) {\n if (selector.startsWith("/") && root.nodeType !== Node.DOCUMENT_NODE)\n selector = "." + selector;\n const result = [];\n const document = root.ownerDocument || root;\n if (!document)\n return result;\n const it = document.evaluate(selector, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);\n for (let node = it.iterateNext(); node; node = it.iterateNext()) {\n if (node.nodeType === Node.ELEMENT_NODE)\n result.push(node);\n }\n return result;\n }\n};\n\n// packages/injected/src/consoleApi.ts\nvar selectorSymbol = Symbol("selector");\nselectorSymbol;\nvar _Locator = class _Locator {\n constructor(injectedScript, selector, options) {\n if (options == null ? void 0 : options.hasText)\n selector += ` >> internal:has-text=${escapeForTextSelector(options.hasText, false)}`;\n if (options == null ? void 0 : options.hasNotText)\n selector += ` >> internal:has-not-text=${escapeForTextSelector(options.hasNotText, false)}`;\n if (options == null ? void 0 : options.has)\n selector += ` >> internal:has=` + JSON.stringify(options.has[selectorSymbol]);\n if (options == null ? void 0 : options.hasNot)\n selector += ` >> internal:has-not=` + JSON.stringify(options.hasNot[selectorSymbol]);\n if ((options == null ? void 0 : options.visible) !== void 0)\n selector += ` >> visible=${options.visible ? "true" : "false"}`;\n this[selectorSymbol] = selector;\n if (selector) {\n const parsed = injectedScript.parseSelector(selector);\n this.element = injectedScript.querySelector(parsed, injectedScript.document, false);\n this.elements = injectedScript.querySelectorAll(parsed, injectedScript.document);\n }\n const selectorBase = selector;\n const self = this;\n self.locator = (selector2, options2) => {\n return new _Locator(injectedScript, selectorBase ? selectorBase + " >> " + selector2 : selector2, options2);\n };\n self.getByTestId = (testId) => self.locator(getByTestIdSelector(injectedScript.testIdAttributeNameForStrictErrorAndConsoleCodegen(), testId));\n self.getByAltText = (text, options2) => self.locator(getByAltTextSelector(text, options2));\n self.getByLabel = (text, options2) => self.locator(getByLabelSelector(text, options2));\n self.getByPlaceholder = (text, options2) => self.locator(getByPlaceholderSelector(text, options2));\n self.getByText = (text, options2) => self.locator(getByTextSelector(text, options2));\n self.getByTitle = (text, options2) => self.locator(getByTitleSelector(text, options2));\n self.getByRole = (role, options2 = {}) => self.locator(getByRoleSelector(role, options2));\n self.filter = (options2) => new _Locator(injectedScript, selector, options2);\n self.first = () => self.locator("nth=0");\n self.last = () => self.locator("nth=-1");\n self.nth = (index) => self.locator(`nth=${index}`);\n self.and = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:and=` + JSON.stringify(locator[selectorSymbol]));\n self.or = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:or=` + JSON.stringify(locator[selectorSymbol]));\n }\n};\nvar Locator = _Locator;\nvar ConsoleAPI = class {\n constructor(injectedScript) {\n this._injectedScript = injectedScript;\n }\n install() {\n if (this._injectedScript.window.playwright)\n return;\n this._injectedScript.window.playwright = {\n $: (selector, strict) => this._querySelector(selector, !!strict),\n $$: (selector) => this._querySelectorAll(selector),\n inspect: (selector) => this._inspect(selector),\n selector: (element) => this._selector(element),\n generateLocator: (element, language) => this._generateLocator(element, language),\n ariaSnapshot: (element, options) => {\n return this._injectedScript.ariaSnapshot(element || this._injectedScript.document.body, options || { mode: "default" });\n },\n resume: () => this._resume(),\n ...new Locator(this._injectedScript, "")\n };\n delete this._injectedScript.window.playwright.filter;\n delete this._injectedScript.window.playwright.first;\n delete this._injectedScript.window.playwright.last;\n delete this._injectedScript.window.playwright.nth;\n delete this._injectedScript.window.playwright.and;\n delete this._injectedScript.window.playwright.or;\n }\n _querySelector(selector, strict) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.query(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelector(parsed, this._injectedScript.document, strict);\n }\n _querySelectorAll(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.$$(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelectorAll(parsed, this._injectedScript.document);\n }\n _inspect(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.inspect(\'Playwright >> selector\').`);\n this._injectedScript.window.inspect(this._querySelector(selector, false));\n }\n _selector(element) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.selector(element).`);\n return this._injectedScript.generateSelectorSimple(element);\n }\n _generateLocator(element, language) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.locator(element).`);\n const selector = this._injectedScript.generateSelectorSimple(element);\n return asLocator(language || "javascript", selector);\n }\n _resume() {\n if (!this._injectedScript.window.__pw_resume)\n return false;\n this._injectedScript.window.__pw_resume().catch(() => {\n });\n }\n};\n\n// packages/isomorphic/utilityScriptSerializers.ts\nfunction isRegExp2(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp2(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date,\n AbortSignal: global.AbortSignal\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n return returnByValue ? this._promiseAwareJsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _promiseAwareJsonValueNoThrow(value) {\n const safeJson = (value2) => {\n try {\n return this.jsonValue(true, value2);\n } catch (e) {\n return void 0;\n }\n };\n if (value && typeof value === "object" && typeof value.then === "function") {\n return (async () => {\n const promiseValue = await value;\n return safeJson(promiseValue);\n })();\n }\n return safeJson(value);\n }\n};\n\n// packages/injected/src/injectedScript.ts\nvar InjectedScript = class {\n constructor(window, options) {\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = "data-testid";\n this._lastAriaSnapshotForTrack = /* @__PURE__ */ new Map();\n // Recorder must use any external dependencies through InjectedScript.\n // Otherwise it will end up with a copy of all modules it uses, and any\n // module-level globals will be duplicated, which leads to subtle bugs.\n this.utils = {\n asLocator,\n cacheNormalizedWhitespaces,\n elementText,\n getAriaRole,\n getElementAccessibleDescription,\n getElementAccessibleName,\n isElementVisible,\n isInsideScope,\n normalizeWhiteSpace,\n parseAriaSnapshot,\n generateAriaTree,\n findNewElement,\n // Builtins protect injected code from clock emulation.\n builtins: null\n };\n this.window = window;\n this.document = window.document;\n this.isUnderTest = options.isUnderTest;\n this.utils.builtins = new UtilityScript(window, options.isUnderTest).builtins;\n this._sdkLanguage = options.sdkLanguage;\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = options.testIdAttributeName;\n this._evaluator = new SelectorEvaluatorImpl();\n this.consoleApi = new ConsoleAPI(this);\n this.onGlobalListenersRemoved = /* @__PURE__ */ new Set();\n this._autoClosingTags = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]);\n this._booleanAttributes = /* @__PURE__ */ new Set(["checked", "selected", "disabled", "readonly", "multiple"]);\n this._eventTypes = /* @__PURE__ */ new Map([\n ["auxclick", "mouse"],\n ["click", "mouse"],\n ["dblclick", "mouse"],\n ["mousedown", "mouse"],\n ["mouseeenter", "mouse"],\n ["mouseleave", "mouse"],\n ["mousemove", "mouse"],\n ["mouseout", "mouse"],\n ["mouseover", "mouse"],\n ["mouseup", "mouse"],\n ["mouseleave", "mouse"],\n ["mousewheel", "mouse"],\n ["keydown", "keyboard"],\n ["keyup", "keyboard"],\n ["keypress", "keyboard"],\n ["textInput", "keyboard"],\n ["touchstart", "touch"],\n ["touchmove", "touch"],\n ["touchend", "touch"],\n ["touchcancel", "touch"],\n ["pointerover", "pointer"],\n ["pointerout", "pointer"],\n ["pointerenter", "pointer"],\n ["pointerleave", "pointer"],\n ["pointerdown", "pointer"],\n ["pointerup", "pointer"],\n ["pointermove", "pointer"],\n ["pointercancel", "pointer"],\n ["gotpointercapture", "pointer"],\n ["lostpointercapture", "pointer"],\n ["focus", "focus"],\n ["blur", "focus"],\n ["drag", "drag"],\n ["dragstart", "drag"],\n ["dragend", "drag"],\n ["dragover", "drag"],\n ["dragenter", "drag"],\n ["dragleave", "drag"],\n ["dragexit", "drag"],\n ["drop", "drag"],\n ["wheel", "wheel"],\n ["deviceorientation", "deviceorientation"],\n ["deviceorientationabsolute", "deviceorientation"],\n ["devicemotion", "devicemotion"]\n ]);\n this._hoverHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousemove"]);\n this._tapHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["pointerdown", "pointerup", "touchstart", "touchend", "touchcancel"]);\n this._mouseHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousedown", "mouseup", "pointerdown", "pointerup", "click", "auxclick", "dblclick", "contextmenu"]);\n this._allHitTargetInterceptorEvents = /* @__PURE__ */ new Set([...this._hoverHitTargetInterceptorEvents, ...this._tapHitTargetInterceptorEvents, ...this._mouseHitTargetInterceptorEvents]);\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("xpath", XPathEngine);\n this._engines.set("xpath:light", XPathEngine);\n this._engines.set("role", createRoleEngine(false));\n this._engines.set("text", this._createTextEngine(true, false));\n this._engines.set("text:light", this._createTextEngine(false, false));\n this._engines.set("id", this._createAttributeEngine("id", true));\n this._engines.set("id:light", this._createAttributeEngine("id", false));\n this._engines.set("data-testid", this._createAttributeEngine("data-testid", true));\n this._engines.set("data-testid:light", this._createAttributeEngine("data-testid", false));\n this._engines.set("data-test-id", this._createAttributeEngine("data-test-id", true));\n this._engines.set("data-test-id:light", this._createAttributeEngine("data-test-id", false));\n this._engines.set("data-test", this._createAttributeEngine("data-test", true));\n this._engines.set("data-test:light", this._createAttributeEngine("data-test", false));\n this._engines.set("css", this._createCSSEngine());\n this._engines.set("nth", { queryAll: () => [] });\n this._engines.set("visible", this._createVisibleEngine());\n this._engines.set("internal:control", this._createControlEngine());\n this._engines.set("internal:has", this._createHasEngine());\n this._engines.set("internal:has-not", this._createHasNotEngine());\n this._engines.set("internal:and", { queryAll: () => [] });\n this._engines.set("internal:or", { queryAll: () => [] });\n this._engines.set("internal:chain", this._createInternalChainEngine());\n this._engines.set("internal:label", this._createInternalLabelEngine());\n this._engines.set("internal:text", this._createTextEngine(true, true));\n this._engines.set("internal:has-text", this._createInternalHasTextEngine());\n this._engines.set("internal:has-not-text", this._createInternalHasNotTextEngine());\n this._engines.set("internal:attr", this._createNamedAttributeEngine());\n this._engines.set("internal:testid", this._createTestIdEngine());\n this._engines.set("internal:role", createRoleEngine(true));\n this._engines.set("internal:describe", this._createDescribeEngine());\n this._engines.set("aria-ref", this._createAriaRefEngine());\n for (const { name, source } of options.customEngines)\n this._engines.set(name, this.eval(source));\n this._stableRafCount = options.stableRafCount;\n this._browserName = options.browserName;\n this._shouldPrependErrorPrefix = !!options.shouldPrependErrorPrefix;\n this._isUtilityWorld = !!options.isUtilityWorld;\n setGlobalOptions({ browserNameForWorkarounds: options.browserName });\n this._setupGlobalListenersRemovalDetection();\n this._setupHitTargetInterceptors();\n if (this.isUnderTest)\n this.window.__injectedScript = this;\n }\n eval(expression) {\n return this.window.eval(expression);\n }\n testIdAttributeNameForStrictErrorAndConsoleCodegen() {\n return this._testIdAttributeNameForStrictErrorAndConsoleCodegen;\n }\n parseSelector(selector) {\n const result = parseSelector(selector);\n visitAllSelectorParts(result, (part) => {\n if (!this._engines.has(part.name))\n throw this.createStacklessError(`Unknown engine "${part.name}" while parsing selector ${selector}`);\n });\n return result;\n }\n generateSelector(targetElement, options) {\n return generateSelector(this, targetElement, options);\n }\n generateSelectorSimple(targetElement, options) {\n return generateSelector(this, targetElement, { ...options, testIdAttributeName: this._testIdAttributeNameForStrictErrorAndConsoleCodegen }).selector;\n }\n querySelector(selector, root, strict) {\n const result = this.querySelectorAll(selector, root);\n if (strict && result.length > 1)\n throw this.strictModeViolationError(selector, result);\n this.checkDeprecatedSelectorUsage(selector, result);\n return result[0];\n }\n _queryNth(elements, part) {\n const list = [...elements];\n let nth = +part.body;\n if (nth === -1)\n nth = list.length - 1;\n return new Set(list.slice(nth, nth + 1));\n }\n _queryLayoutSelector(elements, part, originalRoot) {\n const name = part.name;\n const body = part.body;\n const result = [];\n const inner = this.querySelectorAll(body.parsed, originalRoot);\n for (const element of elements) {\n const score = layoutSelectorScore(name, element, inner, body.distance);\n if (score !== void 0)\n result.push({ element, score });\n }\n result.sort((a, b) => a.score - b.score);\n return new Set(result.map((r) => r.element));\n }\n ariaSnapshot(node, options) {\n return this.incrementalAriaSnapshot(node, options).full;\n }\n incrementalAriaSnapshot(node, options) {\n if (node.nodeType !== Node.ELEMENT_NODE)\n throw this.createStacklessError("Can only capture aria snapshot of Element nodes.");\n const ariaSnapshot = generateAriaTree(node, options);\n const rendered = renderAriaTree(ariaSnapshot, options);\n let incremental;\n if (options.track) {\n const previousSnapshot = this._lastAriaSnapshotForTrack.get(options.track);\n if (previousSnapshot)\n incremental = renderAriaTree(ariaSnapshot, options, previousSnapshot).text;\n this._lastAriaSnapshotForTrack.set(options.track, ariaSnapshot);\n }\n this._lastAriaSnapshotForQuery = ariaSnapshot;\n return { full: rendered.text, incremental, iframeRefs: ariaSnapshot.iframeRefs, iframeDepths: rendered.iframeDepths };\n }\n ariaSnapshotForRecorder() {\n const tree = generateAriaTree(this.document.body, { mode: "ai" });\n const { text: ariaSnapshot } = renderAriaTree(tree, { mode: "ai" });\n return { ariaSnapshot, refs: tree.refs };\n }\n getAllElementsMatchingExpectAriaTemplate(document, template) {\n return getAllElementsMatchingExpectAriaTemplate(document.documentElement, template);\n }\n querySelectorAll(selector, root) {\n if (selector.capture !== void 0) {\n if (selector.parts.some((part) => part.name === "nth"))\n throw this.createStacklessError(`Can\'t query n-th element in a request with the capture.`);\n const withHas = { parts: selector.parts.slice(0, selector.capture + 1) };\n if (selector.capture < selector.parts.length - 1) {\n const parsed = { parts: selector.parts.slice(selector.capture + 1) };\n const has = { name: "internal:has", body: { parsed }, source: stringifySelector(parsed) };\n withHas.parts.push(has);\n }\n return this.querySelectorAll(withHas, root);\n }\n if (!root["querySelectorAll"])\n throw this.createStacklessError("Node is not queryable.");\n if (selector.capture !== void 0) {\n throw this.createStacklessError("Internal error: there should not be a capture in the selector.");\n }\n if (root.nodeType === 11 && selector.parts.length === 1 && selector.parts[0].name === "css" && selector.parts[0].source === ":scope")\n return [root];\n this._evaluator.begin();\n try {\n let roots = /* @__PURE__ */ new Set([root]);\n for (const part of selector.parts) {\n if (part.name === "nth") {\n roots = this._queryNth(roots, part);\n } else if (part.name === "internal:and") {\n const andElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(andElements.filter((e) => roots.has(e)));\n } else if (part.name === "internal:or") {\n const orElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(sortInDOMOrder(/* @__PURE__ */ new Set([...roots, ...orElements])));\n } else if (kLayoutSelectorNames.includes(part.name)) {\n roots = this._queryLayoutSelector(roots, part, root);\n } else {\n const next = /* @__PURE__ */ new Set();\n for (const root2 of roots) {\n const all = this._queryEngineAll(part, root2);\n for (const one of all)\n next.add(one);\n }\n roots = next;\n }\n }\n return [...roots];\n } finally {\n this._evaluator.end();\n }\n }\n _queryEngineAll(part, root) {\n const result = this._engines.get(part.name).queryAll(root, part.body);\n for (const element of result) {\n if (!("nodeName" in element))\n throw this.createStacklessError(`Expected a Node but got ${Object.prototype.toString.call(element)}`);\n }\n return result;\n }\n _createAttributeEngine(attribute, shadow) {\n const toCSS = (selector) => {\n const css = `[${attribute}=${JSON.stringify(selector)}]`;\n return [{ simples: [{ selector: { css, functions: [] }, combinator: "" }] }];\n };\n return {\n queryAll: (root, selector) => {\n return this._evaluator.query({ scope: root, pierceShadow: shadow }, toCSS(selector));\n }\n };\n }\n _createCSSEngine() {\n return {\n queryAll: (root, body) => {\n return this._evaluator.query({ scope: root, pierceShadow: true }, body);\n }\n };\n }\n _createTextEngine(shadow, internal) {\n const queryAll = (root, selector) => {\n const { matcher, kind } = createTextMatcher(selector, internal);\n const result = [];\n let lastDidNotMatchSelf = null;\n const appendElement = (element) => {\n if (kind === "lax" && lastDidNotMatchSelf && lastDidNotMatchSelf.contains(element))\n return false;\n const matches = elementMatchesText(this._evaluator._cacheText, element, matcher);\n if (matches === "none")\n lastDidNotMatchSelf = element;\n if (matches === "self" || matches === "selfAndChildren" && kind === "strict" && !internal)\n result.push(element);\n };\n if (root.nodeType === Node.ELEMENT_NODE)\n appendElement(root);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: shadow }, "*");\n for (const element of elements)\n appendElement(element);\n return result;\n };\n return { queryAll };\n }\n _createInternalHasTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [element] : [];\n }\n };\n }\n _createInternalHasNotTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [] : [element];\n }\n };\n }\n _createInternalLabelEngine() {\n return {\n queryAll: (root, selector) => {\n const { matcher } = createTextMatcher(selector, true);\n const allElements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, "*");\n return allElements.filter((element) => {\n return getElementLabels(this._evaluator._cacheText, element).some((label) => matcher(label));\n });\n }\n };\n }\n _createNamedAttributeEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed attribute selector: " + selector);\n const { name } = parsed.attributes[0];\n const matcher = createAttributeMatcher(parsed.attributes[0]);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, `[${name}]`);\n return elements.filter((e) => matcher(e.getAttribute(name)));\n };\n return { queryAll };\n }\n _createTestIdEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed test id selector: " + selector);\n const names = splitTestIdAttributeNames(parsed.attributes[0].name);\n const matcher = createAttributeMatcher(parsed.attributes[0]);\n const cssQuery = names.map((n) => `[${n}]`).join(",");\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, cssQuery);\n return elements.filter((e) => names.some((n) => {\n const actual = e.getAttribute(n);\n return actual !== null && matcher(actual);\n }));\n };\n return { queryAll };\n }\n _createDescribeEngine() {\n const queryAll = (root) => {\n if (root.nodeType !== 1)\n return [];\n return [root];\n };\n return { queryAll };\n }\n _createControlEngine() {\n return {\n queryAll(root, body) {\n if (body === "enter-frame")\n return [];\n if (body === "return-empty")\n return [];\n if (body === "component") {\n if (root.nodeType !== 1)\n return [];\n return [root.childElementCount === 1 ? root.firstElementChild : root];\n }\n throw new Error(`Internal error, unknown internal:control selector ${body}`);\n }\n };\n }\n _createHasEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [root] : [];\n };\n return { queryAll };\n }\n _createHasNotEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [] : [root];\n };\n return { queryAll };\n }\n _createVisibleEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const visible = body === "true";\n return isElementVisible(root) === visible ? [root] : [];\n };\n return { queryAll };\n }\n _createInternalChainEngine() {\n const queryAll = (root, body) => {\n return this.querySelectorAll(body.parsed, root);\n };\n return { queryAll };\n }\n extend(source, params) {\n const constrFunction = this.window.eval(`\n (() => {\n const module = {};\n ${source}\n return module.exports.default();\n })()`);\n return new constrFunction(this, params);\n }\n async viewportRatio(element) {\n return await new Promise((resolve) => {\n const observer = new IntersectionObserver((entries) => {\n resolve(entries[0].intersectionRatio);\n observer.disconnect();\n });\n observer.observe(element);\n this.utils.builtins.requestAnimationFrame(() => {\n });\n });\n }\n getElementBorderWidth(node) {\n if (node.nodeType !== Node.ELEMENT_NODE || !node.ownerDocument || !node.ownerDocument.defaultView)\n return { left: 0, top: 0 };\n const style = node.ownerDocument.defaultView.getComputedStyle(node);\n return { left: parseInt(style.borderLeftWidth || "", 10), top: parseInt(style.borderTopWidth || "", 10) };\n }\n describeIFrameStyle(iframe) {\n if (!iframe.ownerDocument || !iframe.ownerDocument.defaultView)\n return "error:notconnected";\n const defaultView = iframe.ownerDocument.defaultView;\n for (let e = iframe; e; e = parentElementOrShadowHost(e)) {\n if (defaultView.getComputedStyle(e).transform !== "none")\n return "transformed";\n }\n const iframeStyle = defaultView.getComputedStyle(iframe);\n return {\n left: parseInt(iframeStyle.borderLeftWidth || "", 10) + parseInt(iframeStyle.paddingLeft || "", 10),\n top: parseInt(iframeStyle.borderTopWidth || "", 10) + parseInt(iframeStyle.paddingTop || "", 10)\n };\n }\n retarget(node, behavior) {\n let element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;\n if (!element)\n return null;\n if (behavior === "none")\n return element;\n if (!element.matches("input, textarea, select") && !element.isContentEditable) {\n if (behavior === "button-link")\n element = element.closest("button, [role=button], a, [role=link]") || element;\n else\n element = element.closest("button, [role=button], [role=checkbox], [role=radio]") || element;\n }\n if (behavior === "follow-label") {\n if (!element.matches("a, input, textarea, button, select, [role=link], [role=button], [role=checkbox], [role=radio]") && !element.isContentEditable) {\n const enclosingLabel = element.closest("label");\n if (enclosingLabel && enclosingLabel.control)\n element = enclosingLabel.control;\n }\n }\n return element;\n }\n async checkElementStates(node, states) {\n if (states.includes("stable")) {\n const stableResult = await this._checkElementIsStable(node);\n if (stableResult === false)\n return { missingState: "stable" };\n if (stableResult === "error:notconnected")\n return "error:notconnected";\n }\n for (const state of states) {\n if (state !== "stable") {\n const result = this.elementState(node, state);\n if (result.received === "error:notconnected")\n return "error:notconnected";\n if (!result.matches)\n return { missingState: state };\n }\n }\n }\n async _checkElementIsStable(node) {\n const continuePolling = Symbol("continuePolling");\n let lastRect;\n let stableRafCounter = 0;\n let lastTime = 0;\n const check = () => {\n const element = this.retarget(node, "no-follow-label");\n if (!element)\n return "error:notconnected";\n const time = this.utils.builtins.performance.now();\n if (this._stableRafCount > 1 && time - lastTime < 15)\n return continuePolling;\n lastTime = time;\n const clientRect = element.getBoundingClientRect();\n const rect = { x: clientRect.top, y: clientRect.left, width: clientRect.width, height: clientRect.height };\n if (lastRect) {\n const samePosition = rect.x === lastRect.x && rect.y === lastRect.y && rect.width === lastRect.width && rect.height === lastRect.height;\n if (!samePosition)\n return false;\n if (++stableRafCounter >= this._stableRafCount)\n return true;\n }\n lastRect = rect;\n return continuePolling;\n };\n let fulfill;\n let reject;\n const result = new Promise((f, r) => {\n fulfill = f;\n reject = r;\n });\n const raf = () => {\n try {\n const success = check();\n if (success !== continuePolling)\n fulfill(success);\n else\n this.utils.builtins.requestAnimationFrame(raf);\n } catch (e) {\n reject(e);\n }\n };\n this.utils.builtins.requestAnimationFrame(raf);\n return result;\n }\n _createAriaRefEngine() {\n const queryAll = (root, selector) => {\n var _a, _b;\n const result = (_b = (_a = this._lastAriaSnapshotForQuery) == null ? void 0 : _a.elements) == null ? void 0 : _b.get(selector);\n return result && result.isConnected ? [result] : [];\n };\n return { queryAll };\n }\n elementState(node, state) {\n const element = this.retarget(node, ["visible", "hidden"].includes(state) ? "none" : "follow-label");\n if (!element || !element.isConnected) {\n if (state === "hidden")\n return { matches: true, received: "hidden" };\n return { matches: false, received: "error:notconnected" };\n }\n if (state === "visible" || state === "hidden") {\n const visible = isElementVisible(element);\n return {\n matches: state === "visible" ? visible : !visible,\n received: visible ? "visible" : "hidden"\n };\n }\n if (state === "disabled" || state === "enabled") {\n const disabled = getAriaDisabled(element);\n return {\n matches: state === "disabled" ? disabled : !disabled,\n received: disabled ? "disabled" : "enabled"\n };\n }\n if (state === "editable") {\n const disabled = getAriaDisabled(element);\n const readonly = getReadonly(element);\n if (readonly === "error")\n throw this.createStacklessError("Element is not an ,