Spaces:
Running
Running
github-actions[bot]
commited on
Commit
·
d983868
1
Parent(s):
e513b2a
Deploy: Update from GitHub Actions build
Browse files- .env.example +0 -19
- .gitattributes +0 -37
- Dockerfile +12 -26
- README.md +0 -10
- dist/index.js +26 -0
- package-lock.json +468 -1
- package.json +6 -4
- src/config.js +0 -133
- src/login.js +0 -86
- src/middlewares/auth.js +0 -44
- src/middlewares/cors.js +0 -41
- src/routes/chat-completions.js +0 -53
- src/routes/health.js +0 -23
- src/routes/models.js +0 -75
- src/utils/ai-studio-injector.js +0 -266
- src/utils/ai-studio-processor.js +0 -264
- src/utils/browser.js +0 -949
- src/utils/common-utils.js +0 -104
- src/utils/logger.js +0 -90
- src/utils/page-pool-monitor.js +0 -57
- src/utils/response-parser.js +0 -189
- src/utils/validation.js +0 -41
- src/web-server.js +0 -129
.env.example
DELETED
@@ -1,19 +0,0 @@
|
|
1 |
-
# 服务器配置
|
2 |
-
PORT=3000
|
3 |
-
NODE_ENV=development
|
4 |
-
|
5 |
-
# 浏览器配置
|
6 |
-
HEADLESS=false
|
7 |
-
USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
|
8 |
-
|
9 |
-
# AI Studio 配置
|
10 |
-
AI_STUDIO_URL=https://aistudio.google.com/
|
11 |
-
PAGE_TIMEOUT=30000
|
12 |
-
DEFAULT_MODEL=gemini-pro
|
13 |
-
|
14 |
-
# CORS 配置
|
15 |
-
CORS_ORIGIN=*
|
16 |
-
|
17 |
-
# API 认证配置
|
18 |
-
# 设置一个强密码作为API访问令牌
|
19 |
-
API_TOKEN=your_secret_api_token_here
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitattributes
DELETED
@@ -1,37 +0,0 @@
|
|
1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
37 |
-
*.webp filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dockerfile
CHANGED
@@ -4,48 +4,34 @@ FROM node:23-alpine
|
|
4 |
# 设置工作目录
|
5 |
WORKDIR /app
|
6 |
|
7 |
-
# 安装系统依赖
|
8 |
RUN apk add --no-cache \
|
9 |
-
|
10 |
-
|
11 |
-
make \
|
12 |
-
g++ \
|
13 |
-
# Playwright 依赖
|
14 |
-
chromium \
|
15 |
-
nss \
|
16 |
-
freetype \
|
17 |
-
freetype-dev \
|
18 |
-
harfbuzz \
|
19 |
-
ca-certificates \
|
20 |
-
ttf-freefont \
|
21 |
-
# 其他依赖
|
22 |
gcompat
|
23 |
|
24 |
-
# 设置 Playwright 的环境变量
|
25 |
ENV PLAYWRIGHT_BROWSERS_PATH=/usr/bin
|
26 |
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
27 |
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
28 |
ENV PLAYWRIGHT_SKIP_BROWSER_VALIDATION=1
|
29 |
|
30 |
-
#
|
31 |
COPY package*.json ./
|
32 |
|
33 |
-
#
|
34 |
-
|
|
|
|
|
|
|
35 |
COPY public/ ./public/
|
36 |
# 复制 cookies.json 文件(如果存在)
|
37 |
-
# 使用通配符语法,如果文件不存在则跳过,不会报错
|
38 |
COPY cookies.json* ./
|
39 |
|
40 |
-
# 安装依赖
|
41 |
-
RUN npm ci --only=production
|
42 |
-
|
43 |
# 设置非 root 用户(安全最佳实践)
|
44 |
RUN addgroup -g 1001 -S nodejs && \
|
45 |
adduser -S nodejs -u 1001
|
46 |
|
47 |
-
|
48 |
-
# 更改文件所有权
|
49 |
# 创建 screenshots 和 logs 目录,并设置正确的权限
|
50 |
RUN mkdir -p /app/screenshots && \
|
51 |
mkdir -p /app/logs && \
|
@@ -62,5 +48,5 @@ EXPOSE 7860
|
|
62 |
ENV NODE_ENV=production
|
63 |
ENV PORT=7860
|
64 |
|
65 |
-
# 启动应用
|
66 |
-
CMD ["npm", "start"]
|
|
|
4 |
# 设置工作目录
|
5 |
WORKDIR /app
|
6 |
|
7 |
+
# 安装系统依赖 (与之前相同)
|
8 |
RUN apk add --no-cache \
|
9 |
+
python3 make g++ \
|
10 |
+
chromium nss freetype freetype-dev harfbuzz ca-certificates ttf-freefont \
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
gcompat
|
12 |
|
13 |
+
# 设置 Playwright 的环境变量 (与之前相同)
|
14 |
ENV PLAYWRIGHT_BROWSERS_PATH=/usr/bin
|
15 |
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
16 |
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
17 |
ENV PLAYWRIGHT_SKIP_BROWSER_VALIDATION=1
|
18 |
|
19 |
+
# 仅复制 package.json 和 package-lock.json 以利用 Docker 缓存
|
20 |
COPY package*.json ./
|
21 |
|
22 |
+
# 安装生产环境依赖。这不会安装 esbuild 等 devDependencies。
|
23 |
+
RUN npm ci --only=production
|
24 |
+
|
25 |
+
# 复制构建后的应用代码和静态资源
|
26 |
+
COPY dist/ ./dist/
|
27 |
COPY public/ ./public/
|
28 |
# 复制 cookies.json 文件(如果存在)
|
|
|
29 |
COPY cookies.json* ./
|
30 |
|
|
|
|
|
|
|
31 |
# 设置非 root 用户(安全最佳实践)
|
32 |
RUN addgroup -g 1001 -S nodejs && \
|
33 |
adduser -S nodejs -u 1001
|
34 |
|
|
|
|
|
35 |
# 创建 screenshots 和 logs 目录,并设置正确的权限
|
36 |
RUN mkdir -p /app/screenshots && \
|
37 |
mkdir -p /app/logs && \
|
|
|
48 |
ENV NODE_ENV=production
|
49 |
ENV PORT=7860
|
50 |
|
51 |
+
# 启动应用 (现在会执行 package.json 中更新后的 start 命令)
|
52 |
+
CMD ["npm", "start"]
|
README.md
DELETED
@@ -1,10 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Aistudio2api
|
3 |
-
emoji: 💻
|
4 |
-
colorFrom: gray
|
5 |
-
colorTo: green
|
6 |
-
sdk: docker
|
7 |
-
pinned: false
|
8 |
-
---
|
9 |
-
|
10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dist/index.js
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
var Ft=Object.create;var ae=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Wt=Object.getPrototypeOf,Kt=Object.prototype.hasOwnProperty;var Y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xe=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gt=(e,t)=>{for(var r in t)ae(e,r,{get:t[r],enumerable:!0})},Jt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zt(t))!Kt.call(e,n)&&n!==r&&ae(e,n,{get:()=>t[n],enumerable:!(s=Vt(t,n))||s.enumerable});return e};var Yt=(e,t,r)=>(r=e!=null?Ft(Wt(e)):{},Jt(t||!e||!e.__esModule?ae(r,"default",{value:e,enumerable:!0}):r,e));var et=Te((kn,xr)=>{xr.exports={name:"dotenv",version:"17.0.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var nt=Te((Rn,v)=>{var ge=Y("fs"),ee=Y("path"),Tr=Y("os"),Pr=Y("crypto"),vr=et(),we=vr.version,kr=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Rr(e){let t={},r=e.toString();r=r.replace(/\r\n?/mg,`
|
2 |
+
`);let s;for(;(s=kr.exec(r))!=null;){let n=s[1],o=s[2]||"";o=o.trim();let i=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),i==='"'&&(o=o.replace(/\\n/g,`
|
3 |
+
`),o=o.replace(/\\r/g,"\r")),t[n]=o}return t}function Cr(e){e=e||{};let t=ot(e);e.path=t;let r=_.configDotenv(e);if(!r.parsed){let i=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw i.code="MISSING_DATA",i}let s=st(e).split(","),n=s.length,o;for(let i=0;i<n;i++)try{let a=s[i].trim(),l=Or(r,a);o=_.decrypt(l.ciphertext,l.key);break}catch(a){if(i+1>=n)throw a}return _.parse(o)}function Hr(e){console.error(`[dotenv@${we}][WARN] ${e}`)}function L(e){console.log(`[dotenv@${we}][DEBUG] ${e}`)}function rt(e){console.log(`[dotenv@${we}] ${e}`)}function st(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function Or(e,t){let r;try{r=new URL(t)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:[email protected]/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let s=r.password;if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let n=r.searchParams.get("environment");if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let o=`DOTENV_VAULT_${n.toUpperCase()}`,i=e.parsed[o];if(!i){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:i,key:s}}function ot(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)ge.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=ee.resolve(process.cwd(),".env.vault");return ge.existsSync(t)?t:null}function tt(e){return e[0]==="~"?ee.join(Tr.homedir(),e.slice(1)):e}function Ar(e){let t=!!(e&&e.debug),r=!!(e&&e.quiet);(t||!r)&&rt("Loading env from encrypted .env.vault");let s=_._parseVault(e),n=process.env;return e&&e.processEnv!=null&&(n=e.processEnv),_.populate(n,s,e),{parsed:s}}function $r(e){let t=ee.resolve(process.cwd(),".env"),r="utf8",s=!!(e&&e.debug),n=!!(e&&e.quiet);e&&e.encoding?r=e.encoding:s&&L("No encoding is specified. UTF-8 is used by default");let o=[t];if(e&&e.path)if(!Array.isArray(e.path))o=[tt(e.path)];else{o=[];for(let u of e.path)o.push(tt(u))}let i,a={};for(let u of o)try{let f=_.parse(ge.readFileSync(u,{encoding:r}));_.populate(a,f,e)}catch(f){s&&L(`Failed to load ${u} ${f.message}`),i=f}let l=process.env;e&&e.processEnv!=null&&(l=e.processEnv);let c=_.populate(l,a,e);if(s||!n){let u=Object.keys(c).length,f=[];for(let h of o)try{let m=ee.relative(process.cwd(),h);f.push(m)}catch(m){s&&L(`Failed to load ${h} ${m.message}`),i=m}rt(`injecting env (${u}) from ${f.join(",")} \u2013 [tip] encrypt with dotenvx: https://dotenvx.com`)}return i?{parsed:a,error:i}:{parsed:a}}function Ir(e){if(st(e).length===0)return _.configDotenv(e);let t=ot(e);return t?_._configVault(e):(Hr(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),_.configDotenv(e))}function Nr(e,t){let r=Buffer.from(t.slice(-64),"hex"),s=Buffer.from(e,"base64"),n=s.subarray(0,12),o=s.subarray(-16);s=s.subarray(12,-16);try{let i=Pr.createDecipheriv("aes-256-gcm",r,n);return i.setAuthTag(o),`${i.update(s)}${i.final()}`}catch(i){let a=i instanceof RangeError,l=i.message==="Invalid key length",c=i.message==="Unsupported state or unable to authenticate data";if(a||l){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(c){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw i}}function Mr(e,t,r={}){let s=!!(r&&r.debug),n=!!(r&&r.override),o={};if(typeof t!="object"){let i=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw i.code="OBJECT_REQUIRED",i}for(let i of Object.keys(t))Object.prototype.hasOwnProperty.call(e,i)?(n===!0&&(e[i]=t[i],o[i]=t[i]),s&&L(n===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):(e[i]=t[i],o[i]=t[i]);return o}var _={configDotenv:$r,_configVault:Ar,_parseVault:Cr,config:Ir,decrypt:Nr,parse:Rr,populate:Mr};v.exports.configDotenv=_.configDotenv;v.exports._configVault=_._configVault;v.exports._parseVault=_._parseVault;v.exports.config=_.config;v.exports.decrypt=_.decrypt;v.exports.parse=_.parse;v.exports.populate=_.populate;v.exports=_});import ye from"fs";function Dr(){ye.existsSync(j.logDir)||ye.mkdirSync(j.logDir,{recursive:!0})}function Br(...e){return e.map(t=>typeof t=="object"&&t!==null?JSON.stringify(t,null,2):String(t)).join(" ")}async function Lr(e,t){if(!j.enableFile)return;Dr();let s=`[${new Date().toISOString()}] [${e}] ${t}
|
4 |
+
`;try{await ye.promises.appendFile(j.logFile,s)}catch(n){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",n)}}function jr(e,...t){if(!j.enableConsole)return;let r={[O.DEBUG]:console.debug,[O.INFO]:console.log,[O.WARN]:console.warn,[O.ERROR]:console.error}[e]||console.log,s=new Date().toLocaleTimeString();r(`[${s}] [${e}]`,...t)}function at(e,...t){let r=Br(...t);jr(e,...t),Lr(e,r)}var O,j,d,I,U=xe(()=>{O={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},j={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||O.INFO};d=(...e)=>at(O.INFO,...e),I=(...e)=>at(O.ERROR,...e)});var ut={};Gt(ut,{checkCookieAvailability:()=>Vr,ensureDirectoryExists:()=>lt,getHumanReadableTimestamp:()=>ct,loadCookies:()=>_e,saveScreenshot:()=>be,waitForUserInput:()=>zr});import F from"fs";import Ur from"path";import Fr from"readline";function ct(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function lt(e){F.existsSync(e)||(F.mkdirSync(e,{recursive:!0}),d(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${e}`))}function Vr(e,t){if(t)try{return JSON.parse(t),d("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(r){I("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",r.message)}return F.existsSync(e)?(d(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${e}`),!0):(I(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${e}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),d("\u8BF7\u5148\u8FD0\u884C `npm run login` \u6216\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002"),!1)}function _e(e,t){try{if(t)return d("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(t);if(F.existsSync(e))return d(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${e}`),JSON.parse(F.readFileSync(e,"utf8"))}catch(r){throw I("\u52A0\u8F7D Cookie \u5931\u8D25:",r),new Error("\u65E0\u6CD5\u52A0\u8F7D\u6216\u89E3\u6790 Cookie\u3002")}return[]}async function be(e,t,r="screenshot"){lt(t);let s=ct(),n=Ur.join(t,`${r}_${s}.png`);return await e.screenshot({path:n,fullPage:!0}),d(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${n}`),n}function zr(){let e=Fr.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question("",()=>{e.close(),t()})})}var te=xe(()=>{U()});var R=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function Pe(){return{root:{key:""},static:new R}}function ve(e){let[t,...r]=e.split("/");return r[r.length-1]===""?r.slice(0,-1):r}function Xt(e,t){let r=new R;for(let[s,n]of t){let o=s<0?e.slice(-1*s).join("/"):e[s];if(typeof n=="string")r[n]=o;else{let i=o.match(n);if(i)for(let a in i.groups)r[a]=i.groups[a]}}return r}function ke(e,t="",r,s){let n=ve(r),o=e.root,i=0,a=[];for(let c=0;c<n.length;c++){let u=n[c];if(u.startsWith("**")){o.wildcard||(o.wildcard={key:"**"}),o=o.wildcard,a.push([-c,u.split(":")[1]||"_",u.length===2]);break}if(u==="*"||u.includes(":")){o.param||(o.param={key:"*"}),o=o.param;let h=u==="*";a.push([c,h?`_${i++}`:Qt(u),h]);continue}let f=o.static?.[u];if(f)o=f;else{let h={key:u};o.static||(o.static=new R),o.static[u]=h,o=h}}let l=a.length>0;o.methods||(o.methods=new R),o.methods[t]||(o.methods[t]=[]),o.methods[t].push({data:s||null,paramsMap:l?a:void 0}),l||(e.static[r]=o)}function Qt(e){if(!e.includes(":",1))return e.slice(1);let t=e.replace(/:(\w+)/g,(r,s)=>`(?<${s}>[^/]+)`).replace(/\./g,"\\.");return new RegExp(`^${t}$`)}function Re(e,t="",r,s){r[r.length-1]==="/"&&(r=r.slice(0,-1));let n=e.static[r];if(n&&n.methods){let a=n.methods[t]||n.methods[""];if(a!==void 0)return a[0]}let o=ve(r),i=ce(e,e.root,t,o,0)?.[0];if(i!==void 0)return s?.params===!1?i:{data:i.data,params:i.paramsMap?Xt(o,i.paramsMap):void 0}}function ce(e,t,r,s,n){if(n===s.length){if(t.methods){let i=t.methods[r]||t.methods[""];if(i)return i}if(t.param&&t.param.methods){let i=t.param.methods[r]||t.param.methods[""];if(i){let a=i[0].paramsMap;if(a?.[a?.length-1]?.[2])return i}}if(t.wildcard&&t.wildcard.methods){let i=t.wildcard.methods[r]||t.wildcard.methods[""];if(i){let a=i[0].paramsMap;if(a?.[a?.length-1]?.[2])return i}}return}let o=s[n];if(t.static){let i=t.static[o];if(i){let a=ce(e,i,r,s,n+1);if(a)return a}}if(t.param){let i=ce(e,t.param,r,s,n+1);if(i)return i}if(t.wildcard&&t.wildcard.methods)return t.wildcard.methods[r]||t.wildcard.methods[""]}function Ce(e="/"){let t=[],r=0;for(let s of e.split("/"))s&&(s==="*"?t.push(`(?<_${r++}>[^/]*)`):s.startsWith("**")?t.push(s==="**"?"?(?<_>.*)":`?(?<${s.slice(3)}>.+)`):s.includes(":")?t.push(s.replace(/:(\w+)/g,(n,o)=>`(?<${o}>[^/]+)`).replace(/\./g,"\\.")):t.push(s));return new RegExp(`^/${t.join("/")}/?$`)}function Oe(e){let t=e.port??globalThis.process?.env.PORT??3e3,r=typeof t=="number"?t:Number.parseInt(t,10),s=e.hostname??globalThis.process?.env.HOST;return{port:r,hostname:s}}function Ae(e,t,r){if(!(!e||!t))return e.includes(":")&&(e=`[${e}]`),`http${r?"s":""}://${e}:${t}/`}function $e(e,t){if(!t||(e.silent??globalThis.process?.env?.TEST))return;let r=new URL(t),s=r.hostname==="[::]"||r.hostname==="0.0.0.0";s&&(r.hostname="localhost",t=r.href);let n="\u279C Listening on:",o=s?" (all interfaces)":"";globalThis.process.stdout?.isTTY&&(n=`\x1B[32m${n}\x1B[0m`,t=`\x1B[36m${t}\x1B[0m`,o=`\x1B[2m${o}\x1B[0m`),console.log(` ${n} ${t}${o}`)}function Ie(e){if(!e.tls||e.protocol==="http")return;let t=He(e.tls.cert),r=He(e.tls.key);if(!t&&!r){if(e.protocol==="https")throw new TypeError("TLS `cert` and `key` must be provided for `https` protocol.");return}if(!t||!r)throw new TypeError("TLS `cert` and `key` must be provided together.");return{cert:t,key:r,passphrase:e.tls.passphrase}}function He(e){if(!e)return;if(typeof e!="string")throw new TypeError("TLS certificate and key must be strings in PEM format or file paths.");if(e.startsWith("-----BEGIN "))return e;let{readFileSync:t}=process.getBuiltinModule("node:fs");return t(e,"utf8")}function Ne(){let e=new Set;return{waitUntil:t=>{e.add(t.catch(console.error).finally(()=>{e.delete(t)}))},wait:()=>Promise.all(e)}}function Me(e){let t=e.options.fetch,r=e.options.middleware||[];return r.length===0?t:s=>qe(s,t,r,0)}function qe(e,t,r,s){return s===r.length?t(e):r[s](e,()=>qe(e,t,r,s+1))}var le=(()=>{let e=class{#r;#t;_pathname;_urlqindex;_query;_search;constructor(s){this.#r=s}get _url(){return this.#t||(this.#t=new globalThis.URL(this.#r)),this.#t}toString(){return this._url.toString()}toJSON(){return this.toString()}get pathname(){if(this.#t)return this.#t.pathname;if(this._pathname===void 0){let s=this.#r,n=s.indexOf("://");if(n===-1)return this._url.pathname;let o=s.indexOf("/",n+4);if(o===-1)return this._url.pathname;let i=this._urlqindex=s.indexOf("?",o);this._pathname=s.slice(o,i===-1?void 0:i)}return this._pathname}set pathname(s){this._pathname=void 0,this._url.pathname=s}get searchParams(){return this.#t?this.#t.searchParams:(this._query||(this._query=new URLSearchParams(this.search)),this._query)}get search(){if(this.#t)return this.#t.search;if(this._search===void 0){let s=this._urlqindex;s===-1||s===this.#r.length-1?this._search="":this._search=s===void 0?this._url.search:this.#r.slice(s)}return this._search}set search(s){this._search=void 0,this._query=void 0,this._url.search=s}},t=["hash","host","hostname","href","origin","password","port","protocol","username"];for(let r of t)Object.defineProperty(e.prototype,r,{get(){return this._url[r]},set(s){this._url[r]=s}});return Object.setPrototypeOf(e,globalThis.URL),e})();var De=e=>{let t=e.options.error;t&&e.options.middleware.unshift((r,s)=>{try{let n=s();return n instanceof Promise?n.catch(o=>t(o)):n}catch(n){return t(n)}})};function $(e){if(Array.isArray(e))return e.flatMap(u=>$(u));if(typeof e!="string")return[];let t=[],r=0,s,n,o,i,a,l=()=>{for(;r<e.length&&/\s/.test(e.charAt(r));)r+=1;return r<e.length},c=()=>(n=e.charAt(r),n!=="="&&n!==";"&&n!==",");for(;r<e.length;){for(s=r,a=!1;l();)if(n=e.charAt(r),n===","){for(o=r,r+=1,l(),i=r;r<e.length&&c();)r+=1;r<e.length&&e.charAt(r)==="="?(a=!0,r=i,t.push(e.slice(s,o)),s=r):r=o+1}else r+=1;(!a||r>=e.length)&&t.push(e.slice(s))}return t}async function Be(e,t){if(!t)return e.statusCode=500,ue(e);if(t.nodeResponse){let s=t.nodeResponse();if(Le(e,s.status,s.statusText,s.headers.flat()),s.body){if(s.body instanceof ReadableStream)return je(s.body,e);if(typeof s.body?.pipe=="function")return s.body.pipe(e),new Promise(n=>e.on("close",n));e.write(s.body)}return ue(e)}let r=[];for(let[s,n]of t.headers)if(s==="set-cookie")for(let o of $(n))r.push(["set-cookie",o]);else r.push([s,n]);return Le(e,t.status,t.statusText,r.flat()),t.body?je(t.body,e):ue(e)}function Le(e,t,r,s){e.headersSent||(e.req?.httpVersion==="2.0"?e.writeHead(t,s.flat()):e.writeHead(t,r,s.flat()))}function ue(e){return new Promise(t=>e.end(t))}function je(e,t){if(t.destroyed){e.cancel();return}let r=e.getReader();function s(o){r.cancel(o).catch(()=>{}),o&&t.destroy(o)}function n({done:o,value:i}){try{o?t.end():t.write(i)?r.read().then(n,s):t.once("drain",()=>r.read().then(n,s))}catch(a){s(a instanceof Error?a:void 0)}}return t.on("close",s),t.on("error",s),r.read().then(n,s),r.closed.finally(()=>{t.off("close",s),t.off("error",s)})}var de=Symbol.for("nodejs.util.inspect.custom"),Zt=(()=>{let e=class{_node;constructor(r){this._node=r}append(r,s){r=q(r);let n=this._node.req.headers,o=n[r];o?Array.isArray(o)?o.push(s):n[r]=[o,s]:n[r]=s}delete(r){r=q(r),this._node.req.headers[r]=void 0}get(r){return r=q(r),this._node.req.headers[r]===void 0?null:M(this._node.req.headers[r])}getSetCookie(){let r=this._node.req.headers["set-cookie"];return!r||r.length===0?[]:$(r)}has(r){return r=q(r),!!this._node.req.headers[r]}set(r,s){r=q(r),this._node.req.headers[r]=s}get count(){throw new Error("Method not implemented.")}getAll(r){throw new Error("Method not implemented.")}toJSON(){let r=this._node.req.headers,s={};for(let n in r)r[n]&&(s[n]=M(r[n]));return s}forEach(r,s){let n=this._node.req.headers;for(let o in n)n[o]&&r.call(s,M(n[o]),o,this)}*entries(){let r=this._node.req.headers,s=this._node.req.httpVersion==="2.0";for(let n in r)(!s||n[0]!==":")&&(yield[n,M(r[n])])}*keys(){let r=Object.keys(this._node.req.headers);for(let s of r)yield s}*values(){let r=Object.values(this._node.req.headers);for(let s of r)yield M(s)}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}get[Symbol.toStringTag](){return"Headers"}[de](){return Object.fromEntries(this.entries())}};return Object.setPrototypeOf(e.prototype,globalThis.Headers.prototype),e})();function M(e){return Array.isArray(e)?e.join(", "):typeof e=="string"?e:String(e??"")}function q(e){if(e[0]===":")throw new TypeError(`${JSON.stringify(e)} is an invalid header name.`);return e.toLowerCase()}var er=(()=>{let e=class{_node;_hash="";_username="";_password="";_protocol;_hostname;_port;_pathname;_search;_searchParams;constructor(r){this._node=r}get hash(){return this._hash}set hash(r){this._hash=r}get username(){return this._username}set username(r){this._username=r}get password(){return this._password}set password(r){this._password=r}get host(){return this._node.req.headers.host||this._node.req.headers[":authority"]||""}set host(r){this._hostname=void 0,this._port=void 0,this._node.req.headers.host=r}get hostname(){if(this._hostname===void 0){let[r,s]=Fe(this._node.req.headers.host);this._port===void 0&&s&&(this._port=String(Number.parseInt(s)||"")),this._hostname=r||"localhost"}return this._hostname}set hostname(r){this._hostname=r}get port(){if(this._port===void 0){let[r,s]=Fe(this._node.req.headers.host);this._hostname===void 0&&r&&(this._hostname=r),this._port=s||String(this._node.req.socket?.localPort||"")}return this._port}set port(r){this._port=String(Number.parseInt(r)||"")}get pathname(){if(this._pathname===void 0){let[r,s]=Ue(this._node.req.url||"/");this._pathname=r,this._search===void 0&&(this._search=s)}return this._pathname}set pathname(r){r[0]!=="/"&&(r="/"+r),r!==this._pathname&&(this._pathname=r,this._node.req.url=r+this.search)}get search(){if(this._search===void 0){let[r,s]=Ue(this._node.req.url||"/");this._search=s,this._pathname===void 0&&(this._pathname=r)}return this._search}set search(r){r==="?"?r="":r&&r[0]!=="?"&&(r="?"+r),r!==this._search&&(this._search=r,this._searchParams=void 0,this._node.req.url=this.pathname+r)}get searchParams(){return this._searchParams||(this._searchParams=new URLSearchParams(this.search)),this._searchParams}set searchParams(r){this._searchParams=r,this._search=r.toString()}get protocol(){return this._protocol||(this._protocol=this._node.req.socket?.encrypted||this._node.req.headers["x-forwarded-proto"]==="https"?"https:":"http:"),this._protocol}set protocol(r){this._protocol=r}get origin(){return`${this.protocol}//${this.host}`}set origin(r){}get href(){return`${this.protocol}//${this.host}${this.pathname}${this.search}`}set href(r){let s=new globalThis.URL(r);this._protocol=s.protocol,this.username=s.username,this.password=s.password,this._hostname=s.hostname,this._port=s.port,this.pathname=s.pathname,this.search=s.search,this.hash=s.hash}toString(){return this.href}toJSON(){return this.href}get[Symbol.toStringTag](){return"URL"}[de](){return this.href}};return Object.setPrototypeOf(e.prototype,globalThis.URL.prototype),e})();function Ue(e){let t=(e||"/").replace(/\\/g,"/"),r=t.indexOf("?");return r===-1?[t,""]:[t.slice(0,r),t.slice(r)]}function Fe(e){let t=(e||"").split(":");return[t[0],String(Number.parseInt(t[1])||"")]}var tr=(()=>{let e=["cache","credentials","destination","integrity","keepalive","mode","redirect","referrer","referrerPolicy"],t=class{#r;#t;#e=!1;#s;#o;#n;#i;#a;#c;#l;#u;_node;runtime;constructor(s){this._node=s,this.runtime={name:"node",node:s}}get ip(){return this._node.req.socket?.remoteAddress}get headers(){return this.#t||(this.#t=new Zt(this._node)),this.#t}clone(){return new t({...this._node})}get _url(){return this.#r||(this.#r=new er(this._node)),this.#r}get url(){return this._url.href}get method(){return this._node.req.method||"GET"}get signal(){return this.#s||(this.#s=new AbortController,this._node.req.once("close",()=>{this.#s?.abort()})),this.#s.signal}get bodyUsed(){return this.#e}get _hasBody(){if(this.#o!==void 0)return this.#o;let s=this._node.req.method?.toUpperCase();return!s||!(s==="PATCH"||s==="POST"||s==="PUT"||s==="DELETE")?(this.#o=!1,!1):!Number.parseInt(this._node.req.headers["content-length"]||"")&&!(this._node.req.headers["transfer-encoding"]||"").split(",").map(o=>o.trim()).filter(Boolean).includes("chunked")?(this.#o=!1,!1):(this.#o=!0,!0)}get body(){return this._hasBody?(this.#u||(this.#e=!0,this.#u=new ReadableStream({start:s=>{this._node.req.on("data",n=>{s.enqueue(n)}).once("error",n=>{s.error(n),this.#s?.abort()}).once("close",()=>{this.#s?.abort()}).once("end",()=>{s.close()})}})),this.#u):null}bytes(){if(!this.#n){let s=this.body;this.#n=s?rr(s):Promise.resolve(new Uint8Array)}return this.#n}arrayBuffer(){return this.bytes().then(s=>s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength))}blob(){return this.#i||(this.#i=this.bytes().then(s=>new Blob([s],{type:this._node.req.headers["content-type"]}))),this.#i}formData(){return this.#a||(this.#a=new Response(this.body,{headers:this.headers}).formData()),this.#a}text(){return this.#l||(this.#l=this.bytes().then(s=>new TextDecoder().decode(s))),this.#l}json(){return this.#c||(this.#c=this.text().then(s=>JSON.parse(s))),this.#c}get[Symbol.toStringTag](){return"Request"}[de](){return{method:this.method,url:this.url,headers:this.headers}}};for(let r of e)Object.defineProperty(t.prototype,r,{enumerable:!0,configurable:!1});return Object.setPrototypeOf(t.prototype,globalThis.Request.prototype),t})();async function rr(e){let t=[];return await e.pipeTo(new WritableStream({write(r){t.push(r)}})),Buffer.concat(t)}var D=(()=>{let e="content-type",t="application/json",r=[[e,t]],s=class{#r;#t;constructor(o,i){this.#r=o,this.#t=i}static json(o,i){if(i?.headers){if(!i.headers[e]){let a=new Headers(i.headers);a.has(e)||a.set(e,t),i={...i,headers:a}}}else i=i?{...i}:{},i.headers=r;return new s(JSON.stringify(o),i)}static error(){return globalThis.Response.error()}static redirect(o,i){return globalThis.Response.redirect(o,i)}nodeResponse(){let o=this.#t?.status??200,i=this.#t?.statusText??"",a=[],l=this.#t?.headers;if(this.#s)for(let[f,h]of this.#s)if(f==="set-cookie")for(let m of $(h))a.push(["set-cookie",m]);else a.push([f,h]);else if(l){let f=Array.isArray(l)?l:l.entries?l.entries():Object.entries(l);for(let[h,m]of f)if(h==="set-cookie")for(let T of $(m))a.push(["set-cookie",T]);else a.push([h,m])}let c=this.#r,u;if(c)if(typeof c=="string")u=c;else if(c instanceof ReadableStream)u=c;else if(c instanceof ArrayBuffer)u=Buffer.from(c);else if(c instanceof Uint8Array)u=Buffer.from(c);else if(c instanceof DataView)u=Buffer.from(c.buffer);else if(c instanceof Blob)u=c.stream(),c.type&&a.push(["content-type",c.type]);else if(typeof c.pipe=="function")u=c;else{let f=new globalThis.Response(c);u=f.body;for(let[h,m]of f.headers)a.push([h,m])}return this.#r=void 0,this.#t=void 0,this.#s=void 0,this.#e=void 0,{status:o,statusText:i,headers:a,body:u}}#e;#s;clone(){return this.#e?this.#e.clone():this.#s?new s(this.#r,{...this.#t,headers:this.#s}):new s(this.#r,this.#t)}get#o(){return this.#e||(this.#e=this.#s?new globalThis.Response(this.#r,{...this.#t,headers:this.#s}):new globalThis.Response(this.#r,this.#t),this.#r=void 0,this.#t=void 0,this.#s=void 0),this.#e}get headers(){return this.#e?this.#e.headers:(this.#s||(this.#s=new Headers(this.#t?.headers)),this.#s)}get ok(){if(this.#e)return this.#e.ok;let o=this.#t?.status??200;return o>=200&&o<300}get redirected(){return this.#e?this.#e.redirected:!1}get status(){return this.#e?this.#e.status:this.#t?.status??200}get statusText(){return this.#e?this.#e.statusText:this.#t?.statusText??""}get type(){return this.#e?this.#e.type:"default"}get url(){return this.#e?this.#e.url:""}#n(o){let i=this.#r;return i==null?null:i instanceof o?i:!1}get body(){if(this.#e)return this.#e.body;let o=this.#n(ReadableStream);return o!==!1?o:this.#o.body}get bodyUsed(){return this.#e?this.#e.bodyUsed:!1}arrayBuffer(){if(this.#e)return this.#e.arrayBuffer();let o=this.#n(ArrayBuffer);return o!==!1?Promise.resolve(o||new ArrayBuffer(0)):this.#o.arrayBuffer()}blob(){if(this.#e)return this.#e.blob();let o=this.#n(Blob);return o!==!1?Promise.resolve(o||new Blob):this.#o.blob()}bytes(){if(this.#e)return this.#e.bytes();let o=this.#n(Uint8Array);return o!==!1?Promise.resolve(o||new Uint8Array):this.#o.bytes()}formData(){if(this.#e)return this.#e.formData();let o=this.#n(FormData);return o!==!1?Promise.resolve(o||new FormData):this.#o.formData()}text(){if(this.#e)return this.#e.text();let o=this.#r;return o==null?Promise.resolve(""):typeof o=="string"?Promise.resolve(o):this.#o.text()}json(){return this.#e?this.#e.json():this.text().then(o=>JSON.parse(o))}};return Object.setPrototypeOf(s.prototype,globalThis.Response.prototype),s})();function Ve(e){return new sr(e)}var sr=class{runtime="node";options;node;serveOptions;fetch;#r;#t;#e;constructor(e){this.options={...e,middleware:[...e.middleware||[]]};for(let l of e.plugins||[])l(this);De(this);let t=this.fetch=Me(this);this.#e=Ne();let r=(l,c)=>{let u=new tr({req:l,res:c});u.waitUntil=this.#e.waitUntil;let f=t(u);return f instanceof Promise?f.then(h=>Be(c,h)):Be(c,f)},s=Ie(this.options),{port:n,hostname:o}=Oe(this.options);this.serveOptions={port:n,host:o,exclusive:!this.options.reusePort,...s?{cert:s.cert,key:s.key,passphrase:s.passphrase}:{},...this.options.node};let i;if(this.#r=!!this.serveOptions.cert&&this.options.protocol!=="http",this.options.node?.http2??this.#r)if(this.#r){let{createSecureServer:l}=process.getBuiltinModule("node:http2");i=l({allowHTTP1:!0,...this.serveOptions},r)}else throw new Error("node.http2 option requires tls certificate!");else if(this.#r){let{createServer:l}=process.getBuiltinModule("node:https");i=l(this.serveOptions,r)}else{let{createServer:l}=process.getBuiltinModule("node:http");i=l(this.serveOptions,r)}this.node={server:i,handler:r},e.manual||this.serve()}serve(){if(this.#t)return Promise.resolve(this.#t).then(()=>this);this.#t=new Promise(e=>{this.node.server.listen(this.serveOptions,()=>{$e(this.options,this.url),e()})})}get url(){let e=this.node?.server?.address();if(e)return typeof e=="string"?e:Ae(e.address,e.port,this.#r)}ready(){return Promise.resolve(this.#t).then(()=>this)}async close(e){await Promise.all([this.#e.wait(),new Promise((t,r)=>{let s=this.node?.server;if(!s)return t();e&&"closeAllConnections"in s&&s.closeAllConnections(),s.close(n=>n?r(n):t())})])}};function We(e){e.config=Object.freeze(e.config),e._addRoute=()=>{throw new Error("Cannot add routes after the server init.")}}var Ke=class{app;req;url;context;static __is_event__=!0;_res;constructor(e,t,r){this.context=t||new R,this.req=e,this.app=r;let s=e._url;this.url=s&&s instanceof URL?s:new le(e.url)}get res(){return this._res||(this._res=new or),this._res}get runtime(){return this.req.runtime}waitUntil(e){this.req.waitUntil?.(e)}toString(){return`[${this.req.method}] ${this.req.url}`}toJSON(){return this.toString()}get node(){return this.req.runtime?.node}get headers(){return this.req.headers}get path(){return this.url.pathname+this.url.search}get method(){return this.req.method}},or=class{status;statusText;_headers;get headers(){return this._headers||(this._headers=new Headers),this._headers}},nr=/[^\u0009\u0020-\u007E]/g;function Ge(e=""){return e.replace(nr,"")}function Je(e,t=200){return!e||(typeof e=="string"&&(e=+e),e<100||e>599)?t:e}var C=class Ye extends Error{status;statusText;headers;cause;data;body;unhandled;static isError(t){return t?.constructor?.name==="HTTPError"}static status(t,r,s){return new Ye({...s,statusText:r,status:t})}constructor(t,r){let s,n;typeof t=="string"?(s=t,n=r):n=t;let o=Je(n?.status||n?.cause?.status||n?.status||n?.statusCode,500),i=Ge(n?.statusText||n?.cause?.statusText||n?.statusText||n?.statusMessage),a=s||n?.message||n?.cause?.message||n?.statusText||n?.statusMessage||["HTTPError",o,i].filter(Boolean).join(" ");super(a,{cause:n}),this.cause=n,Error.captureStackTrace?.(this,this.constructor),this.status=o,this.statusText=i||void 0;let l=n?.headers||n?.cause?.headers;this.headers=l?new Headers(l):void 0,this.unhandled=n?.unhandled??n?.cause?.unhandled??void 0,this.data=n?.data,this.body=n?.body}get statusCode(){return this.status}get statusMessage(){return this.statusText}toJSON(){let t=this.unhandled;return{status:this.status,statusText:this.statusText,unhandled:t,message:t?"HTTPError":this.message,data:t?void 0:this.data,...t?void 0:this.body}}};function ir(e,t){try{return t in e}catch{return!1}}function ar(e,t){if(e==null)return!0;if(t!=="object")return t==="boolean"||t==="number"||t==="string";if(typeof e.toJSON=="function"||Array.isArray(e))return!0;if(typeof e.pipe=="function"||typeof e.pipeTo=="function")return!1;if(e instanceof R)return!0;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}var B=Symbol.for("h3.notFound"),cr=Symbol.for("h3.handled");function X(e,t,r={}){if(e&&e instanceof Promise)return e.catch(o=>o).then(o=>X(o,t,r));let s=Xe(e,t,r);if(s instanceof Promise)return X(s,t,r);let{onResponse:n}=r;return n?Promise.resolve(n(s,t)).then(()=>s):s}function Xe(e,t,r,s){if(e===cr)return new D(null);if(e===B&&(e=new C({status:404,message:`Cannot find any route matching [${t.req.method}] ${t.url}`})),e&&e instanceof Error){let o=C.isError(e),i=o?e:new C(e);o||(i.unhandled=!0,e?.stack&&(i.stack=e.stack));let{onError:a}=r;return a&&!s?Promise.resolve(a(i,t)).catch(l=>l).then(l=>Xe(l??e,t,r,!0)):dr(i,r.debug)}let n=t.res._headers;if(!(e instanceof Response)){let o=ur(e,t,r),i=t.res.status;return new D(ze(t.req.method,i)?null:o.body,{status:i,statusText:t.res.statusText,headers:o.headers&&n?he(o.headers,n):o.headers||n})}return n?new D(ze(t.req.method,e.status)?null:e.body,{status:e.status,statusText:e.statusText,headers:he(n,e.headers)}):e}function he(e,t){let r=new Headers(e);for(let[s,n]of t)s==="set-cookie"?r.append(s,n):r.set(s,n);return r}var lr=new Headers({"content-length":"0"}),Q=new Headers({"content-type":"application/json;charset=UTF-8"});function ur(e,t,r){if(e==null)return{body:"",headers:lr};let s=typeof e;if(s==="string")return{body:e};if(e instanceof Uint8Array)return t.res.headers.set("content-length",e.byteLength.toString()),{body:e};if(ar(e,s))return{body:JSON.stringify(e,void 0,r.debug?2:void 0),headers:Q};if(s==="bigint")return{body:e.toString(),headers:Q};if(e instanceof Blob){let n={"content-type":e.type,"content-length":e.size.toString()},o=e.name;return o&&(o=encodeURIComponent(o),n["content-disposition"]=`filename="${o}"; filename*=UTF-8''${o}`),{body:e.stream(),headers:n}}return s==="symbol"?{body:e.toString()}:s==="function"?{body:`${e.name}()`}:{body:e}}function ze(e,t){return e==="HEAD"||t===100||t===101||t===102||t===204||t===205||t===304}function dr(e,t){return new D(JSON.stringify({...e.toJSON(),stack:t&&e.stack?e.stack.split(`
|
5 |
+
`).map(r=>r.trim()):void 0},void 0,t?2:void 0),{status:e.status,statusText:e.statusText,headers:e.headers?he(Q,e.headers):Q})}function hr(e,t={}){let r=fr(t);return!r&&(e.length>1||e.constructor?.name==="AsyncFunction")?e:(s,n)=>{if(r&&!r(s))return n();let o=e(s,n);return o===void 0||o===B?n():o}}function fr(e){if(!e.route&&!e.method&&!e.match)return;let t=e.route?Ce(e.route):void 0,r=e.method?.toUpperCase();return s=>{if(r&&s.req.method!==r||e.match&&!e.match(s))return!1;if(!t)return!0;let n=s.url.pathname.match(t);return n?(n.groups&&(s.context.middlewareParams={...s.context.middlewareParams,...n.groups}),!0):!1}}function fe(e,t,r,s=0){if(s===t.length)return r(e);let n=t[s],o=()=>fe(e,t,r,s+1),i=n(e,o);return i===void 0||i===B?o():i instanceof Promise?i.then(a=>a===void 0||a===B?o():a):i}var Qe=(()=>{let e=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"];class t{_middleware;_routes=[];config;constructor(s={}){this._middleware=[],this.config=s,this.fetch=this.fetch.bind(this),this._fetch=this._fetch.bind(this),this.handler=this.handler.bind(this),s.plugins?.forEach(n=>n(this))}fetch(s,n){try{return Promise.resolve(this._fetch(s,n))}catch(o){return Promise.reject(o)}}_fetch(s,n,o){let i=mr(s,n),a=new Ke(i,o,this),l;try{if(this.config.onRequest){let c=this.config.onRequest(a);l=c instanceof Promise?c.then(()=>this.handler(a)):this.handler(a)}else l=this.handler(a)}catch(c){l=Promise.reject(c)}return X(l,a,this.config)}register(s){return s(this),this}_findRoute(s){}_addRoute(s){this._routes.push(s)}handler(s){let n=this._findRoute(s);n&&(s.context.params=n.params,s.context.matchedRoute=n.data);let o=n?.data.middleware?[...this._middleware,...n.data.middleware]:this._middleware;return fe(s,o,()=>n?n.data.handler(s):B)}mount(s,n){if("handler"in n){n._middleware.length>0&&this._middleware.push((o,i)=>o.url.pathname.startsWith(s)?fe(o,n._middleware,i):i());for(let o of n._routes)this._addRoute({...o,route:s+o.route})}else{let o="fetch"in n?n.fetch:n;this.all(`${s}/**`,i=>{let a=new URL(i.url);return a.pathname=a.pathname.slice(s.length)||"/",o(new Request(a,i.req))})}return this}all(s,n,o){return this.on("",s,n,o)}on(s,n,o,i){let a=(s||"").toUpperCase();return n=new URL(n,"h://_").pathname,this._addRoute({method:a,route:n,handler:o,middleware:i?.middleware,meta:{...o.meta,...i?.meta}}),this}use(s,n,o){let i,a,l;return typeof s=="string"?(i=s,a=n,l=o):(a=s,l=n),this._middleware.push(hr(a,i?{...l,route:i}:l)),this}}for(let r of e)t.prototype[r.toLowerCase()]=function(s,n,o){return this.on(r,s,n,o)};return t})(),me=class extends Qe{_rou3;constructor(e={}){super(e),this._rou3=Pe()}_findRoute(e){return Re(this._rou3,e.req.method,e.url.pathname)}_addRoute(e){ke(this._rou3,e.method,e.route,e),super._addRoute(e)}};function mr(e,t){if(typeof e=="string"){let r=e;if(r[0]==="/"){let s=t?.headers?new Headers(t.headers):void 0,n=s?.get("host")||"localhost";r=`${s?.get("x-forwarded-proto")==="https"?"https":"http"}://${n}${r}`}return new Request(r,t)}else if(t||e instanceof URL)return new Request(e,t);return e}function pr(e){let t=new URLSearchParams(e),r=new R;for(let[s,n]of t.entries())ir(r,s)?(Array.isArray(r[s])||(r[s]=[r[s]]),r[s].push(n)):r[s]=n;return r}async function pe(e){let t=await e.req.text();if(!t)return;if((e.req.headers.get("content-type")||"").startsWith("application/x-www-form-urlencoded"))return pr(t);try{return JSON.parse(t)}catch{throw new C({status:400,statusText:"Bad Request",message:"Invalid JSON body"})}}function gr(e){return!e||e==="/"?"/":e[0]==="/"?e:`/${e}`}function wr(e){return!e||e==="/"?"/":e[e.length-1]==="/"?e.slice(0,-1):e}var yr={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".txt":"text/plain",".xml":"application/xml",".gif":"image/gif",".ico":"image/vnd.microsoft.icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".mp4":"video/mp4",".webm":"video/webm",".zip":"application/zip",".pdf":"application/pdf"};function _r(e){let t=e.split("/").pop();if(!t)return;let r=t.lastIndexOf(".");if(r!==-1)return t.slice(r)}function br(e){return e?yr[e]:void 0}async function Z(e,t){if(t.headers){let c=Array.isArray(t.headers)?t.headers:typeof t.headers.entries=="function"?t.headers.entries():Object.entries(t.headers);for(let[u,f]of c)e.res.headers.set(u,f)}if(e.req.method!=="GET"&&e.req.method!=="HEAD"){if(t.fallthrough)return;throw e.res.headers.set("allow","GET, HEAD"),new C({status:405})}let r=decodeURI(gr(wr(e.url.pathname))),s=Sr(e.req.headers.get("accept-encoding")||"",t.encodings);s.length>1&&e.res.headers.set("vary","accept-encoding");let n=r,o,i=Er(r,s,t.indexNames||["/index.html"]);for(let c of i){let u=await t.getMeta(c);if(u){o=u,n=c;break}}if(!o){if(t.fallthrough)return;throw new C({statusCode:404})}if(o.mtime){let c=new Date(o.mtime),u=e.req.headers.get("if-modified-since");if(u&&new Date(u)>=c)return e.res.status=304,e.res.statusText="Not Modified","";e.res.headers.get("last-modified")||e.res.headers.set("last-modified",c.toUTCString())}if(o.etag&&!e.res.headers.has("etag")&&e.res.headers.set("etag",o.etag),o.etag&&e.req.headers.get("if-none-match")===o.etag)return e.res.status=304,e.res.statusText="Not Modified","";if(!e.res.headers.get("content-type"))if(o.type)e.res.headers.set("content-type",o.type);else{let c=_r(n),u=c?t.getType?.(c)??br(c):void 0;u&&e.res.headers.set("content-type",u)}return o.encoding&&!e.res.headers.get("content-encoding")&&e.res.headers.set("content-encoding",o.encoding),o.size!==void 0&&o.size>0&&!e.req.headers.get("content-length")&&e.res.headers.set("content-length",o.size+""),e.req.method==="HEAD"?"":await t.getContents(n)}function Sr(e,t){return!t||!e?[]:String(e||"").split(",").map(r=>t[r.trim()]).filter(Boolean)}function Er(e,t,r){let s=[];for(let n of["",...r])for(let o of[...t,""])s.push(`${e}${n}${o}`);return s}function S(e,t){return new C(e,t)}function Ze(e,t){return We(e),Ve({fetch:e._fetch,...t})}import{stat as Bt,readFile as Lt}from"node:fs/promises";import{join as jt}from"node:path";import{chromium as Wr}from"playwright";var it=Yt(nt(),1);it.default.config();var qr={server:{port:parseInt(process.env.PORT||"3096",10),host:process.env.HOST||"localhost"},browser:{headless:(process.env.HEADLESS||"true").toLowerCase()!=="false",timeout:parseInt(process.env.TIMEOUT||"30000",10),executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,args:["--disable-blink-features=AutomationControlled","--no-sandbox","--disable-dev-shm-usage","--disable-infobars","--disable-extensions"],userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},cookieFile:"./cookies.json",cookiesFromEnv:process.env.COOKIES,screenshotDir:"./screenshots",aiStudio:{url:process.env.AI_STUDIO_URL||"https://aistudio.google.com/prompts/new_chat",responseTimeout:parseInt(process.env.RESPONSE_TIMEOUT||"600000",10),pageTimeout:parseInt(process.env.PAGE_TIMEOUT||"30000",10)},api:{defaultModel:process.env.DEFAULT_MODEL||"gemini-pro",maxTokens:65536,temperature:1,token:process.env.API_TOKEN},models:{"gemini-2.5-pro":{displayName:"Gemini 2.5 Pro",id:"gemini-2.5-pro",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-pro",parent:null},"gemini-2.5-flash":{displayName:"Gemini 2.5 Flash",id:"gemini-2.5-flash",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-flash",parent:null},"gemini-pro":{displayName:"Gemini Pro",id:"gemini-pro",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-pro",parent:null},"gemini-flash":{displayName:"Gemini Flash",id:"gemini-flash",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-flash",parent:null}},debug:{logRequests:process.env.DEBUG_REQUESTS==="true",logResponses:process.env.DEBUG_RESPONSES==="true",saveScreenshots:process.env.SAVE_SCREENSHOTS==="true"}},p=qr;te();U();var A=null,N=null,re=class{constructor(t=5){this.maxSize=t,this.availablePages=[],this.busyPages=new Set,this.totalPages=0}async getPage(){if(this.availablePages.length>0){let t=this.availablePages.pop();return this.busyPages.add(t),d(`\u4ECE\u9875\u9762\u6C60\u83B7\u53D6\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),t}if(this.totalPages<this.maxSize){let{context:t}=await Kr(),r=await t.newPage();return this.busyPages.add(r),this.totalPages++,d(`\u521B\u5EFA\u65B0\u9875\u9762\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),r}return d("\u9875\u9762\u6C60\u5DF2\u6EE1\uFF0C\u7B49\u5F85\u9875\u9762\u91CA\u653E..."),new Promise(t=>{let r=()=>{if(this.availablePages.length>0){let s=this.availablePages.pop();this.busyPages.add(s),d(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),t(s)}else setTimeout(r,100)};r()})}async releasePage(t){if(!this.busyPages.has(t)){d("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}if(t._needsRemoval){d("\u9875\u9762\u88AB\u6807\u8BB0\u4E3A\u9700\u8981\u79FB\u9664\uFF0C\u5C06\u4ECE\u6C60\u4E2D\u79FB\u9664"),await this.removePage(t);return}try{await this.cleanupPage(t),this.busyPages.delete(t),this.availablePages.push(t),d(`\u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D\uFF0C\u53EF\u7528\u9875\u9762\u6570: ${this.availablePages.length}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`)}catch(r){d(`\u6E05\u7406\u9875\u9762\u65F6\u51FA\u9519\uFF0C\u5C06\u5173\u95ED\u8BE5\u9875\u9762: ${r.message}`),await this.removePage(t)}}async cleanupPage(t){try{t.removeAllListeners();try{await t.evaluate(()=>{Object.keys(window).forEach(s=>{(s.startsWith("__handleStreamChunk")||s.startsWith("__onStreamChunk")||s.startsWith("__onStreamEnd"))&&delete window[s]}),window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor),delete window.__handleStreamChunk,delete window.__onStreamChunk,delete window.__onStreamEnd,delete window.__streamCallbacks})}catch(r){d(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${r.message}`)}d("\u9875\u9762\u72B6\u6001\u5DF2\u6E05\u7406")}catch(r){throw new Error(`\u6E05\u7406\u9875\u9762\u5931\u8D25: ${r.message}`)}}async removePage(t){try{this.busyPages.delete(t);let r=this.availablePages.indexOf(t);r>-1&&this.availablePages.splice(r,1),await t.close(),this.totalPages--,d(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(r){d(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${r.message}`)}}async cleanup(){d("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let t of this.busyPages)try{await t.close()}catch(r){d(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${r.message}`)}for(let t of this.availablePages)try{await t.close()}catch(r){d(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${r.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,d("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},x=null;async function Kr(){if(!A){A=await Wr.launch({headless:p.browser.headless,timeout:p.browser.timeout,args:p.browser.args,executablePath:p.browser.executablePath}),N=await A.newContext({userAgent:p.browser.userAgent});let e=_e(p.cookieFile,p.cookiesFromEnv);await N.addCookies(e)}return{browser:A,context:N}}function ht(e=5){return x||(x=new re(e),d(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${e}`)),x}function ft(){return x||(x=new re,d("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),x}async function se(){let t=await ft().getPage();return await t.bringToFront(),t}async function V(e,t,r={}){let s=e.url();console.log("\u5F53\u524D\u9875\u9762URL:",s),console.log("\u76EE\u6807URL:",t);try{return s!==t?(console.log("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await e.goto(t,{waitUntil:"load",timeout:3e4,...r}),console.log("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(console.log("\u9875\u9762\u5DF2\u5728\u76EE\u6807URL\uFF0C\u8FDB\u884C\u5237\u65B0\u4EE5\u786E\u4FDD\u6700\u65B0\u72B6\u6001..."),await e.bringToFront(),await e.reload({waitUntil:"load",timeout:3e4,...r}),console.log("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function z(e){await ft().releasePage(e)}function W(){return x?x.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function dt(){x&&(await x.cleanup(),x=null),N&&(await N.close(),N=null),A&&(await A.close(),A=null)}async function mt(e,t={}){let{minClicks:r=1,maxClicks:s=3,minDelay:n=300,maxDelay:o=500,referenceElement:i=null}=t;try{d("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let a=Math.floor(Math.random()*(s-r+1))+r;d(`\u5C06\u8FDB\u884C ${a} \u6B21\u968F\u673A\u70B9\u51FB`);let l=null;if(i)try{let c=await i.boundingBox();c&&(l={x:c.x-50,y:Math.max(0,c.y-200),width:c.width+50,height:300},d(`\u4F7F\u7528\u8F93\u5165\u6846\u9644\u8FD1\u7684\u5B89\u5168\u533A\u57DF: x=${l.x}, y=${l.y}, w=${l.width}, h=${l.height}`))}catch(c){d(`\u83B7\u53D6\u53C2\u8003\u5143\u7D20\u4F4D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: ${c.message}`)}if(!l){let c=e.viewportSize(),u=c?.width||1280,f=c?.height||720;l={x:u*.3,y:f*.3,width:u*.4,height:f*.2},d(`\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: x=${l.x}, y=${l.y}, w=${l.width}, h=${l.height}`)}for(let c=0;c<a;c++)try{let u=Math.floor(Math.random()*l.width)+l.x,f=Math.floor(Math.random()*l.height)+l.y;d(`\u7B2C ${c+1} \u6B21\u5B89\u5168\u70B9\u51FB: (${u}, ${f})`);let h=await e.locator("*").first().evaluate((m,T)=>{let g=document.elementFromPoint(T.x,T.y);if(!g)return{safe:!0};let y=g.tagName.toLowerCase(),b=g.hasAttribute("href"),P=g.hasAttribute("onclick")||g.onclick,E=y==="button"||g.type==="button",w=y==="a"||b,k=["input","textarea","select"].includes(y);return{safe:!E&&!w&&!P&&!k,tagName:y,hasHref:b,hasOnClick:P,isButton:E,isLink:w,isInput:k}},{x:u,y:f});if(h.safe?(await e.mouse.move(u,f,{steps:Math.floor(Math.random()*10)+5}),await e.waitForTimeout(Math.floor(Math.random()*200)+100),await e.mouse.click(u,f),d(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${u}, ${f})`)):d(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${u}, ${f}): ${h.tagName}`),c<a-1){let m=Math.floor(Math.random()*(o-n+1))+n;d(`\u7B49\u5F85 ${m}ms \u540E\u8FDB\u884C\u4E0B\u4E00\u6B21\u70B9\u51FB`),await e.waitForTimeout(m)}}catch(u){d(`\u7B2C ${c+1} \u6B21\u70B9\u51FB\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u6B21: ${u.message}`)}d("\u5B89\u5168\u968F\u673A\u70B9\u51FB\u6A21\u62DF\u5B8C\u6210")}catch(a){d(`\u6A21\u62DF\u5B89\u5168\u968F\u673A\u70B9\u51FB\u65F6\u51FA\u73B0\u9519\u8BEF: ${a.message}`)}}async function pt(e,t={}){let{includeScrolling:r=!0,includeMouseMovement:s=!0,includeRandomClicks:n=!0,duration:o=3e3}=t;try{d("\u5F00\u59CB\u6A21\u62DF\u590D\u6742\u7684\u4EBA\u7C7B\u884C\u4E3A...");let i=Date.now(),a=e.viewportSize(),l=a?.width||1280,c=a?.height||720;for(;Date.now()-i<o;){let u=Math.random();if(u<.3&&r){let h=Math.random()>.5?"down":"up",m=Math.floor(Math.random()*300)+100;d(`\u6A21\u62DF\u6EDA\u52A8: ${h}, \u8DDD\u79BB: ${m}px`),await e.mouse.wheel(0,h==="down"?m:-m)}else if(u<.6&&s){let h=Math.floor(Math.random()*l),m=Math.floor(Math.random()*c);d(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${h}, ${m})`),await e.mouse.move(h,m,{steps:Math.floor(Math.random()*15)+5})}else if(u<.8&&n){let h=Math.floor(Math.random()*(l*.8))+l*.1,m=Math.floor(Math.random()*(c*.8))+c*.1;d(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${h}, ${m})`),await e.mouse.click(h,m)}let f=Math.floor(Math.random()*800)+200;await e.waitForTimeout(f)}d("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(i){d(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${i.message}`)}}async function oe(e,t=5e3){try{d("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let r="mat-dialog-container",s='button[mat-dialog-close][aria-label="close"]';if(await e.locator(r).first().isVisible({timeout:t})){d("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let o=e.locator(s).first();return await o.isVisible({timeout:2e3})?(await o.click(),d("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await e.waitForTimeout(1e3),!0):(d("\u672A\u627E\u5230\u5173\u95ED\u6309\u94AE\uFF0C\u5C1D\u8BD5\u6309ESC\u952E\u5173\u95ED\u5BF9\u8BDD\u6846"),await e.keyboard.press("Escape"),await e.waitForTimeout(1e3),!0)}else return d("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(r){return d("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",r.message),!1}}async function gt(e,t,r){try{d("\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u5230\u9875\u9762\u4E2D...");try{await e.evaluate(()=>{Object.keys(window).forEach(i=>{(i.startsWith("__onStreamChunk_")||i.startsWith("__onStreamEnd_"))&&delete window[i]}),delete window.__onStreamChunk,delete window.__onStreamEnd})}catch{}let s=Date.now()+"_"+Math.random().toString(36).substr(2,9),n=`__onStreamChunk_${s}`,o=`__onStreamEnd_${s}`;await e.exposeFunction(n,t),await e.exposeFunction(o,r),await e.evaluate(()=>{window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor);let i=window.XMLHttpRequest.prototype.open,a=window.XMLHttpRequest.prototype.send,l=["MakerSuiteService/GenerateContent","GenerateContent","streamGenerateContent","generateContent"],c=/\[\s*null\s*,\s*null\s*,\s*null\s*,\s*\[\s*"/,u="__END_OF_STREAM__",f=!1;window.__streamInterceptor={activate:()=>{f||(console.log("\u{1F3AF} \u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668..."),f=!0,window.XMLHttpRequest.prototype.open=function(h,m,...T){return this._url=m,this._method=h,console.log(`[XHR] \u8BF7\u6C42: ${h} ${m}`),i.apply(this,[h,m,...T])},window.XMLHttpRequest.prototype.send=function(...h){let m=this._url?this._url.toString():"",T=l.some(g=>m.includes(g));if(this._url&&T){console.log("\u{1F3AF} [XHR Stream] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42:",m),console.log("\u{1F3AF} [XHR Stream] \u51C6\u5907\u63A5\u6536\u6D41\u5F0F\u6570\u636E...");let g=0,y="",b=!1,P=null,E=()=>{if(b)return;b=!0,console.log("[Stream] \u5224\u5B9A\u6D41\u5DF2\u7ED3\u675F"),clearTimeout(P);let w=y.slice(g);w&&window.__streamInterceptor.sendChunk(w),window.__streamInterceptor.sendChunk(u)};this.addEventListener("progress",()=>{if(!b)try{y=this.responseText||"";let w=y.slice(g);if(w){if(console.log(`[Stream] \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${w.length}\uFF0CHTTP\u72B6\u6001: ${this.status}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${w.substring(0,100)}...`),window.__streamInterceptor.sendChunk(w),g=y.length,this.status>=400&&this.readyState===4){console.log(`[Stream] progress\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u7ED3\u675F\u6D41`),E();return}c.test(w)&&(console.log("[Stream] \u2705 \u68C0\u6D4B\u5230\u6700\u7EC8 ID \u7B7E\u540D\u5757\uFF0C\u786E\u8BA4\u6D41\u7ED3\u675F"),E())}}catch(w){console.error("[Stream] \u5904\u7406progress\u4E8B\u4EF6\u65F6\u51FA\u9519:",w)}}),this.addEventListener("readystatechange",()=>{if(!b&&(console.log(`[Stream] readyState: ${this.readyState}, status: ${this.status}`),this.readyState===3||this.readyState===4))try{let w=this.responseText||"",k=w.slice(g);if(k&&(console.log(`[Stream] readyState ${this.readyState} \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${k.length}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${k.substring(0,200)}...`),window.__streamInterceptor.sendChunk(k),g=w.length,y=w,c.test(k)&&(console.log("[Stream] \u2705 readyState\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230\u6700\u7EC8\u7B7E\u540D"),E())),this.readyState===4&&!b)if(console.log(`[Stream] \u8BF7\u6C42\u5B8C\u6210\uFF0CHTTP\u72B6\u6001\u7801: ${this.status}`),this.status>=400){if(console.log(`[Stream] \u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u5904\u7406\u9519\u8BEF\u54CD\u5E94`),y&&y!==w){let ie=y.slice(g);ie&&(console.log(`[Stream] \u53D1\u9001\u5269\u4F59\u9519\u8BEF\u54CD\u5E94\u6570\u636E: ${ie}`),window.__streamInterceptor.sendChunk(ie))}E()}else b||(console.log("[Stream] \u6B63\u5E38\u8BF7\u6C42\u5B8C\u6210\uFF0C\u8BBE\u7F6E\u4FDD\u9669\u8BA1\u65F6\u5668"),P=setTimeout(E,1e3))}catch(w){console.error("[Stream] \u5904\u7406readystatechange\u4E8B\u4EF6\u65F6\u51FA\u9519:",w)}}),this.addEventListener("load",()=>{b||(console.log('[Stream] "load" \u4E8B\u4EF6\u89E6\u53D1\uFF0C\u542F\u52A8\u6700\u7EC8\u786E\u8BA4\u8BA1\u65F6\u5668'),P=setTimeout(E,1500))}),this.addEventListener("error",w=>{console.error("[Stream] XHR \u8BF7\u6C42\u51FA\u9519:",w),b||E()}),this.addEventListener("abort",()=>{console.log("[Stream] XHR \u8BF7\u6C42\u88AB\u4E2D\u6B62"),b||E()})}return a.apply(this,h)})},deactivate:()=>{f&&(console.log("\u{1F504} \u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668..."),window.XMLHttpRequest.prototype.open=i,window.XMLHttpRequest.prototype.send=a,f=!1)},sendChunk:h=>{try{console.log(`[Stream] \u53D1\u9001\u6570\u636E\u5757\u5230Playwright\uFF0C\u957F\u5EA6: ${h.length}`),window.__handleStreamChunk?window.__handleStreamChunk(h):console.error("[Stream] __handleStreamChunk \u51FD\u6570\u4E0D\u5B58\u5728")}catch(m){console.error("[Stream] \u53D1\u9001\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}}},window.__streamCallbacks={onChunk:null,onEnd:null},window.__handleStreamChunk=function(h){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",h.length,"\u5B57\u7B26"),h==="__END_OF_STREAM__"?window.__streamCallbacks.onEnd&&window.__streamCallbacks.onEnd():window.__streamCallbacks.onChunk&&window.__streamCallbacks.onChunk(h)}catch(m){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}},console.log("[Stream] \u62E6\u622A\u5668\u548C\u5904\u7406\u51FD\u6570\u5DF2\u521B\u5EFA\u5B8C\u6210")}),await e.evaluate(i=>{window.__streamCallbacks.onChunk=window[i],console.log("[Stream] onChunk\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",i)},n),await e.evaluate(i=>{window.__streamCallbacks.onEnd=window[i],console.log("[Stream] onEnd\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",i)},o),d("\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u6CE8\u5165\u5B8C\u6210")}catch(s){throw d(`\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u65F6\u51FA\u9519: ${s.message}`),s}}async function wt(e){try{await e.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.activate(),window.__handleStreamChunk||(console.log("[Stream] \u91CD\u65B0\u521B\u5EFA __handleStreamChunk \u51FD\u6570"),window.__handleStreamChunk=function(t){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",t.length,"\u5B57\u7B26"),t==="__END_OF_STREAM__"?window.__onStreamEnd&&window.__onStreamEnd():window.__onStreamChunk&&window.__onStreamChunk(t)}catch(r){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",r)}},console.log("[Stream] __handleStreamChunk \u51FD\u6570\u5DF2\u91CD\u65B0\u521B\u5EFA"))}),d("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B")}catch(t){throw d(`\u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${t.message}`),t}}async function yt(e){try{await e.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.deactivate()}),d("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u505C\u7528")}catch(t){d(`\u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${t.message}`)}}function _t(){process.on("SIGINT",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await dt(),process.exit(0)}),process.on("SIGTERM",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await dt(),process.exit(0)})}U();var bt=null;function St(e=1e4){if(bt){d("\u9875\u9762\u6C60\u76D1\u63A7\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002");return}d(`\u5F00\u59CB\u76D1\u63A7\u9875\u9762\u6C60\u72B6\u6001\uFF0C\u95F4\u9694: ${e}ms`),bt=setInterval(()=>{let t=W(),r=new Date().toLocaleTimeString(),s=t.total>0?(t.busy/t.total*100).toFixed(1):0;d(`[${r}] \u9875\u9762\u6C60\u72B6\u6001: \u603B\u8BA1=${t.total}, \u53EF\u7528=${t.available}, \u5FD9\u788C=${t.busy}, \u4F7F\u7528\u7387=${s}%`)},e)}function Et(){let e=W(),t=new Date().toLocaleString(),r=e.total>0?(e.busy/e.total*100).toFixed(1):0;console.log(`
|
6 |
+
--- \u9875\u9762\u6C60\u72B6\u6001 @ ${t} ---
|
7 |
+
\u603B\u9875\u9762\u6570: ${e.total}
|
8 |
+
\u53EF\u7528\u9875\u9762\u6570: ${e.available}
|
9 |
+
\u5FD9\u788C\u9875\u9762\u6570: ${e.busy}
|
10 |
+
\u6700\u5927\u9875\u9762\u6570: ${e.maxSize}
|
11 |
+
\u4F7F\u7528\u7387: ${r}%
|
12 |
+
------------------------------------
|
13 |
+
`)}function xt(e){let t=e.node.res.getHeaders();if(t["access-control-allow-origin"]||e.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),t["access-control-allow-methods"]||e.node.res.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t["access-control-allow-headers"]||e.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t["access-control-max-age"]||e.node.res.setHeader("Access-Control-Max-Age","86400"),e.node.req.method==="OPTIONS")return e.node.res.statusCode=204,e.node.res.end()}function Tt(e){e.node.res.setHeader("Content-Type","text/event-stream"),e.node.res.setHeader("Cache-Control","no-cache"),e.node.res.setHeader("Connection","keep-alive"),e.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),e.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization")}function Pt(e){let t=W(),r=t.total>0?Math.round(t.busy/t.total*100):0;return{status:"ok",timestamp:new Date().toISOString(),version:process.env.npm_package_version||"1.0.0",pagePool:{...t,utilization:`${r}%`}}}function vt(e){let{messages:t,stream:r=!1,model:s=p.api.defaultModel,temperature:n=p.api.temperature}=e;if(!t||!Array.isArray(t)||t.length===0)throw S({statusCode:400,statusMessage:"Invalid request: `messages` must be a non-empty array."});return{prompt:t.map(i=>!i.role||!i.content?"":`${i.role}: ${i.content}`).join(`
|
14 |
+
|
15 |
+
`),stream:r,model:s,temperature:n,messages:t}}function kt(e){if(!p.api.token){process.env.NODE_ENV==="production"&&console.warn("\u8B66\u544A: API_TOKEN \u672A\u5728\u751F\u4EA7\u73AF\u5883\u4E2D\u914D\u7F6E\uFF0CAPI \u5BF9\u5916\u5F00\u653E\uFF01");return}let t=e.node.req.headers.authorization;if(!t)throw S({statusCode:401,statusMessage:"Unauthorized: Missing Authorization header."});let[r,s]=t.split(" ");if(r!=="Bearer"||!s)throw S({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer <token>."});if(s!==p.api.token)throw S({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}var K=class{constructor(t,r={}){this.page=t,this.options={enableHumanSimulation:!0,...r},this.modelMapping=Object.fromEntries(Object.entries(p.models).map(([s,n])=>[s,n.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await oe(this.page),!0}catch(t){return console.error("\u9875\u9762\u52A0\u8F7D\u8D85\u65F6\u6216\u5931\u8D25:",t),!1}}async findInputElement(){try{await this.page.waitForSelector("footer ms-prompt-input-wrapper",{timeout:1e4}),console.log("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{console.warn("\u7B49\u5F85\u8F93\u5165\u6846\u7236\u5BB9\u5668\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u67E5\u627E...")}let t=['ms-prompt-input-wrapper textarea[aria-label*="prompt"]','textarea[placeholder="Start typing a prompt"]','textarea[aria-label="Start typing a prompt"]',"footer textarea",'textarea[placeholder*="prompt"]','textarea[aria-label*="prompt"]','div[contenteditable="true"]',"textarea"];for(let r of t)try{let s=this.page.locator(r),n=await s.count();if(n>0){console.log(`\u9009\u62E9\u5668 "${r}" \u627E\u5230\u4E86 ${n} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let o=0;o<n;o++){let i=s.nth(o);if(await i.isVisible()&&await i.isEnabled())return console.log(`\u6210\u529F\u627E\u5230\u53EF\u7528\u8F93\u5165\u6846: ${r} (\u7D22\u5F15 ${o})`),i}console.log(`\u9009\u62E9\u5668 "${r}" \u627E\u5230\u7684\u5143\u7D20\u5747\u4E0D\u53EF\u89C1\u6216\u4E0D\u53EF\u7528\u3002`)}}catch(s){console.warn(`\u4F7F\u7528\u9009\u62E9\u5668 "${r}" \u67E5\u627E\u65F6\u51FA\u9519: ${s.message}`)}if(console.error("\u5173\u952E\u9519\u8BEF: \u5C1D\u8BD5\u4E86\u6240\u6709\u9009\u62E9\u5668\u540E\uFF0C\u4ECD\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u8F93\u5165\u5143\u7D20\u3002"),p.debug.saveScreenshots){let{saveScreenshot:r}=await Promise.resolve().then(()=>(te(),ut));await r(this.page,p.screenshotDir,"find-input-failed")}return null}async findSendButton(){let t=['button[aria-label="Run"]',"button.run-button",'button[aria-label*="Send"]','button[data-testid*="send"]'];for(let r of t){let s=this.page.locator(r);if(await s.count()>0){let n=s.first();if(!await n.isDisabled())return n}}return console.error("\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002"),null}async fillMessage(t){let r=await this.findInputElement();if(!r)throw new Error("\u65E0\u6CD5\u627E\u5230\u8F93\u5165\u6846\u3002");try{return this.options.enableHumanSimulation&&await mt(this.page,{referenceElement:r}),await r.fill(t),await this.page.waitForTimeout(200),console.log("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(s){return console.error("\u586B\u5145\u6D88\u606F\u5931\u8D25:",s),!1}}async waitForSendButtonEnabled(t=1e4){try{return await this.page.locator('button[aria-label="Run"]:not([disabled]), button.run-button:not([disabled])').waitFor({state:"visible",timeout:t}),console.log("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return console.warn("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await pt(this.page,{includeScrolling:!1,duration:1500});let t=await this.findSendButton();if(!t)throw new Error("\u65E0\u6CD5\u627E\u5230\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002");try{return await t.click(),console.log("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(r){console.error("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",r);try{return console.log("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),console.log("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(s){return console.error("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",s),!1}}}async setModel(t){try{let r=this.modelMapping[t]||t,s=this.page.locator("ms-model-selector-two-column");if(await s.count()===0)return console.log("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await s.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===r)return console.log("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await s.click({timeout:5e3});let o=this.page.locator(".mat-mdc-select-panel");await o.waitFor({state:"visible",timeout:5e3});let i=o.locator("mat-option.model-option",{hasText:r});return await i.count()>0?(await i.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),console.log(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${r}`),!0):(console.log(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${r}`),await this.page.keyboard.press("Escape"),!1)}catch(r){console.error("\u8BBE\u7F6E\u6A21\u578B\u65F6\u53D1\u751F\u9519\u8BEF:",r);try{await this.page.keyboard.press("Escape")}catch{}return!1}}async setTemperature(t){try{let r=this.page.locator('[data-test-id="temperatureSliderContainer"]');if(await r.count()===0)return console.log("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let s=r.locator('input[type="number"]');return await s.count()>0?(await s.fill(t.toString()),await s.dispatchEvent("change"),console.log(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${t}`),!0):(console.log("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(r){return console.error("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",r),!1}}async processMessage(t,r={}){if(console.log("\u5F00\u59CB\u5904\u7406\u6D88\u606F..."),!await this.waitForPageLoad())throw new Error("\u9875\u9762\u52A0\u8F7D\u5931\u8D25\u3002");if(r.model&&await this.setModel(r.model),r.temperature!==void 0&&await this.setTemperature(r.temperature),!await this.fillMessage(t))throw new Error("\u6D88\u606F\u586B\u5199\u5931\u8D25\u3002");if(await this.waitForSendButtonEnabled(),!await this.sendMessage())throw new Error("\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002");return console.log("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};function Gr(e){return e.includes("The caller does not have permission")?(console.warn("\u68C0\u6D4B\u5230\u6743\u9650\u9519\u8BEF\uFF0C\u5C06\u89E6\u53D1\u91CD\u8BD5\u673A\u5236\u3002"),{permissionError:!0,content:"\u65E0\u6743\u8BBF\u95EE AI Studio\u3002\u8BF7\u68C0\u67E5 Cookie \u6216\u767B\u5F55\u72B6\u6001\u3002"}):null}function Rt(e){let t=[];if(!e)return t;if(Array.isArray(e)){if(e.length>=2&&e[0]===null&&typeof e[1]=="string"&&e[1]&&e[1]!=="model"){let r=e.length>2?"thinking":"text";t.push({type:r,content:e[1].replace(/\\n/g,`
|
16 |
+
`).replace(/\\"/g,'"')})}for(let r of e)t.push(...Rt(r))}return t}function Se(e){let t=Gr(e);if(t)return t;try{let o=e.trim().replace(/\n/g,",").replace(/,+/g,",");o.endsWith(",")&&(o=o.slice(0,-1)),o.startsWith("[")||(o="["+o),o.endsWith("]")||(o=o+"]"),o=o.replace(/,]/g,"]").replace(/\[,/g,"[");let i=JSON.parse(o),a=Rt(i);if(a.length>0){let l=!1;return a.map(c=>(l?c.type="text":c.type==="text"&&(l=!0),c))}}catch{}let r=/\[null,\s*"((?:\\"|[^"])*)"/g,s=[],n;for(;(n=r.exec(e))!==null;)try{let o=n[1].replace(/\\n/g,`
|
17 |
+
`).replace(/\\"/g,'"');if(o&&o!=="model"){let i=o.trim().startsWith("**")?"thinking":"text";s.push({type:i,content:o})}}catch{}if(s.length>0){let o=!1;return s.map(i=>(o?i.type="text":i.type==="text"&&(o=!0),i))}return null}function Ct(e,t,r="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:r,choices:[{index:0,delta:{content:e||"",type:t||"text"},logprobs:null,finish_reason:null}]}}function Ee(e,t="gemini-pro"){return{object:"error",message:e,type:"invalid_request_error",model:t}}function Ht(e,t="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}var ne=3,Ot=1e3;function At(e){let t=e.message.toLowerCase();return["timeout","navigation failed","page crashed","target closed","element not found","is not visible","\u65E0\u6CD5\u627E\u5230","not find","cannot find"].some(s=>t.includes(s))}function Jr(e){let t=e.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(s=>t.includes(s))}async function Yr(e){console.log("\u9875\u9762\u72B6\u6001\u5F02\u5E38\u6216\u9047\u5230\u6743\u9650\u95EE\u9898\uFF0C\u5F00\u59CB\u91CD\u7F6E...");try{await e.reload({waitUntil:"networkidle",timeout:2e4}),console.log("\u9875\u9762\u5237\u65B0\u6210\u529F\u3002")}catch(t){console.warn("\u9875\u9762\u5237\u65B0\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u65B0\u5BFC\u822A:",t.message);try{await V(e,p.aiStudio.url,{timeout:p.aiStudio.pageTimeout}),console.log("\u91CD\u65B0\u5BFC\u822A\u6210\u529F\u3002")}catch(r){throw console.error("\u9875\u9762\u91CD\u7F6E\u5931\u8D25\uFF1A\u5237\u65B0\u548C\u91CD\u65B0\u5BFC\u822A\u5747\u544A\u5931\u8D25\u3002",r),new Error("Failed to reset page state.")}}}async function $t(e,t,r){let s=null,n=null;try{s=await se();for(let o=1;o<=ne;o++)try{console.log(`[\u5C1D\u8BD5 ${o}/${ne}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),(o===1||!s.url().includes("aistudio.google.com"))&&await V(s,p.aiStudio.url,{timeout:p.aiStudio.pageTimeout});let i=await r(s,e,t);return await z(s),i}catch(i){if(n=i,console.warn(`[\u5C1D\u8BD5 ${o}/${ne}] \u5931\u8D25: ${i.message}`),(Jr(i)||At(i))&&o<ne)console.log(`\u68C0\u6D4B\u5230\u53EF\u91CD\u8BD5\u7684\u9519\u8BEF\uFF08\u6743\u9650\u6216\u9875\u9762\u72B6\u6001\uFF09\uFF0C\u5C06\u5728 ${Ot}ms \u540E\u91CD\u8BD5...`),await Yr(s),await new Promise(a=>setTimeout(a,Ot));else throw console.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),i}}catch(o){throw console.error("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",o),s&&(At(o)&&(s._needsRemoval=!0),await z(s)),n||o}}async function It(e,t,r={}){let s=r.model||p.api.defaultModel;try{await $t(e,r,async(n,o,i)=>new Promise(async(a,l)=>{let c=!1,u="",f=new Set,h=g=>{c||(c=!0,yt(n).catch(console.error),g?l(g):a())},m=g=>{if(c)return;u+=g;let y=Se(u);if(y?.permissionError)return h(new Error(y.content));if(Array.isArray(y)&&y.length>0)for(let b of y){let P=`${b.type}::${b.content}`;b.content?.trim()&&!f.has(P)&&(t.enqueue(`data: ${JSON.stringify(Ct(b.content,b.type,s))}
|
18 |
+
|
19 |
+
`),f.add(P))}},T=()=>{c||(console.log("\u6D41\u5DF2\u7ED3\u675F\uFF0C\u53D1\u9001 [DONE] \u4FE1\u53F7\u3002"),t.enqueue(`data: [DONE]
|
20 |
+
|
21 |
+
`),t.close(),h())};try{await gt(n,m,T),await wt(n),await new K(n).processMessage(o,i),setTimeout(()=>{c||h(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},p.aiStudio.responseTimeout)}catch(g){h(g)}}))}catch(n){if(t.desiredSize!==null)try{t.enqueue(`data: ${JSON.stringify(Ee(n.message,s))}
|
22 |
+
|
23 |
+
`),t.enqueue(`data: [DONE]
|
24 |
+
|
25 |
+
`),t.close()}catch(o){console.error("\u5173\u95ED\u6D41\u63A7\u5236\u5668\u65F6\u51FA\u9519:",o)}}}async function Nt(e,t={}){let r=t.model||p.api.defaultModel;try{return await $t(e,t,async(s,n,o)=>new Promise(async(i,a)=>{let l="",c=async u=>{if(u.url().includes("GenerateContent"))try{let f=await u.text(),h=Se(f);if(h?.permissionError)return a(new Error(h.content));Array.isArray(h)&&(l+=h.filter(m=>m.type==="text").map(m=>m.content).join("")),s.removeListener("response",c),i(Ht(l,r))}catch(f){a(f)}};s.on("response",c);try{await new K(s).processMessage(n,o),setTimeout(()=>{s.removeListener("response",c),a(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},p.aiStudio.responseTimeout)}catch(u){s.removeListener("response",c),a(u)}}))}catch(s){return Ee(s.message,r)}}async function Mt(e){try{kt(e);let t=await pe(e),{prompt:r,stream:s,model:n,temperature:o}=vt(t);return s?(Tt(e),new ReadableStream({start(a){It(r,a,{model:n,temperature:o})}})):await Nt(r,{model:n,temperature:o})}catch(t){throw console.error("\u5904\u7406\u804A\u5929\u8BF7\u6C42\u65F6\u51FA\u9519:",t),t.statusCode?t:S({statusCode:500,statusMessage:t.message||"An internal server error occurred."})}}async function qt(e){try{let t=Object.values(p.models).map(r=>({id:r.id,object:r.object,created:r.created,owned_by:r.owned_by,permission:r.permission,root:r.root,parent:r.parent}));return t.sort((r,s)=>s.created-r.created),{object:"list",data:t}}catch(t){throw console.error("\u83B7\u53D6\u6A21\u578B\u5217\u8868\u65F6\u51FA\u9519:",t),S({statusCode:500,statusMessage:"Failed to retrieve models list."})}}async function Dt(e){try{let t=e.context.params?.model;if(!t)throw S({statusCode:400,statusMessage:"Model ID is required."});let r=p.models[t];if(!r)throw S({statusCode:404,statusMessage:`Model '${t}' not found.`});return{id:r.id,object:r.object,created:r.created,owned_by:r.owned_by,permission:r.permission,root:r.root,parent:r.parent}}catch(t){throw console.error(`\u83B7\u53D6\u6A21\u578B '${e.context.params?.model}' \u4FE1\u606F\u65F6\u51FA\u9519:`,t),t.statusCode?t:S({statusCode:500,statusMessage:"Failed to retrieve model information."})}}te();U();var H=new me,Ut=process.cwd();_t();H.use("*",xt);H.get("/health",Pt);H.get("/v1/models",qt);H.get("/v1/models/:model",Dt);H.post("/v1/chat/completions",Mt);H.get("/screenshots/**",e=>{let t=e.path.substring(12),r=jt(Ut,"screenshots",t);return Z(e,{getContents:()=>Lt(r),getMeta:async()=>{let s=await Bt(r).catch(()=>{});if(s?.isFile())return{size:s.size,mtime:s.mtimeMs}}})});H.get("/**",e=>{let t=e.path==="/"?"index.html":e.path,r=jt(Ut,"public",t);return Z(e,{getContents:()=>Lt(r),getMeta:async()=>{let s=await Bt(r).catch(()=>{});if(s?.isFile())return{size:s.size,mtime:s.mtimeMs}}})});d("\u{1F527} \u521D\u59CB\u5316\u9875\u9762\u6C60...");ht(5);process.env.NODE_ENV!=="production"&&(d("\u{1F4CA} \u542F\u52A8\u9875\u9762\u6C60\u76D1\u63A7..."),St(1e4));var G=p.server.port,J=p.server.host;Ze(H,{port:G,host:J});d(`\u{1F680} \u670D\u52A1\u5668\u8FD0\u884C\u5728 http://${J}:${G}`);d(`\u{1F3E0} \u7BA1\u7406\u9762\u677F: http://${J}:${G}/`);d(`\u{1F4CB} \u5065\u5EB7\u68C0\u67E5: http://${J}:${G}/health`);d(`\u{1F4AC} \u804A\u5929\u7AEF\u70B9: http://${J}:${G}/v1/chat/completions`);d(`\u{1F3AF} AI Studio URL: ${p.aiStudio.url}`);d(`\u{1F30D} \u73AF\u5883: ${process.env.NODE_ENV||"development"}`);async function Xr(){let e;try{d("\u{1F4F8} \u5F00\u59CB\u83B7\u53D6AI Studio\u9875\u9762\u622A\u56FE..."),e=await se(),d(`\u{1F310} \u667A\u80FD\u5BFC\u822A\u5230: ${p.aiStudio.url}`),await V(e,p.aiStudio.url,{timeout:p.aiStudio.pageTimeout}),await oe(e),await e.waitForTimeout(2e3);let t=await be(e,"./screenshots","aistudio-startup");d(`\u2705 AI Studio\u622A\u56FE\u5DF2\u4FDD\u5B58: ${t}`)}catch(t){I("\u274C \u622A\u56FEAI Studio\u9875\u9762\u65F6\u51FA\u9519:",t.message)}finally{e&&(await z(e),d("\u{1F504} \u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D"))}}setTimeout(()=>{d(`
|
26 |
+
\u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),Et()},1e3);setTimeout(()=>{Xr()},2e3);
|
package-lock.json
CHANGED
@@ -14,7 +14,433 @@
|
|
14 |
"playwright": "^1.53.2"
|
15 |
},
|
16 |
"devDependencies": {
|
17 |
-
"@types/node": "^20.10.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
}
|
19 |
},
|
20 |
"node_modules/@types/node": {
|
@@ -45,6 +471,47 @@
|
|
45 |
"url": "https://dotenvx.com"
|
46 |
}
|
47 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
"node_modules/fetchdts": {
|
49 |
"version": "0.1.5",
|
50 |
"resolved": "https://registry.npmmirror.com/fetchdts/-/fetchdts-0.1.5.tgz",
|
|
|
14 |
"playwright": "^1.53.2"
|
15 |
},
|
16 |
"devDependencies": {
|
17 |
+
"@types/node": "^20.10.0",
|
18 |
+
"esbuild": "^0.25.5"
|
19 |
+
}
|
20 |
+
},
|
21 |
+
"node_modules/@esbuild/aix-ppc64": {
|
22 |
+
"version": "0.25.5",
|
23 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz",
|
24 |
+
"integrity": "sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA==",
|
25 |
+
"cpu": [
|
26 |
+
"ppc64"
|
27 |
+
],
|
28 |
+
"dev": true,
|
29 |
+
"license": "MIT",
|
30 |
+
"optional": true,
|
31 |
+
"os": [
|
32 |
+
"aix"
|
33 |
+
],
|
34 |
+
"engines": {
|
35 |
+
"node": ">=18"
|
36 |
+
}
|
37 |
+
},
|
38 |
+
"node_modules/@esbuild/android-arm": {
|
39 |
+
"version": "0.25.5",
|
40 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.25.5.tgz",
|
41 |
+
"integrity": "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA==",
|
42 |
+
"cpu": [
|
43 |
+
"arm"
|
44 |
+
],
|
45 |
+
"dev": true,
|
46 |
+
"license": "MIT",
|
47 |
+
"optional": true,
|
48 |
+
"os": [
|
49 |
+
"android"
|
50 |
+
],
|
51 |
+
"engines": {
|
52 |
+
"node": ">=18"
|
53 |
+
}
|
54 |
+
},
|
55 |
+
"node_modules/@esbuild/android-arm64": {
|
56 |
+
"version": "0.25.5",
|
57 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.25.5.tgz",
|
58 |
+
"integrity": "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg==",
|
59 |
+
"cpu": [
|
60 |
+
"arm64"
|
61 |
+
],
|
62 |
+
"dev": true,
|
63 |
+
"license": "MIT",
|
64 |
+
"optional": true,
|
65 |
+
"os": [
|
66 |
+
"android"
|
67 |
+
],
|
68 |
+
"engines": {
|
69 |
+
"node": ">=18"
|
70 |
+
}
|
71 |
+
},
|
72 |
+
"node_modules/@esbuild/android-x64": {
|
73 |
+
"version": "0.25.5",
|
74 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.25.5.tgz",
|
75 |
+
"integrity": "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw==",
|
76 |
+
"cpu": [
|
77 |
+
"x64"
|
78 |
+
],
|
79 |
+
"dev": true,
|
80 |
+
"license": "MIT",
|
81 |
+
"optional": true,
|
82 |
+
"os": [
|
83 |
+
"android"
|
84 |
+
],
|
85 |
+
"engines": {
|
86 |
+
"node": ">=18"
|
87 |
+
}
|
88 |
+
},
|
89 |
+
"node_modules/@esbuild/darwin-arm64": {
|
90 |
+
"version": "0.25.5",
|
91 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz",
|
92 |
+
"integrity": "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ==",
|
93 |
+
"cpu": [
|
94 |
+
"arm64"
|
95 |
+
],
|
96 |
+
"dev": true,
|
97 |
+
"license": "MIT",
|
98 |
+
"optional": true,
|
99 |
+
"os": [
|
100 |
+
"darwin"
|
101 |
+
],
|
102 |
+
"engines": {
|
103 |
+
"node": ">=18"
|
104 |
+
}
|
105 |
+
},
|
106 |
+
"node_modules/@esbuild/darwin-x64": {
|
107 |
+
"version": "0.25.5",
|
108 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.25.5.tgz",
|
109 |
+
"integrity": "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ==",
|
110 |
+
"cpu": [
|
111 |
+
"x64"
|
112 |
+
],
|
113 |
+
"dev": true,
|
114 |
+
"license": "MIT",
|
115 |
+
"optional": true,
|
116 |
+
"os": [
|
117 |
+
"darwin"
|
118 |
+
],
|
119 |
+
"engines": {
|
120 |
+
"node": ">=18"
|
121 |
+
}
|
122 |
+
},
|
123 |
+
"node_modules/@esbuild/freebsd-arm64": {
|
124 |
+
"version": "0.25.5",
|
125 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.5.tgz",
|
126 |
+
"integrity": "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw==",
|
127 |
+
"cpu": [
|
128 |
+
"arm64"
|
129 |
+
],
|
130 |
+
"dev": true,
|
131 |
+
"license": "MIT",
|
132 |
+
"optional": true,
|
133 |
+
"os": [
|
134 |
+
"freebsd"
|
135 |
+
],
|
136 |
+
"engines": {
|
137 |
+
"node": ">=18"
|
138 |
+
}
|
139 |
+
},
|
140 |
+
"node_modules/@esbuild/freebsd-x64": {
|
141 |
+
"version": "0.25.5",
|
142 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.25.5.tgz",
|
143 |
+
"integrity": "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw==",
|
144 |
+
"cpu": [
|
145 |
+
"x64"
|
146 |
+
],
|
147 |
+
"dev": true,
|
148 |
+
"license": "MIT",
|
149 |
+
"optional": true,
|
150 |
+
"os": [
|
151 |
+
"freebsd"
|
152 |
+
],
|
153 |
+
"engines": {
|
154 |
+
"node": ">=18"
|
155 |
+
}
|
156 |
+
},
|
157 |
+
"node_modules/@esbuild/linux-arm": {
|
158 |
+
"version": "0.25.5",
|
159 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.25.5.tgz",
|
160 |
+
"integrity": "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw==",
|
161 |
+
"cpu": [
|
162 |
+
"arm"
|
163 |
+
],
|
164 |
+
"dev": true,
|
165 |
+
"license": "MIT",
|
166 |
+
"optional": true,
|
167 |
+
"os": [
|
168 |
+
"linux"
|
169 |
+
],
|
170 |
+
"engines": {
|
171 |
+
"node": ">=18"
|
172 |
+
}
|
173 |
+
},
|
174 |
+
"node_modules/@esbuild/linux-arm64": {
|
175 |
+
"version": "0.25.5",
|
176 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.25.5.tgz",
|
177 |
+
"integrity": "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg==",
|
178 |
+
"cpu": [
|
179 |
+
"arm64"
|
180 |
+
],
|
181 |
+
"dev": true,
|
182 |
+
"license": "MIT",
|
183 |
+
"optional": true,
|
184 |
+
"os": [
|
185 |
+
"linux"
|
186 |
+
],
|
187 |
+
"engines": {
|
188 |
+
"node": ">=18"
|
189 |
+
}
|
190 |
+
},
|
191 |
+
"node_modules/@esbuild/linux-ia32": {
|
192 |
+
"version": "0.25.5",
|
193 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.25.5.tgz",
|
194 |
+
"integrity": "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA==",
|
195 |
+
"cpu": [
|
196 |
+
"ia32"
|
197 |
+
],
|
198 |
+
"dev": true,
|
199 |
+
"license": "MIT",
|
200 |
+
"optional": true,
|
201 |
+
"os": [
|
202 |
+
"linux"
|
203 |
+
],
|
204 |
+
"engines": {
|
205 |
+
"node": ">=18"
|
206 |
+
}
|
207 |
+
},
|
208 |
+
"node_modules/@esbuild/linux-loong64": {
|
209 |
+
"version": "0.25.5",
|
210 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.25.5.tgz",
|
211 |
+
"integrity": "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg==",
|
212 |
+
"cpu": [
|
213 |
+
"loong64"
|
214 |
+
],
|
215 |
+
"dev": true,
|
216 |
+
"license": "MIT",
|
217 |
+
"optional": true,
|
218 |
+
"os": [
|
219 |
+
"linux"
|
220 |
+
],
|
221 |
+
"engines": {
|
222 |
+
"node": ">=18"
|
223 |
+
}
|
224 |
+
},
|
225 |
+
"node_modules/@esbuild/linux-mips64el": {
|
226 |
+
"version": "0.25.5",
|
227 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.25.5.tgz",
|
228 |
+
"integrity": "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg==",
|
229 |
+
"cpu": [
|
230 |
+
"mips64el"
|
231 |
+
],
|
232 |
+
"dev": true,
|
233 |
+
"license": "MIT",
|
234 |
+
"optional": true,
|
235 |
+
"os": [
|
236 |
+
"linux"
|
237 |
+
],
|
238 |
+
"engines": {
|
239 |
+
"node": ">=18"
|
240 |
+
}
|
241 |
+
},
|
242 |
+
"node_modules/@esbuild/linux-ppc64": {
|
243 |
+
"version": "0.25.5",
|
244 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.25.5.tgz",
|
245 |
+
"integrity": "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ==",
|
246 |
+
"cpu": [
|
247 |
+
"ppc64"
|
248 |
+
],
|
249 |
+
"dev": true,
|
250 |
+
"license": "MIT",
|
251 |
+
"optional": true,
|
252 |
+
"os": [
|
253 |
+
"linux"
|
254 |
+
],
|
255 |
+
"engines": {
|
256 |
+
"node": ">=18"
|
257 |
+
}
|
258 |
+
},
|
259 |
+
"node_modules/@esbuild/linux-riscv64": {
|
260 |
+
"version": "0.25.5",
|
261 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.25.5.tgz",
|
262 |
+
"integrity": "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA==",
|
263 |
+
"cpu": [
|
264 |
+
"riscv64"
|
265 |
+
],
|
266 |
+
"dev": true,
|
267 |
+
"license": "MIT",
|
268 |
+
"optional": true,
|
269 |
+
"os": [
|
270 |
+
"linux"
|
271 |
+
],
|
272 |
+
"engines": {
|
273 |
+
"node": ">=18"
|
274 |
+
}
|
275 |
+
},
|
276 |
+
"node_modules/@esbuild/linux-s390x": {
|
277 |
+
"version": "0.25.5",
|
278 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.25.5.tgz",
|
279 |
+
"integrity": "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ==",
|
280 |
+
"cpu": [
|
281 |
+
"s390x"
|
282 |
+
],
|
283 |
+
"dev": true,
|
284 |
+
"license": "MIT",
|
285 |
+
"optional": true,
|
286 |
+
"os": [
|
287 |
+
"linux"
|
288 |
+
],
|
289 |
+
"engines": {
|
290 |
+
"node": ">=18"
|
291 |
+
}
|
292 |
+
},
|
293 |
+
"node_modules/@esbuild/linux-x64": {
|
294 |
+
"version": "0.25.5",
|
295 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz",
|
296 |
+
"integrity": "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw==",
|
297 |
+
"cpu": [
|
298 |
+
"x64"
|
299 |
+
],
|
300 |
+
"dev": true,
|
301 |
+
"license": "MIT",
|
302 |
+
"optional": true,
|
303 |
+
"os": [
|
304 |
+
"linux"
|
305 |
+
],
|
306 |
+
"engines": {
|
307 |
+
"node": ">=18"
|
308 |
+
}
|
309 |
+
},
|
310 |
+
"node_modules/@esbuild/netbsd-arm64": {
|
311 |
+
"version": "0.25.5",
|
312 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.5.tgz",
|
313 |
+
"integrity": "sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw==",
|
314 |
+
"cpu": [
|
315 |
+
"arm64"
|
316 |
+
],
|
317 |
+
"dev": true,
|
318 |
+
"license": "MIT",
|
319 |
+
"optional": true,
|
320 |
+
"os": [
|
321 |
+
"netbsd"
|
322 |
+
],
|
323 |
+
"engines": {
|
324 |
+
"node": ">=18"
|
325 |
+
}
|
326 |
+
},
|
327 |
+
"node_modules/@esbuild/netbsd-x64": {
|
328 |
+
"version": "0.25.5",
|
329 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.25.5.tgz",
|
330 |
+
"integrity": "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ==",
|
331 |
+
"cpu": [
|
332 |
+
"x64"
|
333 |
+
],
|
334 |
+
"dev": true,
|
335 |
+
"license": "MIT",
|
336 |
+
"optional": true,
|
337 |
+
"os": [
|
338 |
+
"netbsd"
|
339 |
+
],
|
340 |
+
"engines": {
|
341 |
+
"node": ">=18"
|
342 |
+
}
|
343 |
+
},
|
344 |
+
"node_modules/@esbuild/openbsd-arm64": {
|
345 |
+
"version": "0.25.5",
|
346 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.5.tgz",
|
347 |
+
"integrity": "sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw==",
|
348 |
+
"cpu": [
|
349 |
+
"arm64"
|
350 |
+
],
|
351 |
+
"dev": true,
|
352 |
+
"license": "MIT",
|
353 |
+
"optional": true,
|
354 |
+
"os": [
|
355 |
+
"openbsd"
|
356 |
+
],
|
357 |
+
"engines": {
|
358 |
+
"node": ">=18"
|
359 |
+
}
|
360 |
+
},
|
361 |
+
"node_modules/@esbuild/openbsd-x64": {
|
362 |
+
"version": "0.25.5",
|
363 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.25.5.tgz",
|
364 |
+
"integrity": "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg==",
|
365 |
+
"cpu": [
|
366 |
+
"x64"
|
367 |
+
],
|
368 |
+
"dev": true,
|
369 |
+
"license": "MIT",
|
370 |
+
"optional": true,
|
371 |
+
"os": [
|
372 |
+
"openbsd"
|
373 |
+
],
|
374 |
+
"engines": {
|
375 |
+
"node": ">=18"
|
376 |
+
}
|
377 |
+
},
|
378 |
+
"node_modules/@esbuild/sunos-x64": {
|
379 |
+
"version": "0.25.5",
|
380 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.25.5.tgz",
|
381 |
+
"integrity": "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA==",
|
382 |
+
"cpu": [
|
383 |
+
"x64"
|
384 |
+
],
|
385 |
+
"dev": true,
|
386 |
+
"license": "MIT",
|
387 |
+
"optional": true,
|
388 |
+
"os": [
|
389 |
+
"sunos"
|
390 |
+
],
|
391 |
+
"engines": {
|
392 |
+
"node": ">=18"
|
393 |
+
}
|
394 |
+
},
|
395 |
+
"node_modules/@esbuild/win32-arm64": {
|
396 |
+
"version": "0.25.5",
|
397 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.25.5.tgz",
|
398 |
+
"integrity": "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw==",
|
399 |
+
"cpu": [
|
400 |
+
"arm64"
|
401 |
+
],
|
402 |
+
"dev": true,
|
403 |
+
"license": "MIT",
|
404 |
+
"optional": true,
|
405 |
+
"os": [
|
406 |
+
"win32"
|
407 |
+
],
|
408 |
+
"engines": {
|
409 |
+
"node": ">=18"
|
410 |
+
}
|
411 |
+
},
|
412 |
+
"node_modules/@esbuild/win32-ia32": {
|
413 |
+
"version": "0.25.5",
|
414 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.25.5.tgz",
|
415 |
+
"integrity": "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ==",
|
416 |
+
"cpu": [
|
417 |
+
"ia32"
|
418 |
+
],
|
419 |
+
"dev": true,
|
420 |
+
"license": "MIT",
|
421 |
+
"optional": true,
|
422 |
+
"os": [
|
423 |
+
"win32"
|
424 |
+
],
|
425 |
+
"engines": {
|
426 |
+
"node": ">=18"
|
427 |
+
}
|
428 |
+
},
|
429 |
+
"node_modules/@esbuild/win32-x64": {
|
430 |
+
"version": "0.25.5",
|
431 |
+
"resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.25.5.tgz",
|
432 |
+
"integrity": "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g==",
|
433 |
+
"cpu": [
|
434 |
+
"x64"
|
435 |
+
],
|
436 |
+
"dev": true,
|
437 |
+
"license": "MIT",
|
438 |
+
"optional": true,
|
439 |
+
"os": [
|
440 |
+
"win32"
|
441 |
+
],
|
442 |
+
"engines": {
|
443 |
+
"node": ">=18"
|
444 |
}
|
445 |
},
|
446 |
"node_modules/@types/node": {
|
|
|
471 |
"url": "https://dotenvx.com"
|
472 |
}
|
473 |
},
|
474 |
+
"node_modules/esbuild": {
|
475 |
+
"version": "0.25.5",
|
476 |
+
"resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.5.tgz",
|
477 |
+
"integrity": "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ==",
|
478 |
+
"dev": true,
|
479 |
+
"hasInstallScript": true,
|
480 |
+
"license": "MIT",
|
481 |
+
"bin": {
|
482 |
+
"esbuild": "bin/esbuild"
|
483 |
+
},
|
484 |
+
"engines": {
|
485 |
+
"node": ">=18"
|
486 |
+
},
|
487 |
+
"optionalDependencies": {
|
488 |
+
"@esbuild/aix-ppc64": "0.25.5",
|
489 |
+
"@esbuild/android-arm": "0.25.5",
|
490 |
+
"@esbuild/android-arm64": "0.25.5",
|
491 |
+
"@esbuild/android-x64": "0.25.5",
|
492 |
+
"@esbuild/darwin-arm64": "0.25.5",
|
493 |
+
"@esbuild/darwin-x64": "0.25.5",
|
494 |
+
"@esbuild/freebsd-arm64": "0.25.5",
|
495 |
+
"@esbuild/freebsd-x64": "0.25.5",
|
496 |
+
"@esbuild/linux-arm": "0.25.5",
|
497 |
+
"@esbuild/linux-arm64": "0.25.5",
|
498 |
+
"@esbuild/linux-ia32": "0.25.5",
|
499 |
+
"@esbuild/linux-loong64": "0.25.5",
|
500 |
+
"@esbuild/linux-mips64el": "0.25.5",
|
501 |
+
"@esbuild/linux-ppc64": "0.25.5",
|
502 |
+
"@esbuild/linux-riscv64": "0.25.5",
|
503 |
+
"@esbuild/linux-s390x": "0.25.5",
|
504 |
+
"@esbuild/linux-x64": "0.25.5",
|
505 |
+
"@esbuild/netbsd-arm64": "0.25.5",
|
506 |
+
"@esbuild/netbsd-x64": "0.25.5",
|
507 |
+
"@esbuild/openbsd-arm64": "0.25.5",
|
508 |
+
"@esbuild/openbsd-x64": "0.25.5",
|
509 |
+
"@esbuild/sunos-x64": "0.25.5",
|
510 |
+
"@esbuild/win32-arm64": "0.25.5",
|
511 |
+
"@esbuild/win32-ia32": "0.25.5",
|
512 |
+
"@esbuild/win32-x64": "0.25.5"
|
513 |
+
}
|
514 |
+
},
|
515 |
"node_modules/fetchdts": {
|
516 |
"version": "0.1.5",
|
517 |
"resolved": "https://registry.npmmirror.com/fetchdts/-/fetchdts-0.1.5.tgz",
|
package.json
CHANGED
@@ -2,12 +2,13 @@
|
|
2 |
"name": "aistudio2api",
|
3 |
"version": "1.0.0",
|
4 |
"description": "Google AI Studio to OpenAI API proxy using H3 and Playwright",
|
5 |
-
"main": "index.js",
|
6 |
"type": "module",
|
7 |
"scripts": {
|
8 |
"login": "node src/login.js",
|
9 |
"dev": "node --watch src/web-server.js",
|
10 |
-
"
|
|
|
11 |
},
|
12 |
"keywords": [
|
13 |
"h3",
|
@@ -24,6 +25,7 @@
|
|
24 |
"playwright": "^1.53.2"
|
25 |
},
|
26 |
"devDependencies": {
|
27 |
-
"@types/node": "^20.10.0"
|
|
|
28 |
}
|
29 |
-
}
|
|
|
2 |
"name": "aistudio2api",
|
3 |
"version": "1.0.0",
|
4 |
"description": "Google AI Studio to OpenAI API proxy using H3 and Playwright",
|
5 |
+
"main": "dist/index.js",
|
6 |
"type": "module",
|
7 |
"scripts": {
|
8 |
"login": "node src/login.js",
|
9 |
"dev": "node --watch src/web-server.js",
|
10 |
+
"build": "esbuild src/web-server.js --bundle --platform=node --outfile=dist/index.js --format=esm --minify --external:playwright",
|
11 |
+
"start": "node dist/index.js"
|
12 |
},
|
13 |
"keywords": [
|
14 |
"h3",
|
|
|
25 |
"playwright": "^1.53.2"
|
26 |
},
|
27 |
"devDependencies": {
|
28 |
+
"@types/node": "^20.10.0",
|
29 |
+
"esbuild": "^0.25.5"
|
30 |
}
|
31 |
+
}
|
src/config.js
DELETED
@@ -1,133 +0,0 @@
|
|
1 |
-
import dotenv from 'dotenv';
|
2 |
-
|
3 |
-
// 加载 .env 文件中的环境变量
|
4 |
-
dotenv.config();
|
5 |
-
|
6 |
-
/**
|
7 |
-
* @typedef {Object} AppConfig
|
8 |
-
* @property {Object} server - 服务器配置
|
9 |
-
* @property {number} server.port - 监听端口
|
10 |
-
* @property {string} server.host - 监听主机
|
11 |
-
* @property {Object} browser - Playwright 浏览器配置
|
12 |
-
* @property {boolean} browser.headless - 是否以无头模式运行
|
13 |
-
* @property {number} browser.timeout - 浏览器操作的全局超时时间
|
14 |
-
* @property {string|undefined} browser.executablePath - Chromium 可执行文件路径
|
15 |
-
* @property {string[]} browser.args - 浏览器启动参数
|
16 |
-
* @property {string} browser.userAgent - 浏览器 User-Agent
|
17 |
-
* @property {string} cookieFile - Cookie 存储文件路径
|
18 |
-
* @property {string|undefined} cookiesFromEnv - 从环境变量读取的 Cookie 字符串
|
19 |
-
* @property {string} screenshotDir - 截图保存目录
|
20 |
-
* @property {Object} aiStudio - AI Studio 相关配置
|
21 |
-
* @property {string} aiStudio.url - AI Studio 的目标 URL
|
22 |
-
* @property {number} aiStudio.responseTimeout - 等待 AI 响应的超时时间
|
23 |
-
* @property {number} aiStudio.pageTimeout - 页面加载的超时时间
|
24 |
-
* @property {Object} api - API 相关配置
|
25 |
-
* @property {string} api.defaultModel - 默认使用的模型 ID
|
26 |
-
* @property {number} api.maxTokens - 支持的最大令牌数 (此为示例,实际限制在网页端)
|
27 |
-
* @property {number} api.temperature - 默认温度
|
28 |
-
* @property {string|undefined} api.token - API 访问令牌
|
29 |
-
* @property {Object.<string, Object>} models - 支持的模型列表
|
30 |
-
* @property {Object} debug - 调试配置
|
31 |
-
* @property {boolean} debug.logRequests - 是否记录请求体
|
32 |
-
* @property {boolean} debug.logResponses - 是否记录响应体
|
33 |
-
* @property {boolean} debug.saveScreenshots - 是否在出错时保存截图
|
34 |
-
*/
|
35 |
-
|
36 |
-
/** @type {AppConfig} */
|
37 |
-
const config = {
|
38 |
-
// 服务器配置
|
39 |
-
server: {
|
40 |
-
port: parseInt(process.env.PORT || '3096', 10),
|
41 |
-
host: process.env.HOST || 'localhost'
|
42 |
-
},
|
43 |
-
|
44 |
-
// Playwright 浏览器配置
|
45 |
-
browser: {
|
46 |
-
headless: (process.env.HEADLESS || 'true').toLowerCase() !== 'false',
|
47 |
-
timeout: parseInt(process.env.TIMEOUT || '30000', 10),
|
48 |
-
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
49 |
-
args: [
|
50 |
-
'--disable-blink-features=AutomationControlled', // 防止被检测为自动化工具
|
51 |
-
'--no-sandbox',
|
52 |
-
'--disable-dev-shm-usage',
|
53 |
-
'--disable-infobars',
|
54 |
-
'--disable-extensions',
|
55 |
-
],
|
56 |
-
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
|
57 |
-
},
|
58 |
-
|
59 |
-
// Cookie 配置
|
60 |
-
cookieFile: './cookies.json',
|
61 |
-
cookiesFromEnv: process.env.COOKIES,
|
62 |
-
|
63 |
-
// 截图目录
|
64 |
-
screenshotDir: './screenshots',
|
65 |
-
|
66 |
-
// Google AI Studio 配置
|
67 |
-
aiStudio: {
|
68 |
-
url: process.env.AI_STUDIO_URL || 'https://aistudio.google.com/prompts/new_chat',
|
69 |
-
responseTimeout: parseInt(process.env.RESPONSE_TIMEOUT || '600000', 10), // 10分钟
|
70 |
-
pageTimeout: parseInt(process.env.PAGE_TIMEOUT || '30000', 10) // 30秒
|
71 |
-
},
|
72 |
-
|
73 |
-
// API 兼容层配置
|
74 |
-
api: {
|
75 |
-
defaultModel: process.env.DEFAULT_MODEL || 'gemini-pro',
|
76 |
-
maxTokens: 65536, // 理论值,实际由网页决定
|
77 |
-
temperature: 1,
|
78 |
-
token: process.env.API_TOKEN
|
79 |
-
},
|
80 |
-
|
81 |
-
// 可用模型列表 (遵循 OpenAI API 格式)
|
82 |
-
models: {
|
83 |
-
'gemini-2.5-pro': {
|
84 |
-
displayName: 'Gemini 2.5 Pro',
|
85 |
-
id: 'gemini-2.5-pro',
|
86 |
-
object: 'model',
|
87 |
-
created: 1704067200, // 2024-01-01
|
88 |
-
owned_by: 'google',
|
89 |
-
permission: [],
|
90 |
-
root: 'gemini-2.5-pro',
|
91 |
-
parent: null
|
92 |
-
},
|
93 |
-
'gemini-2.5-flash': {
|
94 |
-
displayName: 'Gemini 2.5 Flash',
|
95 |
-
id: 'gemini-2.5-flash',
|
96 |
-
object: 'model',
|
97 |
-
created: 1704067200,
|
98 |
-
owned_by: 'google',
|
99 |
-
permission: [],
|
100 |
-
root: 'gemini-2.5-flash',
|
101 |
-
parent: null
|
102 |
-
},
|
103 |
-
'gemini-pro': {
|
104 |
-
displayName: 'Gemini Pro',
|
105 |
-
id: 'gemini-pro',
|
106 |
-
object: 'model',
|
107 |
-
created: 1701388800, // 2023-12-01
|
108 |
-
owned_by: 'google',
|
109 |
-
permission: [],
|
110 |
-
root: 'gemini-pro',
|
111 |
-
parent: null
|
112 |
-
},
|
113 |
-
'gemini-flash': {
|
114 |
-
displayName: 'Gemini Flash',
|
115 |
-
id: 'gemini-flash',
|
116 |
-
object: 'model',
|
117 |
-
created: 1701388800,
|
118 |
-
owned_by: 'google',
|
119 |
-
permission: [],
|
120 |
-
root: 'gemini-flash',
|
121 |
-
parent: null
|
122 |
-
}
|
123 |
-
},
|
124 |
-
|
125 |
-
// 调试选项
|
126 |
-
debug: {
|
127 |
-
logRequests: process.env.DEBUG_REQUESTS === 'true',
|
128 |
-
logResponses: process.env.DEBUG_RESPONSES === 'true',
|
129 |
-
saveScreenshots: process.env.SAVE_SCREENSHOTS === 'true'
|
130 |
-
}
|
131 |
-
};
|
132 |
-
|
133 |
-
export default config;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/login.js
DELETED
@@ -1,86 +0,0 @@
|
|
1 |
-
import { chromium } from 'playwright';
|
2 |
-
import fs from 'fs';
|
3 |
-
import path from 'path';
|
4 |
-
import { fileURLToPath } from 'url';
|
5 |
-
import config from './config.js';
|
6 |
-
import { loadCookies, waitForUserInput } from './utils/common-utils.js';
|
7 |
-
import { info, error } from './utils/logger.js';
|
8 |
-
import { handleWelcomeModal } from './utils/browser.js';
|
9 |
-
|
10 |
-
/**
|
11 |
-
* 启动一个非无头浏览器,引导用户手动登录 Google AI Studio 并保存 Cookie。
|
12 |
-
*/
|
13 |
-
async function login() {
|
14 |
-
info('启动浏览器以进行手动登录...');
|
15 |
-
const browser = await chromium.launch({
|
16 |
-
headless: false, // 必须为 false 以便用户交互
|
17 |
-
timeout: config.browser.timeout,
|
18 |
-
args: config.browser.args
|
19 |
-
});
|
20 |
-
|
21 |
-
const context = await browser.newContext({
|
22 |
-
userAgent: config.browser.userAgent
|
23 |
-
});
|
24 |
-
|
25 |
-
// 尝试加载现有 Cookie
|
26 |
-
const existingCookies = loadCookies(config.cookieFile, config.cookiesFromEnv);
|
27 |
-
if (existingCookies.length > 0) {
|
28 |
-
await context.addCookies(existingCookies);
|
29 |
-
info(`已加载 ${existingCookies.length} 个现有 Cookie。`);
|
30 |
-
}
|
31 |
-
|
32 |
-
const page = await context.newPage();
|
33 |
-
|
34 |
-
try {
|
35 |
-
info(`导航至 Google AI Studio: ${config.aiStudio.url}`);
|
36 |
-
await page.goto(config.aiStudio.url, { waitUntil: 'networkidle' });
|
37 |
-
await page.waitForTimeout(3000); // 等待页面稳定
|
38 |
-
|
39 |
-
// 尝试处理可能出现的欢迎弹窗
|
40 |
-
await handleWelcomeModal(page);
|
41 |
-
|
42 |
-
info('当前页面 URL:', page.url());
|
43 |
-
info('页面标题:', await page.title());
|
44 |
-
|
45 |
-
info('请在浏览器窗口中完成登录操作。');
|
46 |
-
info('登录成功并跳转到 AI Studio 主界面后,请返回此处按 Enter 键继续...');
|
47 |
-
await waitForUserInput();
|
48 |
-
|
49 |
-
info('用户确认登录完成,正在保存 Cookie...');
|
50 |
-
|
51 |
-
// 再次导航以确保在正确的页面上
|
52 |
-
try {
|
53 |
-
await page.goto(config.aiStudio.url, { waitUntil: 'load', timeout: 15000 });
|
54 |
-
await page.waitForTimeout(5000); // 等待页面完全加载
|
55 |
-
} catch (err) {
|
56 |
-
info('导航到主页时出现小问题,但这通常不影响 Cookie 保存。');
|
57 |
-
}
|
58 |
-
|
59 |
-
const newCookies = await context.cookies();
|
60 |
-
if (newCookies.length > 0) {
|
61 |
-
fs.writeFileSync(config.cookieFile, JSON.stringify(newCookies, null, 2));
|
62 |
-
info(`成功将 ${newCookies.length} 个 Cookie 保存到 ${config.cookieFile}`);
|
63 |
-
info('主要 Cookie 名称:');
|
64 |
-
newCookies.slice(0, 5).forEach(cookie => {
|
65 |
-
info(` - ${cookie.name} (域: ${cookie.domain})`);
|
66 |
-
});
|
67 |
-
} else {
|
68 |
-
error('未能获取到任何 Cookie,请确保已成功登录。');
|
69 |
-
}
|
70 |
-
|
71 |
-
} catch (err) {
|
72 |
-
error('登录过程中发生严重错误:', err);
|
73 |
-
} finally {
|
74 |
-
info('关闭浏览器。');
|
75 |
-
await browser.close();
|
76 |
-
}
|
77 |
-
}
|
78 |
-
|
79 |
-
// 使该文件可以直接通过 `node login.js` 运行
|
80 |
-
const __filename = fileURLToPath(import.meta.url);
|
81 |
-
const scriptPath = path.resolve(process.argv[1]);
|
82 |
-
if (path.resolve(__filename) === scriptPath) {
|
83 |
-
login().catch(err => error('执行登录脚本失败:', err));
|
84 |
-
}
|
85 |
-
|
86 |
-
export default login;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/middlewares/auth.js
DELETED
@@ -1,44 +0,0 @@
|
|
1 |
-
import { createError } from 'h3';
|
2 |
-
import config from '../config.js';
|
3 |
-
|
4 |
-
/**
|
5 |
-
* API Token 认证中间件。
|
6 |
-
* 验证请求头中的 `Authorization: Bearer <token>` 是否与配置的 API_TOKEN 匹配。
|
7 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
8 |
-
* @throws {Error} 如果认证失败,则抛出 H3 错误。
|
9 |
-
*/
|
10 |
-
export function apiTokenAuth(event) {
|
11 |
-
// 如果未配置 API_TOKEN,则跳过认证
|
12 |
-
if (!config.api.token) {
|
13 |
-
// 在开发环境中,这可能是预期的行为,但在生产中应发出警告
|
14 |
-
if (process.env.NODE_ENV === 'production') {
|
15 |
-
console.warn('警告: API_TOKEN 未在生产环境中配置,API 对外开放!');
|
16 |
-
}
|
17 |
-
return;
|
18 |
-
}
|
19 |
-
|
20 |
-
const authHeader = event.node.req.headers.authorization;
|
21 |
-
|
22 |
-
if (!authHeader) {
|
23 |
-
throw createError({
|
24 |
-
statusCode: 401,
|
25 |
-
statusMessage: 'Unauthorized: Missing Authorization header.'
|
26 |
-
});
|
27 |
-
}
|
28 |
-
|
29 |
-
const [authType, token] = authHeader.split(' ');
|
30 |
-
|
31 |
-
if (authType !== 'Bearer' || !token) {
|
32 |
-
throw createError({
|
33 |
-
statusCode: 401,
|
34 |
-
statusMessage: 'Unauthorized: Invalid Authorization header format. Expected: Bearer <token>.'
|
35 |
-
});
|
36 |
-
}
|
37 |
-
|
38 |
-
if (token !== config.api.token) {
|
39 |
-
throw createError({
|
40 |
-
statusCode: 401,
|
41 |
-
statusMessage: 'Unauthorized: Invalid API token.'
|
42 |
-
});
|
43 |
-
}
|
44 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/middlewares/cors.js
DELETED
@@ -1,41 +0,0 @@
|
|
1 |
-
/**
|
2 |
-
* CORS (跨域资源共享) 中间件。
|
3 |
-
* 为所有请求设置通用的 CORS 响应头。
|
4 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
5 |
-
* @returns {Response|void} 如果是 OPTIONS 请求,则返回一个 204 响应。
|
6 |
-
*/
|
7 |
-
export function corsMiddleware(event) {
|
8 |
-
const headers = event.node.res.getHeaders();
|
9 |
-
|
10 |
-
if (!headers['access-control-allow-origin']) {
|
11 |
-
event.node.res.setHeader('Access-Control-Allow-Origin', process.env.CORS_ORIGIN || '*');
|
12 |
-
}
|
13 |
-
if (!headers['access-control-allow-methods']) {
|
14 |
-
event.node.res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
15 |
-
}
|
16 |
-
if (!headers['access-control-allow-headers']) {
|
17 |
-
event.node.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
18 |
-
}
|
19 |
-
if (!headers['access-control-max-age']) {
|
20 |
-
event.node.res.setHeader('Access-Control-Max-Age', '86400'); // 24 hours
|
21 |
-
}
|
22 |
-
|
23 |
-
// 处理预检请求 (OPTIONS)
|
24 |
-
if (event.node.req.method === 'OPTIONS') {
|
25 |
-
event.node.res.statusCode = 204;
|
26 |
-
return event.node.res.end();
|
27 |
-
}
|
28 |
-
}
|
29 |
-
|
30 |
-
/**
|
31 |
-
* 为流式响应 (Server-Sent Events) 设置特定的响应头。
|
32 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
33 |
-
*/
|
34 |
-
export function setStreamHeaders(event) {
|
35 |
-
event.node.res.setHeader('Content-Type', 'text/event-stream');
|
36 |
-
event.node.res.setHeader('Cache-Control', 'no-cache');
|
37 |
-
event.node.res.setHeader('Connection', 'keep-alive');
|
38 |
-
// CORS 头也需要为流式响应设置
|
39 |
-
event.node.res.setHeader('Access-Control-Allow-Origin', process.env.CORS_ORIGIN || '*');
|
40 |
-
event.node.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
41 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/chat-completions.js
DELETED
@@ -1,53 +0,0 @@
|
|
1 |
-
import { readBody, createError } from 'h3';
|
2 |
-
import { validateChatCompletionRequest } from '../utils/validation.js';
|
3 |
-
import { setStreamHeaders } from '../middlewares/cors.js';
|
4 |
-
import { apiTokenAuth } from '../middlewares/auth.js';
|
5 |
-
import { processAIStudioRequest, processAIStudioRequestSync } from '../utils/ai-studio-processor.js';
|
6 |
-
|
7 |
-
/**
|
8 |
-
* 处理 `/v1/chat/completions` 的 POST 请求。
|
9 |
-
* 支持流式和非流式响应。
|
10 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
11 |
-
* @returns {Promise<object|ReadableStream>} OpenAI 格式的响应对象或 SSE 流。
|
12 |
-
*/
|
13 |
-
export async function chatCompletionsHandler(event) {
|
14 |
-
try {
|
15 |
-
// 1. 认证
|
16 |
-
apiTokenAuth(event);
|
17 |
-
|
18 |
-
// 2. 读取和验证请求体
|
19 |
-
const body = await readBody(event);
|
20 |
-
const { prompt, stream, model, temperature } = validateChatCompletionRequest(body);
|
21 |
-
|
22 |
-
// 3. 根据 stream 参数决定处理方式
|
23 |
-
if (stream) {
|
24 |
-
// 流式响应
|
25 |
-
setStreamHeaders(event);
|
26 |
-
|
27 |
-
const stream = new ReadableStream({
|
28 |
-
start(controller) {
|
29 |
-
// 将请求处理委托给 AI Studio 处理器
|
30 |
-
processAIStudioRequest(prompt, controller, { model, temperature });
|
31 |
-
}
|
32 |
-
});
|
33 |
-
|
34 |
-
return stream;
|
35 |
-
|
36 |
-
} else {
|
37 |
-
// 非流式响应
|
38 |
-
const result = await processAIStudioRequestSync(prompt, { model, temperature });
|
39 |
-
return result;
|
40 |
-
}
|
41 |
-
|
42 |
-
} catch (error) {
|
43 |
-
console.error('处理聊天请求时出错:', error);
|
44 |
-
// 重新抛出 H3 错误或将标准错误包装成 H3 错误
|
45 |
-
if (error.statusCode) {
|
46 |
-
throw error;
|
47 |
-
}
|
48 |
-
throw createError({
|
49 |
-
statusCode: 500,
|
50 |
-
statusMessage: error.message || 'An internal server error occurred.'
|
51 |
-
});
|
52 |
-
}
|
53 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/health.js
DELETED
@@ -1,23 +0,0 @@
|
|
1 |
-
import { getPagePoolStatus } from '../utils/browser.js';
|
2 |
-
|
3 |
-
/**
|
4 |
-
* 处理 `/health` 的 GET 请求,提供服务健康状态。
|
5 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
6 |
-
* @returns {object} 包含服务状态和页面池信息的健康报告。
|
7 |
-
*/
|
8 |
-
export function healthHandler(event) {
|
9 |
-
const pagePoolStatus = getPagePoolStatus();
|
10 |
-
const utilization = pagePoolStatus.total > 0
|
11 |
-
? Math.round((pagePoolStatus.busy / pagePoolStatus.total) * 100)
|
12 |
-
: 0;
|
13 |
-
|
14 |
-
return {
|
15 |
-
status: 'ok',
|
16 |
-
timestamp: new Date().toISOString(),
|
17 |
-
version: process.env.npm_package_version || '1.0.0',
|
18 |
-
pagePool: {
|
19 |
-
...pagePoolStatus,
|
20 |
-
utilization: `${utilization}%`
|
21 |
-
}
|
22 |
-
};
|
23 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/models.js
DELETED
@@ -1,75 +0,0 @@
|
|
1 |
-
import { createError } from 'h3';
|
2 |
-
import config from '../config.js';
|
3 |
-
|
4 |
-
/**
|
5 |
-
* 处理 `/v1/models` 的 GET 请求,返回所有可用模型的列表。
|
6 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
7 |
-
* @returns {Promise<object>} OpenAI 格式的模型列表响应。
|
8 |
-
*/
|
9 |
-
export async function modelsHandler(event) {
|
10 |
-
try {
|
11 |
-
const models = Object.values(config.models).map(model => ({
|
12 |
-
id: model.id,
|
13 |
-
object: model.object,
|
14 |
-
created: model.created,
|
15 |
-
owned_by: model.owned_by,
|
16 |
-
permission: model.permission,
|
17 |
-
root: model.root,
|
18 |
-
parent: model.parent
|
19 |
-
}));
|
20 |
-
|
21 |
-
// 按创建时间降序排序
|
22 |
-
models.sort((a, b) => b.created - a.created);
|
23 |
-
|
24 |
-
return {
|
25 |
-
object: 'list',
|
26 |
-
data: models
|
27 |
-
};
|
28 |
-
} catch (error) {
|
29 |
-
console.error('获取模型列表时出错:', error);
|
30 |
-
throw createError({
|
31 |
-
statusCode: 500,
|
32 |
-
statusMessage: 'Failed to retrieve models list.'
|
33 |
-
});
|
34 |
-
}
|
35 |
-
}
|
36 |
-
|
37 |
-
/**
|
38 |
-
* 处理 `/v1/models/:model` 的 GET 请求,返回单个模型的详细信息。
|
39 |
-
* @param {import('h3').H3Event} event - H3 事件对象。
|
40 |
-
* @returns {Promise<object>} OpenAI 格式的单个模型信息。
|
41 |
-
*/
|
42 |
-
export async function modelHandler(event) {
|
43 |
-
try {
|
44 |
-
const modelId = event.context.params?.model;
|
45 |
-
|
46 |
-
if (!modelId) {
|
47 |
-
throw createError({ statusCode: 400, statusMessage: 'Model ID is required.' });
|
48 |
-
}
|
49 |
-
|
50 |
-
const model = config.models[modelId];
|
51 |
-
|
52 |
-
if (!model) {
|
53 |
-
throw createError({ statusCode: 404, statusMessage: `Model '${modelId}' not found.` });
|
54 |
-
}
|
55 |
-
|
56 |
-
return {
|
57 |
-
id: model.id,
|
58 |
-
object: model.object,
|
59 |
-
created: model.created,
|
60 |
-
owned_by: model.owned_by,
|
61 |
-
permission: model.permission,
|
62 |
-
root: model.root,
|
63 |
-
parent: model.parent
|
64 |
-
};
|
65 |
-
} catch (error) {
|
66 |
-
console.error(`获取模型 '${event.context.params?.model}' 信息时出错:`, error);
|
67 |
-
if (error.statusCode) {
|
68 |
-
throw error;
|
69 |
-
}
|
70 |
-
throw createError({
|
71 |
-
statusCode: 500,
|
72 |
-
statusMessage: 'Failed to retrieve model information.'
|
73 |
-
});
|
74 |
-
}
|
75 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/ai-studio-injector.js
DELETED
@@ -1,266 +0,0 @@
|
|
1 |
-
import { handleWelcomeModal, simulateHumanRandomClicks, simulateHumanBehavior } from './browser.js';
|
2 |
-
import config from '../config.js';
|
3 |
-
/**
|
4 |
-
* 封装了与 Google AI Studio 页面交互的所有操作,
|
5 |
-
* 如输入文本、点击按钮、设置模型和温度等。
|
6 |
-
*/
|
7 |
-
export class AIStudioInjector {
|
8 |
-
/**
|
9 |
-
* @param {import('playwright').Page} page Playwright 页面对象
|
10 |
-
* @param {object} [options={}] 配置选项
|
11 |
-
* @param {boolean} [options.enableHumanSimulation=true] 是否启用人类行为模拟
|
12 |
-
*/
|
13 |
-
constructor(page, options = {}) {
|
14 |
-
this.page = page;
|
15 |
-
this.options = {
|
16 |
-
enableHumanSimulation: true,
|
17 |
-
...options
|
18 |
-
};
|
19 |
-
this.modelMapping = Object.fromEntries(
|
20 |
-
Object.entries(config.models).map(([key, model]) => [key, model.displayName])
|
21 |
-
);
|
22 |
-
}
|
23 |
-
/**
|
24 |
-
* 等待页面主要内容加载完成并处理欢迎弹窗。
|
25 |
-
* @returns {Promise<boolean>} 是否加载成功。
|
26 |
-
*/
|
27 |
-
async waitForPageLoad() {
|
28 |
-
try {
|
29 |
-
await this.page.waitForSelector('body', { timeout: 15000 });
|
30 |
-
await handleWelcomeModal(this.page);
|
31 |
-
return true;
|
32 |
-
} catch (error) {
|
33 |
-
console.error('页面加载超时或失败:', error);
|
34 |
-
return false;
|
35 |
-
}
|
36 |
-
}
|
37 |
-
/**
|
38 |
-
* 查找页面上的主输入框。
|
39 |
-
* 增强了选择器和等待逻辑,以提高在动态加载页面上的成功率。
|
40 |
-
* @returns {Promise<import('playwright').Locator|null>} 输入框的定位器。
|
41 |
-
*/
|
42 |
-
async findInputElement() {
|
43 |
-
// 首先,等待一个稳定的父容器出现,这表明输入区域已开始渲染。
|
44 |
-
// 这可以大大减少因时序问题导致的查找失败。
|
45 |
-
try {
|
46 |
-
await this.page.waitForSelector('footer ms-prompt-input-wrapper', { timeout: 10000 });
|
47 |
-
console.log('输入框的父容器已加载。');
|
48 |
-
} catch (error) {
|
49 |
-
console.warn('等待输入框父容器超时,将继续尝试查找...');
|
50 |
-
}
|
51 |
-
|
52 |
-
// 定义一组从最具体到最通用的选择器
|
53 |
-
const selectors = [
|
54 |
-
// --- 新增的、更具体的选择器 (基于您提供的HTML) ---
|
55 |
-
'ms-prompt-input-wrapper textarea[aria-label*="prompt"]', // 结合自定义组件和aria-label
|
56 |
-
'textarea[placeholder="Start typing a prompt"]', // 精确匹配placeholder
|
57 |
-
'textarea[aria-label="Start typing a prompt"]', // 精确匹配aria-label
|
58 |
-
'footer textarea', // 任何在footer里的textarea
|
59 |
-
// --- 原有的选择器作为后备 ---
|
60 |
-
'textarea[placeholder*="prompt"]',
|
61 |
-
'textarea[aria-label*="prompt"]',
|
62 |
-
'div[contenteditable="true"]', // 某些情况下可能是div
|
63 |
-
'textarea', // 最通用的后备
|
64 |
-
];
|
65 |
-
|
66 |
-
for (const selector of selectors) {
|
67 |
-
try {
|
68 |
-
const locator = this.page.locator(selector);
|
69 |
-
const count = await locator.count();
|
70 |
-
|
71 |
-
if (count > 0) {
|
72 |
-
console.log(`选择器 "${selector}" 找到了 ${count} 个元素。正在检查可见性和可用性...`);
|
73 |
-
// 遍历找到的元素,返回第一个可见且可用的
|
74 |
-
for (let i = 0; i < count; i++) {
|
75 |
-
const element = locator.nth(i);
|
76 |
-
if (await element.isVisible() && await element.isEnabled()) {
|
77 |
-
console.log(`成功找到可用输入框: ${selector} (索引 ${i})`);
|
78 |
-
return element;
|
79 |
-
}
|
80 |
-
}
|
81 |
-
console.log(`选择器 "${selector}" 找到的元素均不可见或不可用。`);
|
82 |
-
}
|
83 |
-
} catch (error) {
|
84 |
-
// 忽略单个选择器的错误,继续尝试下一个
|
85 |
-
console.warn(`使用选择器 "${selector}" 查找时出错: ${error.message}`);
|
86 |
-
}
|
87 |
-
}
|
88 |
-
|
89 |
-
console.error('关键错误: 尝试了所有选择器后,仍未找到任何可用的输入元素。');
|
90 |
-
// 在失败时保存截图以供调试
|
91 |
-
if (config.debug.saveScreenshots) {
|
92 |
-
const { saveScreenshot } = await import('./common-utils.js');
|
93 |
-
await saveScreenshot(this.page, config.screenshotDir, 'find-input-failed');
|
94 |
-
}
|
95 |
-
return null;
|
96 |
-
}
|
97 |
-
/**
|
98 |
-
* 查找页面上的发送/运行按钮。
|
99 |
-
* @returns {Promise<import('playwright').Locator|null>} 按钮的定位器。
|
100 |
-
*/
|
101 |
-
async findSendButton() {
|
102 |
-
const selectors = [
|
103 |
-
'button[aria-label="Run"]',
|
104 |
-
'button.run-button',
|
105 |
-
'button[aria-label*="Send"]',
|
106 |
-
'button[data-testid*="send"]',
|
107 |
-
];
|
108 |
-
for (const selector of selectors) {
|
109 |
-
const locator = this.page.locator(selector);
|
110 |
-
if (await locator.count() > 0) {
|
111 |
-
const button = locator.first();
|
112 |
-
const isDisabled = await button.isDisabled();
|
113 |
-
if (!isDisabled) return button;
|
114 |
-
}
|
115 |
-
}
|
116 |
-
console.error('未找到任何可用的发送按钮。');
|
117 |
-
return null;
|
118 |
-
}
|
119 |
-
/**
|
120 |
-
* 在输入框中填入消息。
|
121 |
-
* @param {string} message 要发送的消息。
|
122 |
-
* @returns {Promise<boolean>} 是否填充成功。
|
123 |
-
*/
|
124 |
-
async fillMessage(message) {
|
125 |
-
const inputElement = await this.findInputElement();
|
126 |
-
if (!inputElement) throw new Error('无法找到输入框。');
|
127 |
-
try {
|
128 |
-
if (this.options.enableHumanSimulation) {
|
129 |
-
await simulateHumanRandomClicks(this.page, { referenceElement: inputElement });
|
130 |
-
}
|
131 |
-
await inputElement.fill(message);
|
132 |
-
await this.page.waitForTimeout(200); // 等待UI响应
|
133 |
-
console.log('消息填充完成。');
|
134 |
-
return true;
|
135 |
-
} catch (error) {
|
136 |
-
console.error('填充消息失败:', error);
|
137 |
-
return false;
|
138 |
-
}
|
139 |
-
}
|
140 |
-
/**
|
141 |
-
* 等待发送按钮变为可用状态。
|
142 |
-
* @param {number} [timeout=10000] 超时时间。
|
143 |
-
* @returns {Promise<boolean>} 按钮是否变为可用。
|
144 |
-
*/
|
145 |
-
async waitForSendButtonEnabled(timeout = 10000) {
|
146 |
-
try {
|
147 |
-
const sendButtonLocator = this.page.locator('button[aria-label="Run"]:not([disabled]), button.run-button:not([disabled])');
|
148 |
-
await sendButtonLocator.waitFor({ state: 'visible', timeout });
|
149 |
-
console.log('发送按钮已可用。');
|
150 |
-
return true;
|
151 |
-
} catch (error) {
|
152 |
-
console.warn('等待发送按钮可用超时,将继续尝试。');
|
153 |
-
return false;
|
154 |
-
}
|
155 |
-
}
|
156 |
-
/**
|
157 |
-
* 点击发送按钮发送消息。
|
158 |
-
* @returns {Promise<boolean>} 是否发送成功。
|
159 |
-
*/
|
160 |
-
async sendMessage() {
|
161 |
-
if (this.options.enableHumanSimulation) {
|
162 |
-
await simulateHumanBehavior(this.page, { includeScrolling: false, duration: 1500 });
|
163 |
-
}
|
164 |
-
const sendButton = await this.findSendButton();
|
165 |
-
if (!sendButton) throw new Error('无法找到可用的发送按钮。');
|
166 |
-
try {
|
167 |
-
await sendButton.click();
|
168 |
-
console.log('消息已发送。');
|
169 |
-
return true;
|
170 |
-
} catch (error) {
|
171 |
-
console.error('点击发送按钮失败:', error);
|
172 |
-
try {
|
173 |
-
console.log('尝试使用键盘快捷键 (Ctrl+Enter) 发送...');
|
174 |
-
await this.page.keyboard.press('Control+Enter');
|
175 |
-
console.log('已使用键盘快捷键发送。');
|
176 |
-
return true;
|
177 |
-
} catch (keyboardError) {
|
178 |
-
console.error('键盘快捷键发送也失败:', keyboardError);
|
179 |
-
return false;
|
180 |
-
}
|
181 |
-
}
|
182 |
-
}
|
183 |
-
/**
|
184 |
-
* 设置 AI 模型。
|
185 |
-
* @param {string} modelName 模型 ID (例如 'gemini-pro')。
|
186 |
-
* @returns {Promise<boolean>} 是否设置成功。
|
187 |
-
*/
|
188 |
-
async setModel(modelName) {
|
189 |
-
try {
|
190 |
-
const targetDisplayName = this.modelMapping[modelName] || modelName;
|
191 |
-
const modelSelectorContainerLocator = this.page.locator('ms-model-selector-two-column');
|
192 |
-
if (await modelSelectorContainerLocator.count() === 0) {
|
193 |
-
console.log('未找到模型选择器,跳过模型设置。');
|
194 |
-
return false;
|
195 |
-
}
|
196 |
-
const currentModelText = await modelSelectorContainerLocator.locator('.model-option-content .gmat-body-medium').textContent();
|
197 |
-
if (currentModelText?.trim() === targetDisplayName) {
|
198 |
-
console.log('当前已是目标模型,无需切换。');
|
199 |
-
return true;
|
200 |
-
}
|
201 |
-
await modelSelectorContainerLocator.click({ timeout: 5000 });
|
202 |
-
const dropdownPanelLocator = this.page.locator('.mat-mdc-select-panel');
|
203 |
-
await dropdownPanelLocator.waitFor({ state: 'visible', timeout: 5000 });
|
204 |
-
const targetOption = dropdownPanelLocator.locator('mat-option.model-option', { hasText: targetDisplayName });
|
205 |
-
if (await targetOption.count() > 0) {
|
206 |
-
await targetOption.first().click({ timeout: 5000 });
|
207 |
-
await this.page.waitForTimeout(1000); // 等待选择生效
|
208 |
-
console.log(`模型已成功设置为: ${targetDisplayName}`);
|
209 |
-
return true;
|
210 |
-
} else {
|
211 |
-
console.log(`未在下拉菜单中找到目标模型: ${targetDisplayName}`);
|
212 |
-
await this.page.keyboard.press('Escape'); // 关闭下拉菜单
|
213 |
-
return false;
|
214 |
-
}
|
215 |
-
} catch (error) {
|
216 |
-
console.error('设置模型时发生错误:', error);
|
217 |
-
try { await this.page.keyboard.press('Escape'); } catch (e) {}
|
218 |
-
return false;
|
219 |
-
}
|
220 |
-
}
|
221 |
-
/**
|
222 |
-
* 设置温度参数。
|
223 |
-
* @param {number} temperature 温度值。
|
224 |
-
* @returns {Promise<boolean>} 是否设置成功。
|
225 |
-
*/
|
226 |
-
async setTemperature(temperature) {
|
227 |
-
try {
|
228 |
-
const temperatureContainerLocator = this.page.locator('[data-test-id="temperatureSliderContainer"]');
|
229 |
-
if (await temperatureContainerLocator.count() === 0) {
|
230 |
-
console.log('未找到温度设置容器,跳过。');
|
231 |
-
return false;
|
232 |
-
}
|
233 |
-
const numberInput = temperatureContainerLocator.locator('input[type="number"]');
|
234 |
-
if (await numberInput.count() > 0) {
|
235 |
-
await numberInput.fill(temperature.toString());
|
236 |
-
await numberInput.dispatchEvent('change');
|
237 |
-
console.log(`温度已设置为: ${temperature}`);
|
238 |
-
return true;
|
239 |
-
}
|
240 |
-
console.log('未找到温度数字输入框,跳过设置。');
|
241 |
-
return false;
|
242 |
-
} catch (error) {
|
243 |
-
console.error('设置温度时出错:', error);
|
244 |
-
return false;
|
245 |
-
}
|
246 |
-
}
|
247 |
-
/**
|
248 |
-
* 完整处理流程:加载页面、设置参数、填写并发送消息。
|
249 |
-
* @param {string} message 要发送的消息。
|
250 |
-
* @param {object} [options={}] 请求选项。
|
251 |
-
* @param {string} [options.model] 模型 ID。
|
252 |
-
* @param {number} [options.temperature] 温度值。
|
253 |
-
* @returns {Promise<boolean>} 整个流程是否成功。
|
254 |
-
*/
|
255 |
-
async processMessage(message, options = {}) {
|
256 |
-
console.log('开始处理消息...');
|
257 |
-
if (!await this.waitForPageLoad()) throw new Error('页面加载失败。');
|
258 |
-
if (options.model) await this.setModel(options.model);
|
259 |
-
if (options.temperature !== undefined) await this.setTemperature(options.temperature);
|
260 |
-
if (!await this.fillMessage(message)) throw new Error('消息填写失败。');
|
261 |
-
await this.waitForSendButtonEnabled();
|
262 |
-
if (!await this.sendMessage()) throw new Error('消息发送失败。');
|
263 |
-
console.log('消息发送成功,等待网络拦截获取响应。');
|
264 |
-
return true;
|
265 |
-
}
|
266 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/ai-studio-processor.js
DELETED
@@ -1,264 +0,0 @@
|
|
1 |
-
import { AIStudioInjector } from './ai-studio-injector.js';
|
2 |
-
import { getPageFromPool, releasePageToPool, injectStreamInterceptor, activateStreamInterceptor, deactivateStreamInterceptor, smartNavigate } from './browser.js';
|
3 |
-
import { parseGeminiResponse, createStreamResponse, createErrorResponse, createNonStreamResponse } from './response-parser.js';
|
4 |
-
import config from '../config.js';
|
5 |
-
|
6 |
-
const MAX_RETRIES = 3;
|
7 |
-
const RETRY_DELAY_MS = 1000; // 增加了重试延迟,给页面更多反应时间
|
8 |
-
|
9 |
-
/**
|
10 |
-
* 检查错误是否与页面状态相关,这类错误通常可以通过刷新或重新导航解决。
|
11 |
-
* @param {Error} error - 错误对象。
|
12 |
-
* @returns {boolean} 是否是页面状态错误。
|
13 |
-
*/
|
14 |
-
function isPageStateError(error) {
|
15 |
-
const message = error.message.toLowerCase();
|
16 |
-
const pageErrors = [
|
17 |
-
'timeout',
|
18 |
-
'navigation failed',
|
19 |
-
'page crashed',
|
20 |
-
'target closed',
|
21 |
-
'element not found',
|
22 |
-
'is not visible',
|
23 |
-
'无法找到', // 增强中文错误识别
|
24 |
-
'not find', // 增强英文错误识别
|
25 |
-
'cannot find' // 增强英文错误识别
|
26 |
-
];
|
27 |
-
return pageErrors.some(pattern => message.includes(pattern));
|
28 |
-
}
|
29 |
-
|
30 |
-
/**
|
31 |
-
* 检查错误是否与权限相关,这类错误通常可以通过刷新页面来解决(如果Cookie有效)。
|
32 |
-
* @param {Error} error - 错误对象。
|
33 |
-
* @returns {boolean} 是否是权限错误。
|
34 |
-
*/
|
35 |
-
function isPermissionError(error) {
|
36 |
-
const message = error.message.toLowerCase();
|
37 |
-
const permissionKeywords = [
|
38 |
-
'permission', // 英文关键词
|
39 |
-
'unauthorized', // 英文关键词
|
40 |
-
'无权访问', // 中文关键词 (来自你的日志)
|
41 |
-
'cookie', // 关联关键词
|
42 |
-
'登录' // 关联关键词
|
43 |
-
];
|
44 |
-
return permissionKeywords.some(keyword => message.includes(keyword));
|
45 |
-
}
|
46 |
-
|
47 |
-
|
48 |
-
/**
|
49 |
-
* 重置页面状态,优先刷新,失败则重新导航。
|
50 |
-
* @param {import('playwright').Page} page - Playwright 页面对象。
|
51 |
-
*/
|
52 |
-
async function resetPageState(page) {
|
53 |
-
console.log('页面状态异常或遇到权限问题,开始重置...');
|
54 |
-
try {
|
55 |
-
await page.reload({ waitUntil: 'networkidle', timeout: 20000 });
|
56 |
-
console.log('页面刷新成功。');
|
57 |
-
} catch (reloadError) {
|
58 |
-
console.warn('页面刷新失败,尝试重新导航:', reloadError.message);
|
59 |
-
try {
|
60 |
-
await smartNavigate(page, config.aiStudio.url, { timeout: config.aiStudio.pageTimeout });
|
61 |
-
console.log('重新导航成功。');
|
62 |
-
} catch (gotoError) {
|
63 |
-
console.error('页面重置失败:刷新和重新导航均告失败。', gotoError);
|
64 |
-
throw new Error('Failed to reset page state.');
|
65 |
-
}
|
66 |
-
}
|
67 |
-
}
|
68 |
-
|
69 |
-
/**
|
70 |
-
* 核心处理逻辑,封装了重试和页面交互。
|
71 |
-
* @param {string} prompt - 用户提示。
|
72 |
-
* @param {object} options - 请求选项。
|
73 |
-
* @param {function} responseHandler - 处理响应的回调函数。
|
74 |
-
* @returns {Promise<any>} 响应处理函数返回的结果。
|
75 |
-
*/
|
76 |
-
async function coreAIStudioProcessor(prompt, options, responseHandler) {
|
77 |
-
let page = null;
|
78 |
-
let lastError = null;
|
79 |
-
|
80 |
-
try {
|
81 |
-
page = await getPageFromPool();
|
82 |
-
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
83 |
-
try {
|
84 |
-
console.log(`[尝试 ${attempt}/${MAX_RETRIES}] 开始处理请求...`);
|
85 |
-
// 在第一次尝试或页面URL不正确时,强制导航
|
86 |
-
if (attempt === 1 || !page.url().includes('aistudio.google.com')) {
|
87 |
-
await smartNavigate(page, config.aiStudio.url, { timeout: config.aiStudio.pageTimeout });
|
88 |
-
}
|
89 |
-
|
90 |
-
const result = await responseHandler(page, prompt, options);
|
91 |
-
await releasePageToPool(page);
|
92 |
-
return result;
|
93 |
-
|
94 |
-
} catch (error) {
|
95 |
-
lastError = error;
|
96 |
-
console.warn(`[尝试 ${attempt}/${MAX_RETRIES}] 失败: ${error.message}`);
|
97 |
-
|
98 |
-
// 使用新的、更健壮的错误检查函数
|
99 |
-
if ((isPermissionError(error) || isPageStateError(error)) && attempt < MAX_RETRIES) {
|
100 |
-
console.log(`检测到可重试的错误(权限或页面状态),将在 ${RETRY_DELAY_MS}ms 后重试...`);
|
101 |
-
await resetPageState(page); // 刷新或重新导航页面
|
102 |
-
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
|
103 |
-
} else {
|
104 |
-
console.error(`错误不可重试或已达到最大重试次数,将抛出异常。`);
|
105 |
-
throw error; // 抛出错误,终止循环
|
106 |
-
}
|
107 |
-
}
|
108 |
-
}
|
109 |
-
} catch (error) {
|
110 |
-
console.error('处理 AI Studio 请求最终失败:', error);
|
111 |
-
if (page) {
|
112 |
-
// 如果是页面状态错误,标记页面以便从池中移除
|
113 |
-
if (isPageStateError(error)) {
|
114 |
-
page._needsRemoval = true;
|
115 |
-
}
|
116 |
-
await releasePageToPool(page);
|
117 |
-
}
|
118 |
-
throw lastError || error;
|
119 |
-
}
|
120 |
-
}
|
121 |
-
|
122 |
-
/**
|
123 |
-
* 流式处理 AI Studio 请求。
|
124 |
-
* @param {string} prompt - 用户提示。
|
125 |
-
* @param {ReadableStreamDefaultController} controller - 流控制器。
|
126 |
-
* @param {object} options - 请求选项。
|
127 |
-
*/
|
128 |
-
export async function processAIStudioRequest(prompt, controller, options = {}) {
|
129 |
-
const model = options.model || config.api.defaultModel;
|
130 |
-
try {
|
131 |
-
await coreAIStudioProcessor(prompt, options, async (page, p, opts) => {
|
132 |
-
return new Promise(async (resolve, reject) => {
|
133 |
-
let streamEnded = false;
|
134 |
-
let accumulatedResponse = "";
|
135 |
-
const sentContentKeys = new Set();
|
136 |
-
|
137 |
-
const finalize = (err) => {
|
138 |
-
if (streamEnded) return;
|
139 |
-
streamEnded = true;
|
140 |
-
deactivateStreamInterceptor(page).catch(console.error);
|
141 |
-
if (err) {
|
142 |
-
reject(err);
|
143 |
-
} else {
|
144 |
-
resolve();
|
145 |
-
}
|
146 |
-
};
|
147 |
-
|
148 |
-
const onStreamChunk = (chunk) => {
|
149 |
-
if (streamEnded) return;
|
150 |
-
accumulatedResponse += chunk;
|
151 |
-
const parsedData = parseGeminiResponse(accumulatedResponse);
|
152 |
-
|
153 |
-
// 如果解析器检测到权限错误,就用这个错误来拒绝Promise
|
154 |
-
if (parsedData?.permissionError) {
|
155 |
-
return finalize(new Error(parsedData.content));
|
156 |
-
}
|
157 |
-
|
158 |
-
if (Array.isArray(parsedData) && parsedData.length > 0) {
|
159 |
-
for (const item of parsedData) {
|
160 |
-
const contentKey = `${item.type}::${item.content}`;
|
161 |
-
if (item.content?.trim() && !sentContentKeys.has(contentKey)) {
|
162 |
-
controller.enqueue(`data: ${JSON.stringify(createStreamResponse(item.content, item.type, model))}\n\n`);
|
163 |
-
sentContentKeys.add(contentKey);
|
164 |
-
}
|
165 |
-
}
|
166 |
-
}
|
167 |
-
};
|
168 |
-
|
169 |
-
const onStreamEnd = () => {
|
170 |
-
if (streamEnded) return;
|
171 |
-
console.log('流已结束,发送 [DONE] 信号。');
|
172 |
-
controller.enqueue('data: [DONE]\n\n');
|
173 |
-
controller.close();
|
174 |
-
finalize();
|
175 |
-
};
|
176 |
-
|
177 |
-
try {
|
178 |
-
await injectStreamInterceptor(page, onStreamChunk, onStreamEnd);
|
179 |
-
await activateStreamInterceptor(page);
|
180 |
-
const injector = new AIStudioInjector(page);
|
181 |
-
await injector.processMessage(p, opts);
|
182 |
-
|
183 |
-
// 设置一个总超时,以防万一
|
184 |
-
setTimeout(() => {
|
185 |
-
if (!streamEnded) {
|
186 |
-
finalize(new Error('AI Studio 响应超时。'));
|
187 |
-
}
|
188 |
-
}, config.aiStudio.responseTimeout);
|
189 |
-
|
190 |
-
} catch (err) {
|
191 |
-
finalize(err);
|
192 |
-
}
|
193 |
-
});
|
194 |
-
});
|
195 |
-
} catch (error) {
|
196 |
-
// 确保在任何情况下都能正确关闭流
|
197 |
-
if (controller.desiredSize !== null) {
|
198 |
-
try {
|
199 |
-
controller.enqueue(`data: ${JSON.stringify(createErrorResponse(error.message, model))}\n\n`);
|
200 |
-
controller.enqueue('data: [DONE]\n\n');
|
201 |
-
controller.close();
|
202 |
-
} catch (e) {
|
203 |
-
console.error('关闭流控制器时出错:', e);
|
204 |
-
}
|
205 |
-
}
|
206 |
-
}
|
207 |
-
}
|
208 |
-
|
209 |
-
/**
|
210 |
-
* 非流式(同步)处理 AI Studio 请求。
|
211 |
-
* @param {string} prompt - 用户提示。
|
212 |
-
* @param {object} options - 请求选项。
|
213 |
-
* @returns {Promise<object>} OpenAI 格式的响应对象。
|
214 |
-
*/
|
215 |
-
export async function processAIStudioRequestSync(prompt, options = {}) {
|
216 |
-
const model = options.model || config.api.defaultModel;
|
217 |
-
try {
|
218 |
-
return await coreAIStudioProcessor(prompt, options, async (page, p, opts) => {
|
219 |
-
return new Promise(async (resolve, reject) => {
|
220 |
-
let collectedContent = '';
|
221 |
-
const responseListener = async (response) => {
|
222 |
-
if (response.url().includes('GenerateContent')) {
|
223 |
-
try {
|
224 |
-
const text = await response.text();
|
225 |
-
const parsedData = parseGeminiResponse(text);
|
226 |
-
|
227 |
-
if (parsedData?.permissionError) {
|
228 |
-
return reject(new Error(parsedData.content));
|
229 |
-
}
|
230 |
-
|
231 |
-
if (Array.isArray(parsedData)) {
|
232 |
-
collectedContent += parsedData
|
233 |
-
.filter(item => item.type === 'text')
|
234 |
-
.map(item => item.content)
|
235 |
-
.join('');
|
236 |
-
}
|
237 |
-
page.removeListener('response', responseListener);
|
238 |
-
resolve(createNonStreamResponse(collectedContent, model));
|
239 |
-
} catch (err) {
|
240 |
-
reject(err);
|
241 |
-
}
|
242 |
-
}
|
243 |
-
};
|
244 |
-
|
245 |
-
page.on('response', responseListener);
|
246 |
-
|
247 |
-
try {
|
248 |
-
const injector = new AIStudioInjector(page);
|
249 |
-
await injector.processMessage(p, opts);
|
250 |
-
|
251 |
-
setTimeout(() => {
|
252 |
-
page.removeListener('response', responseListener);
|
253 |
-
reject(new Error('AI Studio 响应超时。'));
|
254 |
-
}, config.aiStudio.responseTimeout);
|
255 |
-
} catch (err) {
|
256 |
-
page.removeListener('response', responseListener);
|
257 |
-
reject(err);
|
258 |
-
}
|
259 |
-
});
|
260 |
-
});
|
261 |
-
} catch (error) {
|
262 |
-
return createErrorResponse(error.message, model);
|
263 |
-
}
|
264 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/browser.js
DELETED
@@ -1,949 +0,0 @@
|
|
1 |
-
import { chromium } from 'playwright'
|
2 |
-
// import { chromium } from 'playwright-extra'
|
3 |
-
// import StealthPlugin from 'puppeteer-extra-plugin-stealth'
|
4 |
-
import config from '../config.js'
|
5 |
-
import { loadCookies } from './common-utils.js'
|
6 |
-
import { info } from './logger.js'
|
7 |
-
|
8 |
-
// 存储浏览器实例
|
9 |
-
let browser = null
|
10 |
-
let context = null
|
11 |
-
|
12 |
-
// 页面池管理
|
13 |
-
class PagePool {
|
14 |
-
constructor(maxSize = 5) {
|
15 |
-
this.maxSize = maxSize
|
16 |
-
this.availablePages = []
|
17 |
-
this.busyPages = new Set()
|
18 |
-
this.totalPages = 0
|
19 |
-
}
|
20 |
-
|
21 |
-
/**
|
22 |
-
* 获取一个可用的页面
|
23 |
-
* @returns {Promise<Page>}
|
24 |
-
*/
|
25 |
-
async getPage() {
|
26 |
-
// 如果有可用页面,直接返回
|
27 |
-
if (this.availablePages.length > 0) {
|
28 |
-
const page = this.availablePages.pop()
|
29 |
-
this.busyPages.add(page)
|
30 |
-
info(`从页面池获取页面,当前忙碌页面数: ${this.busyPages.size}`)
|
31 |
-
return page
|
32 |
-
}
|
33 |
-
|
34 |
-
// 如果没有可用页面且未达到最大数量,创建新页面
|
35 |
-
if (this.totalPages < this.maxSize) {
|
36 |
-
const { context } = await initBrowser()
|
37 |
-
const page = await context.newPage()
|
38 |
-
this.busyPages.add(page)
|
39 |
-
this.totalPages++
|
40 |
-
info(`创建新页面,总页面数: ${this.totalPages},忙碌页面数: ${this.busyPages.size}`)
|
41 |
-
return page
|
42 |
-
}
|
43 |
-
|
44 |
-
// 如果达到最大数量,等待有页面释放
|
45 |
-
info('页面池已满,等待页面释放...')
|
46 |
-
return new Promise((resolve) => {
|
47 |
-
const checkAvailable = () => {
|
48 |
-
if (this.availablePages.length > 0) {
|
49 |
-
const page = this.availablePages.pop()
|
50 |
-
this.busyPages.add(page)
|
51 |
-
info(`等待后获取到页面,当前忙碌页面数: ${this.busyPages.size}`)
|
52 |
-
resolve(page)
|
53 |
-
} else {
|
54 |
-
setTimeout(checkAvailable, 100)
|
55 |
-
}
|
56 |
-
}
|
57 |
-
checkAvailable()
|
58 |
-
})
|
59 |
-
}
|
60 |
-
|
61 |
-
/**
|
62 |
-
* 释放页面回到池中
|
63 |
-
* @param {Page} page
|
64 |
-
*/
|
65 |
-
async releasePage(page) {
|
66 |
-
if (!this.busyPages.has(page)) {
|
67 |
-
info('尝试释放不在忙碌列表中的页面')
|
68 |
-
return
|
69 |
-
}
|
70 |
-
|
71 |
-
// 检查页面是否被标记为需要移除
|
72 |
-
if (page._needsRemoval) {
|
73 |
-
info('页面被标记为需要移除,将从池中移除')
|
74 |
-
await this.removePage(page)
|
75 |
-
return
|
76 |
-
}
|
77 |
-
|
78 |
-
try {
|
79 |
-
// 清理页面状态
|
80 |
-
await this.cleanupPage(page)
|
81 |
-
|
82 |
-
this.busyPages.delete(page)
|
83 |
-
this.availablePages.push(page)
|
84 |
-
info(`页面已释放回池中,可用页面数: ${this.availablePages.length},忙碌页面数: ${this.busyPages.size}`)
|
85 |
-
} catch (error) {
|
86 |
-
info(`清理页面时出错,将关闭该页面: ${error.message}`)
|
87 |
-
await this.removePage(page)
|
88 |
-
}
|
89 |
-
}
|
90 |
-
|
91 |
-
/**
|
92 |
-
* 清理页面状态
|
93 |
-
* @param {Page} page
|
94 |
-
*/
|
95 |
-
async cleanupPage(page) {
|
96 |
-
try {
|
97 |
-
// 移除所有事件监听器
|
98 |
-
page.removeAllListeners()
|
99 |
-
|
100 |
-
// 清理流式拦截器相关的函数和状态
|
101 |
-
try {
|
102 |
-
await page.evaluate(() => {
|
103 |
-
// 清理所有流式拦截器相关的函数
|
104 |
-
const keys = Object.keys(window)
|
105 |
-
keys.forEach(key => {
|
106 |
-
if (key.startsWith('__handleStreamChunk') ||
|
107 |
-
key.startsWith('__onStreamChunk') ||
|
108 |
-
key.startsWith('__onStreamEnd')) {
|
109 |
-
delete window[key]
|
110 |
-
}
|
111 |
-
})
|
112 |
-
|
113 |
-
// 清理拦截器状态
|
114 |
-
if (window.__streamInterceptor) {
|
115 |
-
if (typeof window.__streamInterceptor.deactivate === 'function') {
|
116 |
-
window.__streamInterceptor.deactivate()
|
117 |
-
}
|
118 |
-
delete window.__streamInterceptor
|
119 |
-
}
|
120 |
-
|
121 |
-
// 清理其他相关状态
|
122 |
-
delete window.__handleStreamChunk
|
123 |
-
delete window.__onStreamChunk
|
124 |
-
delete window.__onStreamEnd
|
125 |
-
delete window.__streamCallbacks
|
126 |
-
})
|
127 |
-
} catch (evalError) {
|
128 |
-
// 忽略页面evaluate错误,可能页面已经关闭
|
129 |
-
info(`清理页面状态时出现evaluate错误: ${evalError.message}`)
|
130 |
-
}
|
131 |
-
|
132 |
-
info('页面状态已清理')
|
133 |
-
} catch (error) {
|
134 |
-
throw new Error(`清理页面失败: ${error.message}`)
|
135 |
-
}
|
136 |
-
}
|
137 |
-
|
138 |
-
/**
|
139 |
-
* 从池中移除页面
|
140 |
-
* @param {Page} page
|
141 |
-
*/
|
142 |
-
async removePage(page) {
|
143 |
-
try {
|
144 |
-
this.busyPages.delete(page)
|
145 |
-
const index = this.availablePages.indexOf(page)
|
146 |
-
if (index > -1) {
|
147 |
-
this.availablePages.splice(index, 1)
|
148 |
-
}
|
149 |
-
|
150 |
-
await page.close()
|
151 |
-
this.totalPages--
|
152 |
-
info(`页面已从池中移除,总页面数: ${this.totalPages}`)
|
153 |
-
} catch (error) {
|
154 |
-
info(`关闭页面时出错: ${error.message}`)
|
155 |
-
}
|
156 |
-
}
|
157 |
-
|
158 |
-
/**
|
159 |
-
* 清理所有页面
|
160 |
-
*/
|
161 |
-
async cleanup() {
|
162 |
-
info('开始清理页面池...')
|
163 |
-
|
164 |
-
// 关闭所有忙碌页面
|
165 |
-
for (const page of this.busyPages) {
|
166 |
-
try {
|
167 |
-
await page.close()
|
168 |
-
} catch (error) {
|
169 |
-
info(`关闭忙碌页面时出错: ${error.message}`)
|
170 |
-
}
|
171 |
-
}
|
172 |
-
|
173 |
-
// 关闭所有可用页面
|
174 |
-
for (const page of this.availablePages) {
|
175 |
-
try {
|
176 |
-
await page.close()
|
177 |
-
} catch (error) {
|
178 |
-
info(`关闭可用页面时出错: ${error.message}`)
|
179 |
-
}
|
180 |
-
}
|
181 |
-
|
182 |
-
this.busyPages.clear()
|
183 |
-
this.availablePages = []
|
184 |
-
this.totalPages = 0
|
185 |
-
info('页面池清理完成')
|
186 |
-
}
|
187 |
-
|
188 |
-
/**
|
189 |
-
* 获取池状态信息
|
190 |
-
*/
|
191 |
-
getStatus() {
|
192 |
-
return {
|
193 |
-
total: this.totalPages,
|
194 |
-
available: this.availablePages.length,
|
195 |
-
busy: this.busyPages.size,
|
196 |
-
maxSize: this.maxSize
|
197 |
-
}
|
198 |
-
}
|
199 |
-
}
|
200 |
-
|
201 |
-
// 全局页面池实例
|
202 |
-
let pagePool = null
|
203 |
-
|
204 |
-
/**
|
205 |
-
* 初始化浏览器
|
206 |
-
* @returns {Promise<{browser: any, context: any}>}
|
207 |
-
*/
|
208 |
-
export async function initBrowser() {
|
209 |
-
if (!browser) {
|
210 |
-
// chromium.use(StealthPlugin())
|
211 |
-
browser = await chromium.launch({
|
212 |
-
headless: config.browser.headless, // 从环境变量读取
|
213 |
-
timeout: config.browser.timeout,
|
214 |
-
args: config.browser.args,
|
215 |
-
executablePath: config.browser.executablePath
|
216 |
-
})
|
217 |
-
context = await browser.newContext({
|
218 |
-
userAgent: config.browser.userAgent
|
219 |
-
});
|
220 |
-
|
221 |
-
// 读取并设置cookies(优先使用环境变量)
|
222 |
-
const cookies = loadCookies(config.cookieFile, config.cookiesFromEnv);
|
223 |
-
await context.addCookies(cookies);
|
224 |
-
}
|
225 |
-
return { browser, context }
|
226 |
-
}
|
227 |
-
|
228 |
-
/**
|
229 |
-
* 初始化页面池
|
230 |
-
* @param {number} maxSize - 页面池最大大小
|
231 |
-
* @returns {PagePool}
|
232 |
-
*/
|
233 |
-
export function initPagePool(maxSize = 5) {
|
234 |
-
if (!pagePool) {
|
235 |
-
pagePool = new PagePool(maxSize)
|
236 |
-
info(`页面池已初始化,最大页面数: ${maxSize}`)
|
237 |
-
}
|
238 |
-
return pagePool
|
239 |
-
}
|
240 |
-
|
241 |
-
/**
|
242 |
-
* 获取页面池实例
|
243 |
-
* @returns {PagePool}
|
244 |
-
*/
|
245 |
-
export function getPagePool() {
|
246 |
-
if (!pagePool) {
|
247 |
-
pagePool = new PagePool()
|
248 |
-
info('页面池已自动初始化,使用默认配置')
|
249 |
-
}
|
250 |
-
return pagePool
|
251 |
-
}
|
252 |
-
|
253 |
-
/**
|
254 |
-
* 从页面池获取页面
|
255 |
-
* @returns {Promise<any>}
|
256 |
-
*/
|
257 |
-
export async function getPageFromPool() {
|
258 |
-
const pool = getPagePool()
|
259 |
-
const page = await pool.getPage()
|
260 |
-
|
261 |
-
// 将页面切换到前台
|
262 |
-
await page.bringToFront()
|
263 |
-
|
264 |
-
return page
|
265 |
-
}
|
266 |
-
|
267 |
-
/**
|
268 |
-
* 智能导航到指定URL,如果页面已在目标URL则进行刷新
|
269 |
-
* @param {Page} page - Playwright页面对象
|
270 |
-
* @param {string} targetUrl - 目标URL
|
271 |
-
* @param {Object} options - 导航选项
|
272 |
-
* @returns {Promise<boolean>} 是否进行了实际导航
|
273 |
-
*/
|
274 |
-
export async function smartNavigate(page, targetUrl, options = {}) {
|
275 |
-
const currentUrl = page.url()
|
276 |
-
console.log('当前页面URL:', currentUrl)
|
277 |
-
console.log('目标URL:', targetUrl)
|
278 |
-
|
279 |
-
|
280 |
-
try {
|
281 |
-
if (currentUrl !== targetUrl) {
|
282 |
-
console.log('页面URL不匹配,需要导航...')
|
283 |
-
await page.goto(targetUrl, {
|
284 |
-
waitUntil: 'load',
|
285 |
-
timeout: 30000,
|
286 |
-
...options
|
287 |
-
})
|
288 |
-
console.log('页面导航完成')
|
289 |
-
return true
|
290 |
-
} else {
|
291 |
-
console.log('页面已在目标URL,进行刷新以确保最新状态...')
|
292 |
-
// 确保页面处于活跃状态
|
293 |
-
await page.bringToFront()
|
294 |
-
|
295 |
-
// 刷新页面
|
296 |
-
await page.reload({
|
297 |
-
waitUntil: 'load',
|
298 |
-
timeout: 30000,
|
299 |
-
...options
|
300 |
-
})
|
301 |
-
console.log('页面刷新完成')
|
302 |
-
return true
|
303 |
-
}
|
304 |
-
}
|
305 |
-
catch {
|
306 |
-
|
307 |
-
}
|
308 |
-
return false
|
309 |
-
}
|
310 |
-
|
311 |
-
/**
|
312 |
-
* 释放页面回到池中
|
313 |
-
* @param {any} page
|
314 |
-
*/
|
315 |
-
export async function releasePageToPool(page) {
|
316 |
-
const pool = getPagePool()
|
317 |
-
await pool.releasePage(page)
|
318 |
-
}
|
319 |
-
|
320 |
-
/**
|
321 |
-
* 获取页面池状态
|
322 |
-
* @returns {Object}
|
323 |
-
*/
|
324 |
-
export function getPagePoolStatus() {
|
325 |
-
if (!pagePool) {
|
326 |
-
return { total: 0, available: 0, busy: 0, maxSize: 0 }
|
327 |
-
}
|
328 |
-
return pagePool.getStatus()
|
329 |
-
}
|
330 |
-
|
331 |
-
/**
|
332 |
-
* 清理浏览器资源
|
333 |
-
*/
|
334 |
-
export async function cleanup() {
|
335 |
-
// 先清理页面池
|
336 |
-
if (pagePool) {
|
337 |
-
await pagePool.cleanup()
|
338 |
-
pagePool = null
|
339 |
-
}
|
340 |
-
|
341 |
-
if (context) {
|
342 |
-
await context.close()
|
343 |
-
context = null
|
344 |
-
}
|
345 |
-
if (browser) {
|
346 |
-
await browser.close()
|
347 |
-
browser = null
|
348 |
-
}
|
349 |
-
}
|
350 |
-
|
351 |
-
/**
|
352 |
-
* 模拟人类随机点击行为 - 仅在输入框上方300像素内的安全区域
|
353 |
-
* @param {Page} page - Playwright页面对象
|
354 |
-
* @param {Object} options - 配置选项
|
355 |
-
* @param {number} options.minClicks - 最少点击次数,默认2
|
356 |
-
* @param {number} options.maxClicks - 最多点击次数,默认5
|
357 |
-
* @param {number} options.minDelay - 点击间最小延迟(毫秒),默认500
|
358 |
-
* @param {number} options.maxDelay - 点击间最大延迟(毫秒),默认2000
|
359 |
-
* @param {Element} options.referenceElement - 参考元素(如输入框),在其上方300像素内进行点击
|
360 |
-
* @returns {Promise<void>}
|
361 |
-
*/
|
362 |
-
export async function simulateHumanRandomClicks(page, options = {}) {
|
363 |
-
const {
|
364 |
-
minClicks = 1,
|
365 |
-
maxClicks = 3,
|
366 |
-
minDelay = 300,
|
367 |
-
maxDelay = 500,
|
368 |
-
referenceElement = null
|
369 |
-
} = options
|
370 |
-
|
371 |
-
try {
|
372 |
-
info('开始模拟人类随机点击行为...')
|
373 |
-
|
374 |
-
// 随机确定点击次数
|
375 |
-
const clickCount = Math.floor(Math.random() * (maxClicks - minClicks + 1)) + minClicks
|
376 |
-
info(`将进行 ${clickCount} 次随机点击`)
|
377 |
-
|
378 |
-
let safeArea = null
|
379 |
-
|
380 |
-
// 如果提供���参考元素,获取其位置信息
|
381 |
-
if (referenceElement) {
|
382 |
-
try {
|
383 |
-
const boundingBox = await referenceElement.boundingBox()
|
384 |
-
if (boundingBox) {
|
385 |
-
// 定义输入框上方300像素内的安全区域
|
386 |
-
safeArea = {
|
387 |
-
x: boundingBox.x - 50, // 左边扩展50px
|
388 |
-
y: Math.max(0, boundingBox.y - 200), // 上方300px区域
|
389 |
-
width: boundingBox.width + 50, // 宽度扩展100px
|
390 |
-
height: 300 // 高度300px的安全区域(输入框上方300像素内)
|
391 |
-
}
|
392 |
-
info(`使用输入框附近的安全区域: x=${safeArea.x}, y=${safeArea.y}, w=${safeArea.width}, h=${safeArea.height}`)
|
393 |
-
}
|
394 |
-
} catch (error) {
|
395 |
-
info(`获取参考元素位置失败,使用默认安全区域: ${error.message}`)
|
396 |
-
}
|
397 |
-
}
|
398 |
-
|
399 |
-
// 如果没有安全区域,使用页面中央的安全区域
|
400 |
-
if (!safeArea) {
|
401 |
-
const viewport = page.viewportSize()
|
402 |
-
const width = viewport?.width || 1280
|
403 |
-
const height = viewport?.height || 720
|
404 |
-
|
405 |
-
safeArea = {
|
406 |
-
x: width * 0.3,
|
407 |
-
y: height * 0.3,
|
408 |
-
width: width * 0.4,
|
409 |
-
height: height * 0.2
|
410 |
-
}
|
411 |
-
info(`使用默认安全区域: x=${safeArea.x}, y=${safeArea.y}, w=${safeArea.width}, h=${safeArea.height}`)
|
412 |
-
}
|
413 |
-
|
414 |
-
for (let i = 0; i < clickCount; i++) {
|
415 |
-
try {
|
416 |
-
// 在安全区域内生成随机坐标
|
417 |
-
const x = Math.floor(Math.random() * safeArea.width) + safeArea.x
|
418 |
-
const y = Math.floor(Math.random() * safeArea.height) + safeArea.y
|
419 |
-
|
420 |
-
info(`第 ${i + 1} 次安全点击: (${x}, ${y})`)
|
421 |
-
|
422 |
-
// 检查点击位置是否有可交互元素
|
423 |
-
const elementAtPoint = await page.locator(`*`).first().evaluate((_, coords) => {
|
424 |
-
const element = document.elementFromPoint(coords.x, coords.y)
|
425 |
-
if (!element) return { safe: true }
|
426 |
-
|
427 |
-
const tagName = element.tagName.toLowerCase()
|
428 |
-
const hasHref = element.hasAttribute('href')
|
429 |
-
const hasOnClick = element.hasAttribute('onclick') || element.onclick
|
430 |
-
const isButton = tagName === 'button' || element.type === 'button'
|
431 |
-
const isLink = tagName === 'a' || hasHref
|
432 |
-
const isInput = ['input', 'textarea', 'select'].includes(tagName)
|
433 |
-
|
434 |
-
return {
|
435 |
-
safe: !isButton && !isLink && !hasOnClick && !isInput,
|
436 |
-
tagName,
|
437 |
-
hasHref,
|
438 |
-
hasOnClick,
|
439 |
-
isButton,
|
440 |
-
isLink,
|
441 |
-
isInput
|
442 |
-
}
|
443 |
-
}, { x, y })
|
444 |
-
|
445 |
-
if (elementAtPoint.safe) {
|
446 |
-
// 模拟鼠标移动到目标位置
|
447 |
-
await page.mouse.move(x, y, {
|
448 |
-
steps: Math.floor(Math.random() * 10) + 5 // 5-15步移动,更自然
|
449 |
-
})
|
450 |
-
|
451 |
-
// 随机等待一小段时间
|
452 |
-
await page.waitForTimeout(Math.floor(Math.random() * 200) + 100)
|
453 |
-
|
454 |
-
// 执行点击
|
455 |
-
await page.mouse.click(x, y)
|
456 |
-
info(`安全点击完成: (${x}, ${y})`)
|
457 |
-
} else {
|
458 |
-
info(`跳过不安全的点击位置 (${x}, ${y}): ${elementAtPoint.tagName}`)
|
459 |
-
}
|
460 |
-
|
461 |
-
// 点击间随机延迟
|
462 |
-
if (i < clickCount - 1) {
|
463 |
-
const delay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay
|
464 |
-
info(`等待 ${delay}ms 后进行下一次点击`)
|
465 |
-
await page.waitForTimeout(delay)
|
466 |
-
}
|
467 |
-
} catch (clickError) {
|
468 |
-
info(`第 ${i + 1} 次点击出现错误,继续下一次: ${clickError.message}`)
|
469 |
-
}
|
470 |
-
}
|
471 |
-
|
472 |
-
info('安全随机点击模拟完成')
|
473 |
-
} catch (error) {
|
474 |
-
info(`模拟安全随机点击时出现错误: ${error.message}`)
|
475 |
-
}
|
476 |
-
}
|
477 |
-
|
478 |
-
/**
|
479 |
-
* 模拟更复杂的人类行为
|
480 |
-
* @param {Page} page - Playwright页面对象
|
481 |
-
* @param {Object} options - 配置选项
|
482 |
-
* @returns {Promise<void>}
|
483 |
-
*/
|
484 |
-
export async function simulateHumanBehavior(page, options = {}) {
|
485 |
-
const {
|
486 |
-
includeScrolling = true,
|
487 |
-
includeMouseMovement = true,
|
488 |
-
includeRandomClicks = true,
|
489 |
-
duration = 3000 // 总持续时间
|
490 |
-
} = options
|
491 |
-
|
492 |
-
try {
|
493 |
-
info('开始模拟复杂的人类行为...')
|
494 |
-
|
495 |
-
const startTime = Date.now()
|
496 |
-
const viewport = page.viewportSize()
|
497 |
-
const width = viewport?.width || 1280
|
498 |
-
const height = viewport?.height || 720
|
499 |
-
|
500 |
-
while (Date.now() - startTime < duration) {
|
501 |
-
const action = Math.random()
|
502 |
-
|
503 |
-
if (action < 0.3 && includeScrolling) {
|
504 |
-
// 30% 概率进行滚动
|
505 |
-
const scrollDirection = Math.random() > 0.5 ? 'down' : 'up'
|
506 |
-
const scrollAmount = Math.floor(Math.random() * 300) + 100
|
507 |
-
|
508 |
-
info(`模拟滚动: ${scrollDirection}, 距离: ${scrollAmount}px`)
|
509 |
-
await page.mouse.wheel(0, scrollDirection === 'down' ? scrollAmount : -scrollAmount)
|
510 |
-
|
511 |
-
} else if (action < 0.6 && includeMouseMovement) {
|
512 |
-
// 30% 概率进行鼠标移动
|
513 |
-
const x = Math.floor(Math.random() * width)
|
514 |
-
const y = Math.floor(Math.random() * height)
|
515 |
-
|
516 |
-
info(`模拟鼠标移动到: (${x}, ${y})`)
|
517 |
-
await page.mouse.move(x, y, {
|
518 |
-
steps: Math.floor(Math.random() * 15) + 5
|
519 |
-
})
|
520 |
-
|
521 |
-
} else if (action < 0.8 && includeRandomClicks) {
|
522 |
-
// 20% 概率进行点击
|
523 |
-
const x = Math.floor(Math.random() * (width * 0.8)) + width * 0.1
|
524 |
-
const y = Math.floor(Math.random() * (height * 0.8)) + height * 0.1
|
525 |
-
|
526 |
-
info(`模拟随机点击: (${x}, ${y})`)
|
527 |
-
await page.mouse.click(x, y)
|
528 |
-
}
|
529 |
-
|
530 |
-
// 随机等待
|
531 |
-
const waitTime = Math.floor(Math.random() * 800) + 200
|
532 |
-
await page.waitForTimeout(waitTime)
|
533 |
-
}
|
534 |
-
|
535 |
-
info('复杂人类行为模拟完成')
|
536 |
-
} catch (error) {
|
537 |
-
info(`模拟复杂人类行为时出现错误: ${error.message}`)
|
538 |
-
}
|
539 |
-
}
|
540 |
-
|
541 |
-
/**
|
542 |
-
* 处理Google AI Studio可能出现的欢迎模态对话框
|
543 |
-
* @param {Page} page - Playwright页面对象
|
544 |
-
* @param {number} timeout - 等待对话框出现的超时时间(毫秒),默认5000ms
|
545 |
-
* @returns {Promise<boolean>} - 返回是否成功处理了对话框
|
546 |
-
*/
|
547 |
-
export async function handleWelcomeModal(page, timeout = 5000) {
|
548 |
-
try {
|
549 |
-
info('检查是否有欢迎对话框需要关闭...')
|
550 |
-
|
551 |
-
// 对话框和关闭按钮的选择器
|
552 |
-
const dialogSelector = 'mat-dialog-container'
|
553 |
-
const closeButtonSelector = 'button[mat-dialog-close][aria-label="close"]'
|
554 |
-
|
555 |
-
// 检查是否存在对话框
|
556 |
-
const dialog = page.locator(dialogSelector).first()
|
557 |
-
|
558 |
-
if (await dialog.isVisible({ timeout })) {
|
559 |
-
info('发现欢迎对话框,尝试关闭...')
|
560 |
-
|
561 |
-
// 查找并点击关闭按钮
|
562 |
-
const closeButton = page.locator(closeButtonSelector).first()
|
563 |
-
|
564 |
-
if (await closeButton.isVisible({ timeout: 2000 })) {
|
565 |
-
await closeButton.click()
|
566 |
-
info('已通过关闭按钮关闭欢迎对话框')
|
567 |
-
|
568 |
-
// 等待对话框消失
|
569 |
-
await page.waitForTimeout(1000)
|
570 |
-
return true
|
571 |
-
} else {
|
572 |
-
info('未找到关闭按钮,尝试按ESC键关闭对话框')
|
573 |
-
await page.keyboard.press('Escape')
|
574 |
-
await page.waitForTimeout(1000)
|
575 |
-
return true
|
576 |
-
}
|
577 |
-
} else {
|
578 |
-
info('未发现欢迎对话框')
|
579 |
-
return false
|
580 |
-
}
|
581 |
-
} catch (err) {
|
582 |
-
info('处理欢迎对话框时出现错误,继续执行:', err.message)
|
583 |
-
return false
|
584 |
-
}
|
585 |
-
}
|
586 |
-
|
587 |
-
/**
|
588 |
-
* 注入流式拦截脚本到页面中(基于Tampermonkey脚本的思路)
|
589 |
-
* 这种方法避免了Playwright的page.route()阻塞问题
|
590 |
-
* @param {Page} page - Playwright页面对象
|
591 |
-
* @param {Function} onStreamChunk - 流数据块回调函数
|
592 |
-
* @param {Function} onStreamEnd - 流结束回调函数
|
593 |
-
* @returns {Promise<void>}
|
594 |
-
*/
|
595 |
-
export async function injectStreamInterceptor(page, onStreamChunk, onStreamEnd) {
|
596 |
-
try {
|
597 |
-
info('注入流式拦截脚本到页面中...')
|
598 |
-
|
599 |
-
// 清理可能存在的旧函数(清理所有以__onStream开头的函数)
|
600 |
-
try {
|
601 |
-
await page.evaluate(() => {
|
602 |
-
// 清理所有以__onStream开头的函数
|
603 |
-
Object.keys(window).forEach(key => {
|
604 |
-
if (key.startsWith('__onStreamChunk_') || key.startsWith('__onStreamEnd_')) {
|
605 |
-
delete window[key]
|
606 |
-
}
|
607 |
-
})
|
608 |
-
// 也清理旧的固定名称函数
|
609 |
-
delete window.__onStreamChunk
|
610 |
-
delete window.__onStreamEnd
|
611 |
-
})
|
612 |
-
} catch (e) {
|
613 |
-
// 忽略清理错误
|
614 |
-
}
|
615 |
-
|
616 |
-
// 设置回调函数(使用唯一名称避免冲突)
|
617 |
-
const uniqueId = Date.now() + '_' + Math.random().toString(36).substr(2, 9)
|
618 |
-
const chunkFunctionName = `__onStreamChunk_${uniqueId}`
|
619 |
-
const endFunctionName = `__onStreamEnd_${uniqueId}`
|
620 |
-
|
621 |
-
await page.exposeFunction(chunkFunctionName, onStreamChunk)
|
622 |
-
await page.exposeFunction(endFunctionName, onStreamEnd)
|
623 |
-
|
624 |
-
// 直接在页面中注入拦截脚本(不使用addInitScript,确保每次都能重新注入)
|
625 |
-
await page.evaluate(() => {
|
626 |
-
// 如果已经存在拦截器,先清理
|
627 |
-
if (window.__streamInterceptor) {
|
628 |
-
if (typeof window.__streamInterceptor.deactivate === 'function') {
|
629 |
-
window.__streamInterceptor.deactivate()
|
630 |
-
}
|
631 |
-
delete window.__streamInterceptor
|
632 |
-
}
|
633 |
-
|
634 |
-
// 保存原始的XMLHttpRequest方法
|
635 |
-
const originalXhrOpen = window.XMLHttpRequest.prototype.open
|
636 |
-
const originalXhrSend = window.XMLHttpRequest.prototype.send
|
637 |
-
// 支持多种可能的URL模式
|
638 |
-
const TARGET_URL_PATTERNS = [
|
639 |
-
"MakerSuiteService/GenerateContent",
|
640 |
-
"GenerateContent",
|
641 |
-
"streamGenerateContent",
|
642 |
-
"generateContent"
|
643 |
-
]
|
644 |
-
|
645 |
-
// 流结束检测的正则表达式(基于Tampermonkey脚本)
|
646 |
-
const FINAL_BLOCK_SIGNATURE = /\[\s*null\s*,\s*null\s*,\s*null\s*,\s*\[\s*"/
|
647 |
-
const END_OF_STREAM_SIGNAL = "__END_OF_STREAM__"
|
648 |
-
|
649 |
-
let interceptorActive = false
|
650 |
-
|
651 |
-
// 向页面暴露拦截器控制函数
|
652 |
-
window.__streamInterceptor = {
|
653 |
-
activate: () => {
|
654 |
-
if (interceptorActive) return
|
655 |
-
|
656 |
-
console.log('🎯 激活流式拦截器...')
|
657 |
-
interceptorActive = true
|
658 |
-
|
659 |
-
// 重写XMLHttpRequest.open方法
|
660 |
-
window.XMLHttpRequest.prototype.open = function (method, url, ...rest) {
|
661 |
-
this._url = url
|
662 |
-
this._method = method
|
663 |
-
console.log(`[XHR] 请求: ${method} ${url}`)
|
664 |
-
return originalXhrOpen.apply(this, [method, url, ...rest])
|
665 |
-
}
|
666 |
-
|
667 |
-
// 重写XMLHttpRequest.send方法
|
668 |
-
window.XMLHttpRequest.prototype.send = function (...args) {
|
669 |
-
// 检查URL是否匹配任何目标模式
|
670 |
-
const urlString = this._url ? this._url.toString() : ''
|
671 |
-
const isTargetRequest = TARGET_URL_PATTERNS.some(pattern => urlString.includes(pattern))
|
672 |
-
|
673 |
-
if (this._url && isTargetRequest) {
|
674 |
-
console.log('🎯 [XHR Stream] 拦截到目标请求:', urlString)
|
675 |
-
console.log('🎯 [XHR Stream] 准备接收流式数据...')
|
676 |
-
|
677 |
-
let lastSentLength = 0
|
678 |
-
let fullResponseText = ""
|
679 |
-
let streamEnded = false
|
680 |
-
let finalizationTimer = null
|
681 |
-
|
682 |
-
const finalizeStream = () => {
|
683 |
-
if (streamEnded) return
|
684 |
-
streamEnded = true
|
685 |
-
console.log('[Stream] 判定流已结束')
|
686 |
-
clearTimeout(finalizationTimer)
|
687 |
-
|
688 |
-
const finalChunk = fullResponseText.slice(lastSentLength)
|
689 |
-
if (finalChunk) {
|
690 |
-
window.__streamInterceptor.sendChunk(finalChunk)
|
691 |
-
}
|
692 |
-
window.__streamInterceptor.sendChunk(END_OF_STREAM_SIGNAL)
|
693 |
-
}
|
694 |
-
|
695 |
-
// 监听progress事件来获取流式数据
|
696 |
-
this.addEventListener('progress', () => {
|
697 |
-
if (streamEnded) return
|
698 |
-
|
699 |
-
try {
|
700 |
-
fullResponseText = this.responseText || ''
|
701 |
-
const newChunk = fullResponseText.slice(lastSentLength)
|
702 |
-
|
703 |
-
if (newChunk) {
|
704 |
-
console.log(`[Stream] 收到数据块,长度: ${newChunk.length},HTTP状态: ${this.status}`)
|
705 |
-
console.log(`[Stream] 数据块内容预览: ${newChunk.substring(0, 100)}...`)
|
706 |
-
|
707 |
-
window.__streamInterceptor.sendChunk(newChunk)
|
708 |
-
lastSentLength = fullResponseText.length
|
709 |
-
|
710 |
-
// 检查是否是错误状态码的响应
|
711 |
-
if (this.status >= 400 && this.readyState === 4) {
|
712 |
-
console.log(`[Stream] progress事件中检测到HTTP错误状态码 ${this.status},立即结束流`)
|
713 |
-
finalizeStream()
|
714 |
-
return
|
715 |
-
}
|
716 |
-
|
717 |
-
// 使用精确的签名来检查流是否结束
|
718 |
-
if (FINAL_BLOCK_SIGNATURE.test(newChunk)) {
|
719 |
-
console.log('[Stream] ✅ 检测到最终 ID 签名块,确认流结束')
|
720 |
-
finalizeStream()
|
721 |
-
}
|
722 |
-
}
|
723 |
-
} catch (error) {
|
724 |
-
console.error('[Stream] 处理progress事件时出错:', error)
|
725 |
-
}
|
726 |
-
})
|
727 |
-
|
728 |
-
// 监听readystatechange事件作为备用方法
|
729 |
-
this.addEventListener('readystatechange', () => {
|
730 |
-
if (streamEnded) return
|
731 |
-
|
732 |
-
console.log(`[Stream] readyState: ${this.readyState}, status: ${this.status}`)
|
733 |
-
|
734 |
-
// readyState 3 = LOADING (部分数据可用)
|
735 |
-
// readyState 4 = DONE (请求完成)
|
736 |
-
if (this.readyState === 3 || this.readyState === 4) {
|
737 |
-
try {
|
738 |
-
const currentText = this.responseText || ''
|
739 |
-
const newChunk = currentText.slice(lastSentLength)
|
740 |
-
|
741 |
-
if (newChunk) {
|
742 |
-
console.log(`[Stream] readyState ${this.readyState} 收到数据块,长度: ${newChunk.length}`)
|
743 |
-
console.log(`[Stream] 数据块内容预览: ${newChunk.substring(0, 200)}...`)
|
744 |
-
|
745 |
-
window.__streamInterceptor.sendChunk(newChunk)
|
746 |
-
lastSentLength = currentText.length
|
747 |
-
fullResponseText = currentText
|
748 |
-
|
749 |
-
// 检查流结束签名
|
750 |
-
if (FINAL_BLOCK_SIGNATURE.test(newChunk)) {
|
751 |
-
console.log('[Stream] ✅ readyState事件中检测到最终签名')
|
752 |
-
finalizeStream()
|
753 |
-
}
|
754 |
-
}
|
755 |
-
|
756 |
-
// 如果请求完成,检查HTTP状态码
|
757 |
-
if (this.readyState === 4 && !streamEnded) {
|
758 |
-
console.log(`[Stream] 请求完成,HTTP状态码: ${this.status}`)
|
759 |
-
|
760 |
-
// 检查是否是错误状态码
|
761 |
-
if (this.status >= 400) {
|
762 |
-
console.log(`[Stream] 检测到HTTP错误状态码 ${this.status},立即处理错误响应`)
|
763 |
-
// 对于错误状态码,立即发送所有响应数据并结束流
|
764 |
-
if (fullResponseText && fullResponseText !== currentText) {
|
765 |
-
const remainingChunk = fullResponseText.slice(lastSentLength)
|
766 |
-
if (remainingChunk) {
|
767 |
-
console.log(`[Stream] 发送剩余错误响应数据: ${remainingChunk}`)
|
768 |
-
window.__streamInterceptor.sendChunk(remainingChunk)
|
769 |
-
}
|
770 |
-
}
|
771 |
-
finalizeStream()
|
772 |
-
} else if (!streamEnded) {
|
773 |
-
// 正常状态码,设置保险计时器
|
774 |
-
console.log('[Stream] 正常请求完成,设置保险计时器')
|
775 |
-
finalizationTimer = setTimeout(finalizeStream, 1000)
|
776 |
-
}
|
777 |
-
}
|
778 |
-
} catch (error) {
|
779 |
-
console.error('[Stream] 处理readystatechange事件时出错:', error)
|
780 |
-
}
|
781 |
-
}
|
782 |
-
})
|
783 |
-
|
784 |
-
this.addEventListener('load', () => {
|
785 |
-
if (streamEnded) return
|
786 |
-
console.log('[Stream] "load" 事件触发,启动最终确认计时器')
|
787 |
-
finalizationTimer = setTimeout(finalizeStream, 1500)
|
788 |
-
})
|
789 |
-
|
790 |
-
this.addEventListener('error', (e) => {
|
791 |
-
console.error('[Stream] XHR 请求出错:', e)
|
792 |
-
if (!streamEnded) finalizeStream()
|
793 |
-
})
|
794 |
-
|
795 |
-
this.addEventListener('abort', () => {
|
796 |
-
console.log('[Stream] XHR 请求被中止')
|
797 |
-
if (!streamEnded) finalizeStream()
|
798 |
-
})
|
799 |
-
}
|
800 |
-
return originalXhrSend.apply(this, args)
|
801 |
-
}
|
802 |
-
},
|
803 |
-
|
804 |
-
deactivate: () => {
|
805 |
-
if (!interceptorActive) return
|
806 |
-
console.log('🔄 停用流式拦截器...')
|
807 |
-
window.XMLHttpRequest.prototype.open = originalXhrOpen
|
808 |
-
window.XMLHttpRequest.prototype.send = originalXhrSend
|
809 |
-
interceptorActive = false
|
810 |
-
},
|
811 |
-
|
812 |
-
sendChunk: (chunk) => {
|
813 |
-
try {
|
814 |
-
console.log(`[Stream] 发送数据块到Playwright,长度: ${chunk.length}`)
|
815 |
-
// 直接调用暴露的函数
|
816 |
-
if (window.__handleStreamChunk) {
|
817 |
-
window.__handleStreamChunk(chunk)
|
818 |
-
} else {
|
819 |
-
console.error('[Stream] __handleStreamChunk 函数不存在')
|
820 |
-
}
|
821 |
-
} catch (error) {
|
822 |
-
console.error('[Stream] 发送数据块时出错:', error)
|
823 |
-
}
|
824 |
-
}
|
825 |
-
}
|
826 |
-
|
827 |
-
// 创建全局回调存储
|
828 |
-
window.__streamCallbacks = {
|
829 |
-
onChunk: null,
|
830 |
-
onEnd: null
|
831 |
-
}
|
832 |
-
|
833 |
-
// 创建处理函数
|
834 |
-
window.__handleStreamChunk = function (chunk) {
|
835 |
-
try {
|
836 |
-
console.log('[Stream] 处理数据块:', chunk.length, '字符')
|
837 |
-
if (chunk === "__END_OF_STREAM__") {
|
838 |
-
if (window.__streamCallbacks.onEnd) {
|
839 |
-
window.__streamCallbacks.onEnd()
|
840 |
-
}
|
841 |
-
} else {
|
842 |
-
if (window.__streamCallbacks.onChunk) {
|
843 |
-
window.__streamCallbacks.onChunk(chunk)
|
844 |
-
}
|
845 |
-
}
|
846 |
-
} catch (error) {
|
847 |
-
console.error('[Stream] 处理数据块时出错:', error)
|
848 |
-
}
|
849 |
-
}
|
850 |
-
|
851 |
-
console.log('[Stream] 拦截器和处理函数已创建完成')
|
852 |
-
})
|
853 |
-
|
854 |
-
// 连接回调函数(分别设置以避免参数问题)
|
855 |
-
await page.evaluate((chunkFuncName) => {
|
856 |
-
window.__streamCallbacks.onChunk = window[chunkFuncName]
|
857 |
-
console.log('[Stream] onChunk回调函数已连接:', chunkFuncName)
|
858 |
-
}, chunkFunctionName)
|
859 |
-
|
860 |
-
await page.evaluate((endFuncName) => {
|
861 |
-
window.__streamCallbacks.onEnd = window[endFuncName]
|
862 |
-
console.log('[Stream] onEnd回调函数已连接:', endFuncName)
|
863 |
-
}, endFunctionName)
|
864 |
-
|
865 |
-
info('流式拦截脚本注入完成')
|
866 |
-
} catch (error) {
|
867 |
-
info(`注入流式拦截脚本时出错: ${error.message}`)
|
868 |
-
throw error
|
869 |
-
}
|
870 |
-
}
|
871 |
-
|
872 |
-
/**
|
873 |
-
* 激活页面中的流式拦截器
|
874 |
-
* @param {Page} page - Playwright页面对象
|
875 |
-
* @returns {Promise<void>}
|
876 |
-
*/
|
877 |
-
export async function activateStreamInterceptor(page) {
|
878 |
-
try {
|
879 |
-
await page.evaluate(() => {
|
880 |
-
if (window.__streamInterceptor) {
|
881 |
-
window.__streamInterceptor.activate()
|
882 |
-
}
|
883 |
-
|
884 |
-
// 重新检查并设置处理函数(页面导航后可能被清除)
|
885 |
-
if (!window.__handleStreamChunk) {
|
886 |
-
console.log('[Stream] 重新创建 __handleStreamChunk 函数')
|
887 |
-
|
888 |
-
// 重新创建处理函数
|
889 |
-
window.__handleStreamChunk = function (chunk) {
|
890 |
-
try {
|
891 |
-
console.log('[Stream] 处理数据块:', chunk.length, '字符')
|
892 |
-
if (chunk === "__END_OF_STREAM__") {
|
893 |
-
if (window.__onStreamEnd) {
|
894 |
-
window.__onStreamEnd()
|
895 |
-
}
|
896 |
-
} else {
|
897 |
-
if (window.__onStreamChunk) {
|
898 |
-
window.__onStreamChunk(chunk)
|
899 |
-
}
|
900 |
-
}
|
901 |
-
} catch (error) {
|
902 |
-
console.error('[Stream] 处理数据块时出错:', error)
|
903 |
-
}
|
904 |
-
}
|
905 |
-
|
906 |
-
console.log('[Stream] __handleStreamChunk 函数已重新创建')
|
907 |
-
}
|
908 |
-
})
|
909 |
-
info('流式拦截器已激活')
|
910 |
-
} catch (error) {
|
911 |
-
info(`激活流式拦截器时出错: ${error.message}`)
|
912 |
-
throw error
|
913 |
-
}
|
914 |
-
}
|
915 |
-
|
916 |
-
/**
|
917 |
-
* 停用页面中的流式拦截器
|
918 |
-
* @param {Page} page - Playwright页面对象
|
919 |
-
* @returns {Promise<void>}
|
920 |
-
*/
|
921 |
-
export async function deactivateStreamInterceptor(page) {
|
922 |
-
try {
|
923 |
-
await page.evaluate(() => {
|
924 |
-
if (window.__streamInterceptor) {
|
925 |
-
window.__streamInterceptor.deactivate()
|
926 |
-
}
|
927 |
-
})
|
928 |
-
info('流式拦截器已停用')
|
929 |
-
} catch (error) {
|
930 |
-
info(`停用流式拦截器时出错: ${error.message}`)
|
931 |
-
}
|
932 |
-
}
|
933 |
-
|
934 |
-
/**
|
935 |
-
* 设置进程退出处理
|
936 |
-
*/
|
937 |
-
export function setupProcessHandlers() {
|
938 |
-
process.on('SIGINT', async () => {
|
939 |
-
console.log('正在清理资源...')
|
940 |
-
await cleanup()
|
941 |
-
process.exit(0)
|
942 |
-
})
|
943 |
-
|
944 |
-
process.on('SIGTERM', async () => {
|
945 |
-
console.log('正在清理资源...')
|
946 |
-
await cleanup()
|
947 |
-
process.exit(0)
|
948 |
-
})
|
949 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/common-utils.js
DELETED
@@ -1,104 +0,0 @@
|
|
1 |
-
import fs from 'fs';
|
2 |
-
import path from 'path';
|
3 |
-
import readline from 'readline';
|
4 |
-
import { info, error } from './logger.js';
|
5 |
-
|
6 |
-
/**
|
7 |
-
* 创建一个人类可读的时间戳字符串。
|
8 |
-
* @returns {string} 格式为 'YYYY-MM-DD_HH-MM-SS' 的时间戳。
|
9 |
-
*/
|
10 |
-
export function getHumanReadableTimestamp() {
|
11 |
-
return new Date().toISOString().replace(/T/, '_').replace(/:/g, '-').replace(/\..+/, '');
|
12 |
-
}
|
13 |
-
|
14 |
-
/**
|
15 |
-
* 确保指定的目录存在,如果不存在则创建它。
|
16 |
-
* @param {string} dir - 目录路径。
|
17 |
-
*/
|
18 |
-
export function ensureDirectoryExists(dir) {
|
19 |
-
if (!fs.existsSync(dir)) {
|
20 |
-
fs.mkdirSync(dir, { recursive: true });
|
21 |
-
info(`已创建目录: ${dir}`);
|
22 |
-
}
|
23 |
-
}
|
24 |
-
|
25 |
-
/**
|
26 |
-
* 检查 Cookie 是否可用(通过环境变量或文件)。
|
27 |
-
* @param {string} cookieFile - Cookie 文件路径。
|
28 |
-
* @param {string|undefined} cookiesFromEnv - 环境变量中的 Cookie 字符串。
|
29 |
-
* @returns {boolean} Cookie 是否可用。
|
30 |
-
*/
|
31 |
-
export function checkCookieAvailability(cookieFile, cookiesFromEnv) {
|
32 |
-
if (cookiesFromEnv) {
|
33 |
-
try {
|
34 |
-
JSON.parse(cookiesFromEnv);
|
35 |
-
info('发现并验证了环境变量中的 COOKIES。');
|
36 |
-
return true;
|
37 |
-
} catch (err) {
|
38 |
-
error('环境变量 COOKIES 格式无效 (必须是 JSON 数组字符串):', err.message);
|
39 |
-
}
|
40 |
-
}
|
41 |
-
if (fs.existsSync(cookieFile)) {
|
42 |
-
info(`发现 Cookie 文件: ${cookieFile}`);
|
43 |
-
return true;
|
44 |
-
}
|
45 |
-
error(`Cookie 文件不存在: ${cookieFile},且未设置 COOKIES 环境变量。`);
|
46 |
-
info('请先运行 `npm run login` 或设置 COOKIES 环境变量。');
|
47 |
-
return false;
|
48 |
-
}
|
49 |
-
|
50 |
-
/**
|
51 |
-
* 加载 Cookie,优先从环境变量读取,其次从文件读取。
|
52 |
-
* @param {string} cookieFile - Cookie 文件路径。
|
53 |
-
* @param {string|undefined} cookiesFromEnv - 环境变量中的 Cookie 字符串。
|
54 |
-
* @returns {object[]} Cookie 对象数组。
|
55 |
-
*/
|
56 |
-
export function loadCookies(cookieFile, cookiesFromEnv) {
|
57 |
-
try {
|
58 |
-
if (cookiesFromEnv) {
|
59 |
-
info('从环境变量 COOKIES 加载 Cookie...');
|
60 |
-
return JSON.parse(cookiesFromEnv);
|
61 |
-
}
|
62 |
-
if (fs.existsSync(cookieFile)) {
|
63 |
-
info(`从文件加载 Cookie: ${cookieFile}`);
|
64 |
-
return JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
|
65 |
-
}
|
66 |
-
} catch (err) {
|
67 |
-
error('加载 Cookie 失败:', err);
|
68 |
-
throw new Error('无法加载或解析 Cookie。');
|
69 |
-
}
|
70 |
-
return [];
|
71 |
-
}
|
72 |
-
|
73 |
-
/**
|
74 |
-
* 保存页面截图。
|
75 |
-
* @param {import('playwright').Page} page - Playwright 页面对象。
|
76 |
-
* @param {string} screenshotDir - 截图保存目录。
|
77 |
-
* @param {string} [prefix='screenshot'] - 截图文件名前缀。
|
78 |
-
* @returns {Promise<string>} 截图文件的完整路径。
|
79 |
-
*/
|
80 |
-
export async function saveScreenshot(page, screenshotDir, prefix = 'screenshot') {
|
81 |
-
ensureDirectoryExists(screenshotDir);
|
82 |
-
const timestamp = getHumanReadableTimestamp();
|
83 |
-
const screenshotPath = path.join(screenshotDir, `${prefix}_${timestamp}.png`);
|
84 |
-
await page.screenshot({ path: screenshotPath, fullPage: true });
|
85 |
-
info(`截图已保存: ${screenshotPath}`);
|
86 |
-
return screenshotPath;
|
87 |
-
}
|
88 |
-
|
89 |
-
/**
|
90 |
-
* 等待用户在控制台按下 Enter 键。
|
91 |
-
* @returns {Promise<void>}
|
92 |
-
*/
|
93 |
-
export function waitForUserInput() {
|
94 |
-
const rl = readline.createInterface({
|
95 |
-
input: process.stdin,
|
96 |
-
output: process.stdout
|
97 |
-
});
|
98 |
-
return new Promise(resolve => {
|
99 |
-
rl.question('', () => {
|
100 |
-
rl.close();
|
101 |
-
resolve();
|
102 |
-
});
|
103 |
-
});
|
104 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/logger.js
DELETED
@@ -1,90 +0,0 @@
|
|
1 |
-
import fs from 'fs';
|
2 |
-
import path from 'path';
|
3 |
-
|
4 |
-
const LogLevel = {
|
5 |
-
DEBUG: 'DEBUG',
|
6 |
-
INFO: 'INFO',
|
7 |
-
WARN: 'WARN',
|
8 |
-
ERROR: 'ERROR'
|
9 |
-
};
|
10 |
-
|
11 |
-
const LOG_CONFIG = {
|
12 |
-
logFile: './logs/app.log',
|
13 |
-
logDir: './logs',
|
14 |
-
enableConsole: true,
|
15 |
-
enableFile: true,
|
16 |
-
logLevel: process.env.LOG_LEVEL || LogLevel.INFO
|
17 |
-
};
|
18 |
-
|
19 |
-
/**
|
20 |
-
* 确保日志目录存在。
|
21 |
-
*/
|
22 |
-
function ensureLogDirectory() {
|
23 |
-
if (!fs.existsSync(LOG_CONFIG.logDir)) {
|
24 |
-
fs.mkdirSync(LOG_CONFIG.logDir, { recursive: true });
|
25 |
-
}
|
26 |
-
}
|
27 |
-
|
28 |
-
/**
|
29 |
-
* 格式化日志消息。
|
30 |
-
* @param {any[]} args - 要记录的参数。
|
31 |
-
* @returns {string} 格式化后的消息字符串。
|
32 |
-
*/
|
33 |
-
function formatMessage(...args) {
|
34 |
-
return args.map(arg =>
|
35 |
-
(typeof arg === 'object' && arg !== null) ? JSON.stringify(arg, null, 2) : String(arg)
|
36 |
-
).join(' ');
|
37 |
-
}
|
38 |
-
|
39 |
-
/**
|
40 |
-
* 将日志异步写入文件。
|
41 |
-
* @param {string} level - 日志级别。
|
42 |
-
* @param {string} message - 日志消息。
|
43 |
-
*/
|
44 |
-
async function writeToFile(level, message) {
|
45 |
-
if (!LOG_CONFIG.enableFile) return;
|
46 |
-
ensureLogDirectory();
|
47 |
-
const timestamp = new Date().toISOString();
|
48 |
-
const logEntry = `[${timestamp}] [${level}] ${message}\n`;
|
49 |
-
try {
|
50 |
-
await fs.promises.appendFile(LOG_CONFIG.logFile, logEntry);
|
51 |
-
} catch (error) {
|
52 |
-
console.error('写入日志文件失败:', error);
|
53 |
-
}
|
54 |
-
}
|
55 |
-
|
56 |
-
/**
|
57 |
-
* 将日志输出到控制台。
|
58 |
-
* @param {string} level - 日志级别。
|
59 |
-
* @param {any[]} args - 要记录的参数。
|
60 |
-
*/
|
61 |
-
function writeToConsole(level, ...args) {
|
62 |
-
if (!LOG_CONFIG.enableConsole) return;
|
63 |
-
const consoleMethod = {
|
64 |
-
[LogLevel.DEBUG]: console.debug,
|
65 |
-
[LogLevel.INFO]: console.log,
|
66 |
-
[LogLevel.WARN]: console.warn,
|
67 |
-
[LogLevel.ERROR]: console.error,
|
68 |
-
}[level] || console.log;
|
69 |
-
|
70 |
-
const timestamp = new Date().toLocaleTimeString();
|
71 |
-
consoleMethod(`[${timestamp}] [${level}]`, ...args);
|
72 |
-
}
|
73 |
-
|
74 |
-
/**
|
75 |
-
* 通用日志记录函数。
|
76 |
-
* @param {string} level - 日志级别。
|
77 |
-
* @param {any[]} args - 要记录的参数。
|
78 |
-
*/
|
79 |
-
function log(level, ...args) {
|
80 |
-
const message = formatMessage(...args);
|
81 |
-
writeToConsole(level, ...args);
|
82 |
-
writeToFile(level, message);
|
83 |
-
}
|
84 |
-
|
85 |
-
export const debug = (...args) => log(LogLevel.DEBUG, ...args);
|
86 |
-
export const info = (...args) => log(LogLevel.INFO, ...args);
|
87 |
-
export const warn = (...args) => log(LogLevel.WARN, ...args);
|
88 |
-
export const error = (...args) => log(LogLevel.ERROR, ...args);
|
89 |
-
|
90 |
-
export default { debug, info, warn, error };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/page-pool-monitor.js
DELETED
@@ -1,57 +0,0 @@
|
|
1 |
-
import { getPagePoolStatus } from './browser.js';
|
2 |
-
import { info } from './logger.js';
|
3 |
-
|
4 |
-
let monitorIntervalId = null;
|
5 |
-
|
6 |
-
/**
|
7 |
-
* 开始监控页面池状态,并定期打印到控制台。
|
8 |
-
* @param {number} [intervalMs=10000] - 监控间隔(毫秒)。
|
9 |
-
*/
|
10 |
-
export function startPagePoolMonitoring(intervalMs = 10000) {
|
11 |
-
if (monitorIntervalId) {
|
12 |
-
info('页面池监控已在运行中。');
|
13 |
-
return;
|
14 |
-
}
|
15 |
-
|
16 |
-
info(`开始监控页面池状态,间隔: ${intervalMs}ms`);
|
17 |
-
monitorIntervalId = setInterval(() => {
|
18 |
-
const status = getPagePoolStatus();
|
19 |
-
const timestamp = new Date().toLocaleTimeString();
|
20 |
-
const utilization = status.total > 0 ? ((status.busy / status.total) * 100).toFixed(1) : 0;
|
21 |
-
|
22 |
-
info(`[${timestamp}] 页面池状态: 总计=${status.total}, 可用=${status.available}, 忙碌=${status.busy}, 使用率=${utilization}%`);
|
23 |
-
}, intervalMs);
|
24 |
-
}
|
25 |
-
|
26 |
-
/**
|
27 |
-
* 停止页面池监控。
|
28 |
-
*/
|
29 |
-
export function stopPagePoolMonitoring() {
|
30 |
-
if (!monitorIntervalId) {
|
31 |
-
info('页面池监控未在运行。');
|
32 |
-
return;
|
33 |
-
}
|
34 |
-
|
35 |
-
info('停止页面池监控。');
|
36 |
-
clearInterval(monitorIntervalId);
|
37 |
-
monitorIntervalId = null;
|
38 |
-
}
|
39 |
-
|
40 |
-
/**
|
41 |
-
* 打印一次详细的当前页面池状态。
|
42 |
-
*/
|
43 |
-
export function printPagePoolStatus() {
|
44 |
-
const status = getPagePoolStatus();
|
45 |
-
const timestamp = new Date().toLocaleString();
|
46 |
-
const utilization = status.total > 0 ? ((status.busy / status.total) * 100).toFixed(1) : 0;
|
47 |
-
|
48 |
-
console.log(`
|
49 |
-
--- 页面池状态 @ ${timestamp} ---
|
50 |
-
总页面数: ${status.total}
|
51 |
-
可用页面数: ${status.available}
|
52 |
-
忙碌页面数: ${status.busy}
|
53 |
-
最大页面数: ${status.maxSize}
|
54 |
-
使用率: ${utilization}%
|
55 |
-
------------------------------------
|
56 |
-
`);
|
57 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/response-parser.js
DELETED
@@ -1,189 +0,0 @@
|
|
1 |
-
/**
|
2 |
-
* Gemini 的响应流是一种非标准的、混合了 JSON 数组和特殊分隔符的格式。
|
3 |
-
* 本解析器的目标是从这种复杂的流中稳健地提取出有意义的文本内容和其类型(思考过程或最终文本)。
|
4 |
-
*
|
5 |
-
* 策略:
|
6 |
-
* 1. **权限错误优先**:首先检查表示权限问题的特定错误消息。
|
7 |
-
* 2. **JSON 优先解析**:尝试将响应文本修复为可解析的 JSON 数组。这是最可靠的方法,因为它能访问完整的结构。
|
8 |
-
* a. **结构化类型判断**:递归地在解析后的数据结构中寻找内容块 `[null, "string", ...]`。
|
9 |
-
* - 如果该数组长度 > 2,则初步判断为 `thinking`。
|
10 |
-
* - 如果该数组长度 === 2,则初步判断为 `text`。
|
11 |
-
* b. **状态化流处理**:在解析完整个数据块后,进行一次后处理。一旦第一个 `text` 类型的块出现,其后所有的块都将被强制转换为 `text` 类型,确保输出的纯净性。
|
12 |
-
* 3. **正则回退**:如果 JSON 解析失败,则回退到正则表达式,尽力提取内容。
|
13 |
-
*/
|
14 |
-
/**
|
15 |
-
* 检查并返回权限错误。
|
16 |
-
* @param {string} responseText - 响应文本。
|
17 |
-
* @returns {{permissionError: true, content: string}|null}
|
18 |
-
*/
|
19 |
-
function getPermissionError(responseText) {
|
20 |
-
if (responseText.includes('The caller does not have permission')) {
|
21 |
-
console.warn('检测到权限错误,将触发重试机制。');
|
22 |
-
return {
|
23 |
-
permissionError: true,
|
24 |
-
content: '无权访问 AI Studio。请检查 Cookie 或登录状态。'
|
25 |
-
};
|
26 |
-
}
|
27 |
-
return null;
|
28 |
-
}
|
29 |
-
/**
|
30 |
-
* 递归地在解析后的数据中寻找内容块,并根据结构初步判断类型。
|
31 |
-
* @param {any} data - 要搜索的数据。
|
32 |
-
* @returns {Array<{type: 'thinking' | 'text', content: string}>}
|
33 |
-
*/
|
34 |
-
function findContentRecursively(data) {
|
35 |
-
const results = [];
|
36 |
-
if (!data) {
|
37 |
-
return results;
|
38 |
-
}
|
39 |
-
if (Array.isArray(data)) {
|
40 |
-
if (data.length >= 2 && data[0] === null && typeof data[1] === 'string' && data[1]) {
|
41 |
-
if (data[1] !== 'model') {
|
42 |
-
const type = data.length > 2 ? 'thinking' : 'text';
|
43 |
-
results.push({
|
44 |
-
type: type,
|
45 |
-
content: data[1].replace(/\\n/g, '\n').replace(/\\"/g, '"'),
|
46 |
-
});
|
47 |
-
}
|
48 |
-
}
|
49 |
-
for (const item of data) {
|
50 |
-
results.push(...findContentRecursively(item));
|
51 |
-
}
|
52 |
-
}
|
53 |
-
return results;
|
54 |
-
}
|
55 |
-
/**
|
56 |
-
* 解析 Gemini 响应并返回内容数组。
|
57 |
-
* @param {string} responseText - Gemini API 响应文本。
|
58 |
-
* @returns {Array<{type: 'thinking' | 'text', content: string}>|{permissionError: true, content: string}|null}
|
59 |
-
*/
|
60 |
-
export function parseGeminiResponse(responseText) {
|
61 |
-
const permissionError = getPermissionError(responseText);
|
62 |
-
if (permissionError) return permissionError;
|
63 |
-
try {
|
64 |
-
let parsableText = responseText
|
65 |
-
.trim()
|
66 |
-
.replace(/\n/g, ',') // 用逗号替换换行符
|
67 |
-
.replace(/,+/g, ','); // 处理多个逗号
|
68 |
-
if (parsableText.endsWith(',')) {
|
69 |
-
parsableText = parsableText.slice(0, -1);
|
70 |
-
}
|
71 |
-
if (!parsableText.startsWith('[')) {
|
72 |
-
parsableText = '[' + parsableText;
|
73 |
-
}
|
74 |
-
if (!parsableText.endsWith(']')) {
|
75 |
-
parsableText = parsableText + ']';
|
76 |
-
}
|
77 |
-
parsableText = parsableText.replace(/,]/g, ']').replace(/\[,/g, '[');
|
78 |
-
const data = JSON.parse(parsableText);
|
79 |
-
const contentItems = findContentRecursively(data);
|
80 |
-
if (contentItems.length > 0) {
|
81 |
-
// 后处理阶段:应用 "一旦出现 text,后续皆为 text" 规则。
|
82 |
-
// 这能确保在最终答案开始输出后,流的类型统一,避免混入 "thinking" 片段。
|
83 |
-
let hasSeenText = false;
|
84 |
-
return contentItems.map(item => {
|
85 |
-
if (hasSeenText) {
|
86 |
-
// 如果之前已出现过 'text' 类型的内容,则将当前内容也标记为 'text'。
|
87 |
-
item.type = 'text';
|
88 |
-
} else if (item.type === 'text') {
|
89 |
-
// 这是流中首次出现 'text' 类型的内容,设置标志位。
|
90 |
-
hasSeenText = true;
|
91 |
-
}
|
92 |
-
return item;
|
93 |
-
});
|
94 |
-
}
|
95 |
-
} catch (e) {
|
96 |
-
// JSON 解析失败,将进入下面的正则回退逻辑
|
97 |
-
}
|
98 |
-
// 正则回退逻辑
|
99 |
-
const contentRegex = /\[null,\s*"((?:\\"|[^"])*)"/g;
|
100 |
-
const results = [];
|
101 |
-
let match;
|
102 |
-
while ((match = contentRegex.exec(responseText)) !== null) {
|
103 |
-
try {
|
104 |
-
const content = match[1].replace(/\\n/g, '\n').replace(/\\"/g, '"');
|
105 |
-
if (content && content !== 'model') {
|
106 |
-
const type = content.trim().startsWith('**') ? 'thinking' : 'text';
|
107 |
-
results.push({ type, content });
|
108 |
-
}
|
109 |
-
} catch (err) { /* 忽略单个匹配的解析错误 */ }
|
110 |
-
}
|
111 |
-
// 对正则提取的结果也应用相同的 "once text, always text" 逻辑
|
112 |
-
if (results.length > 0) {
|
113 |
-
let hasSeenText = false;
|
114 |
-
return results.map(item => {
|
115 |
-
if (hasSeenText) {
|
116 |
-
item.type = 'text';
|
117 |
-
} else if (item.type === 'text') {
|
118 |
-
hasSeenText = true;
|
119 |
-
}
|
120 |
-
return item;
|
121 |
-
});
|
122 |
-
}
|
123 |
-
return null;
|
124 |
-
}
|
125 |
-
/**
|
126 |
-
* 创建 OpenAI 格式的流式响应块 (chunk)。
|
127 |
-
* @param {string} content - 文本内容。
|
128 |
-
* @param {'thinking' | 'text'} type - 内容的类型。
|
129 |
-
* @param {string} [model='gemini-pro'] - 模型名称。
|
130 |
-
* @returns {object}
|
131 |
-
*/
|
132 |
-
export function createStreamResponse(content, type, model = 'gemini-pro') {
|
133 |
-
return {
|
134 |
-
id: `chatcmpl-${Date.now()}`,
|
135 |
-
object: 'chat.completion.chunk',
|
136 |
-
created: Math.floor(Date.now() / 1000),
|
137 |
-
model,
|
138 |
-
choices: [{
|
139 |
-
index: 0,
|
140 |
-
delta: {
|
141 |
-
content: content || '',
|
142 |
-
type: type || 'text',
|
143 |
-
},
|
144 |
-
logprobs: null,
|
145 |
-
finish_reason: null
|
146 |
-
}]
|
147 |
-
};
|
148 |
-
}
|
149 |
-
/**
|
150 |
-
* 创建 OpenAI 格式的错误响应。
|
151 |
-
* @param {string} message - 错误消息。
|
152 |
-
* @param {string} [model='gemini-pro'] - 模型名称。
|
153 |
-
* @returns {object}
|
154 |
-
*/
|
155 |
-
export function createErrorResponse(message, model = 'gemini-pro') {
|
156 |
-
return {
|
157 |
-
object: 'error',
|
158 |
-
message,
|
159 |
-
type: 'invalid_request_error',
|
160 |
-
model,
|
161 |
-
};
|
162 |
-
}
|
163 |
-
/**
|
164 |
-
* 创建 OpenAI 格式的非流式(完整)响应。
|
165 |
-
* @param {string} content - 完整的响应内容。
|
166 |
-
* @param {string} [model='gemini-pro'] - 模型名称。
|
167 |
-
* @returns {object}
|
168 |
-
*/
|
169 |
-
export function createNonStreamResponse(content, model = 'gemini-pro') {
|
170 |
-
return {
|
171 |
-
id: `chatcmpl-${Date.now()}`,
|
172 |
-
object: 'chat.completion',
|
173 |
-
created: Math.floor(Date.now() / 1000),
|
174 |
-
model,
|
175 |
-
choices: [{
|
176 |
-
index: 0,
|
177 |
-
message: {
|
178 |
-
role: 'assistant',
|
179 |
-
content
|
180 |
-
},
|
181 |
-
finish_reason: 'stop'
|
182 |
-
}],
|
183 |
-
usage: {
|
184 |
-
prompt_tokens: 0, // 未实现
|
185 |
-
completion_tokens: 0, // 未实现
|
186 |
-
total_tokens: 0 // 未实现
|
187 |
-
}
|
188 |
-
};
|
189 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils/validation.js
DELETED
@@ -1,41 +0,0 @@
|
|
1 |
-
import { createError } from 'h3';
|
2 |
-
import config from "../config.js";
|
3 |
-
|
4 |
-
/**
|
5 |
-
* 验证聊天完成请求体,并将其转换为内部处理格式。
|
6 |
-
* @param {object} body - H3 请求体。
|
7 |
-
* @returns {{prompt: string, stream: boolean, model: string, temperature: number, messages: object[]}} 验证和格式化后的数据。
|
8 |
-
* @throws {Error} 如果验证失败,则抛出 H3 错误。
|
9 |
-
*/
|
10 |
-
export function validateChatCompletionRequest(body) {
|
11 |
-
const {
|
12 |
-
messages,
|
13 |
-
stream = false,
|
14 |
-
model = config.api.defaultModel,
|
15 |
-
temperature = config.api.temperature
|
16 |
-
} = body;
|
17 |
-
|
18 |
-
if (!messages || !Array.isArray(messages) || messages.length === 0) {
|
19 |
-
throw createError({
|
20 |
-
statusCode: 400,
|
21 |
-
statusMessage: 'Invalid request: `messages` must be a non-empty array.'
|
22 |
-
});
|
23 |
-
}
|
24 |
-
|
25 |
-
// 将消息数组转换为单个字符串 prompt,以适应 AI Studio 的单输入框模式
|
26 |
-
const prompt = messages.map(message => {
|
27 |
-
if (!message.role || !message.content) {
|
28 |
-
return '';
|
29 |
-
}
|
30 |
-
// 添加角色标签以提供上下文
|
31 |
-
return `${message.role}: ${message.content}`;
|
32 |
-
}).join('\n\n');
|
33 |
-
|
34 |
-
return {
|
35 |
-
prompt,
|
36 |
-
stream,
|
37 |
-
model,
|
38 |
-
temperature,
|
39 |
-
messages
|
40 |
-
};
|
41 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/web-server.js
DELETED
@@ -1,129 +0,0 @@
|
|
1 |
-
import { H3, serve, serveStatic } from 'h3';
|
2 |
-
import { stat, readFile } from 'node:fs/promises';
|
3 |
-
import { join } from 'node:path';
|
4 |
-
import {
|
5 |
-
setupProcessHandlers,
|
6 |
-
initPagePool,
|
7 |
-
getPageFromPool,
|
8 |
-
releasePageToPool,
|
9 |
-
handleWelcomeModal,
|
10 |
-
smartNavigate
|
11 |
-
} from './utils/browser.js';
|
12 |
-
import { startPagePoolMonitoring, printPagePoolStatus } from './utils/page-pool-monitor.js';
|
13 |
-
import { corsMiddleware } from './middlewares/cors.js';
|
14 |
-
import { healthHandler } from './routes/health.js';
|
15 |
-
import { chatCompletionsHandler } from './routes/chat-completions.js';
|
16 |
-
import { modelsHandler, modelHandler } from './routes/models.js';
|
17 |
-
import { saveScreenshot } from './utils/common-utils.js';
|
18 |
-
import config from './config.js';
|
19 |
-
import { info, error } from './utils/logger.js';
|
20 |
-
|
21 |
-
const app = new H3();
|
22 |
-
const CWD = process.cwd();
|
23 |
-
|
24 |
-
// 设置进程退出处理
|
25 |
-
setupProcessHandlers();
|
26 |
-
|
27 |
-
// 全局 CORS 中间件
|
28 |
-
app.use('*', corsMiddleware);
|
29 |
-
|
30 |
-
// --- API 端点 ---
|
31 |
-
// 健康检查端点
|
32 |
-
app.get('/health', healthHandler);
|
33 |
-
|
34 |
-
// 模型相关端点
|
35 |
-
app.get('/v1/models', modelsHandler);
|
36 |
-
app.get('/v1/models/:model', modelHandler);
|
37 |
-
|
38 |
-
// 主要的聊天完成端点
|
39 |
-
app.post('/v1/chat/completions', chatCompletionsHandler);
|
40 |
-
|
41 |
-
// --- 静态文件服务 (必须在 API 端点之后) ---
|
42 |
-
// 处理 screenshots 目录
|
43 |
-
app.get('/screenshots/**', (event) => {
|
44 |
-
// event.path is like /screenshots/foo.png
|
45 |
-
const assetPath = event.path.substring('/screenshots'.length);
|
46 |
-
const filePath = join(CWD, 'screenshots', assetPath);
|
47 |
-
return serveStatic(event, {
|
48 |
-
getContents: () => readFile(filePath),
|
49 |
-
getMeta: async () => {
|
50 |
-
const stats = await stat(filePath).catch(() => {});
|
51 |
-
if (stats?.isFile()) return { size: stats.size, mtime: stats.mtimeMs };
|
52 |
-
}
|
53 |
-
});
|
54 |
-
});
|
55 |
-
|
56 |
-
// 处理 public 目录 (作为其他所有 GET 请求的兜底)
|
57 |
-
app.get('/**', (event) => {
|
58 |
-
const assetPath = event.path === '/' ? 'index.html' : event.path;
|
59 |
-
const filePath = join(CWD, 'public', assetPath);
|
60 |
-
return serveStatic(event, {
|
61 |
-
getContents: () => readFile(filePath),
|
62 |
-
getMeta: async () => {
|
63 |
-
const stats = await stat(filePath).catch(() => {});
|
64 |
-
if (stats?.isFile()) return { size: stats.size, mtime: stats.mtimeMs };
|
65 |
-
}
|
66 |
-
});
|
67 |
-
});
|
68 |
-
|
69 |
-
|
70 |
-
// 初始化页面池
|
71 |
-
info('🔧 初始化页面池...');
|
72 |
-
initPagePool(5); // 最大5个页面
|
73 |
-
|
74 |
-
// 启动页面池监控(开发环境)
|
75 |
-
if (process.env.NODE_ENV !== 'production') {
|
76 |
-
info('📊 启动页面池监控...');
|
77 |
-
startPagePoolMonitoring(10000); // 每10秒监控一次
|
78 |
-
}
|
79 |
-
|
80 |
-
// 启动服务器
|
81 |
-
const port = config.server.port;
|
82 |
-
const host = config.server.host;
|
83 |
-
serve(app, { port, host });
|
84 |
-
|
85 |
-
info(`🚀 服务器运行在 http://${host}:${port}`);
|
86 |
-
info(`🏠 管理面板: http://${host}:${port}/`);
|
87 |
-
info(`📋 健康检查: http://${host}:${port}/health`);
|
88 |
-
info(`💬 聊天端点: http://${host}:${port}/v1/chat/completions`);
|
89 |
-
info(`🎯 AI Studio URL: ${config.aiStudio.url}`);
|
90 |
-
info(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
|
91 |
-
|
92 |
-
// 截图AI Studio页面的函数
|
93 |
-
async function captureAIStudioScreenshot() {
|
94 |
-
let page;
|
95 |
-
try {
|
96 |
-
info('📸 开始获取AI Studio页面截图...');
|
97 |
-
page = await getPageFromPool();
|
98 |
-
|
99 |
-
info(`🌐 智能导航到: ${config.aiStudio.url}`);
|
100 |
-
await smartNavigate(page, config.aiStudio.url, {
|
101 |
-
timeout: config.aiStudio.pageTimeout
|
102 |
-
});
|
103 |
-
|
104 |
-
await handleWelcomeModal(page);
|
105 |
-
await page.waitForTimeout(2000);
|
106 |
-
|
107 |
-
const screenshotPath = await saveScreenshot(page, './screenshots', 'aistudio-startup');
|
108 |
-
info(`✅ AI Studio截图已保存: ${screenshotPath}`);
|
109 |
-
|
110 |
-
} catch (err) {
|
111 |
-
error('❌ 截图AI Studio页面时出错:', err.message);
|
112 |
-
} finally {
|
113 |
-
if (page) {
|
114 |
-
await releasePageToPool(page);
|
115 |
-
info('🔄 页面已释放回池中');
|
116 |
-
}
|
117 |
-
}
|
118 |
-
}
|
119 |
-
|
120 |
-
// 打印初始页面池状态
|
121 |
-
setTimeout(() => {
|
122 |
-
info('\n📊 初始页面池状态:');
|
123 |
-
printPagePoolStatus();
|
124 |
-
}, 1000);
|
125 |
-
|
126 |
-
// 启动后截图AI Studio页面
|
127 |
-
setTimeout(() => {
|
128 |
-
captureAIStudioScreenshot();
|
129 |
-
}, 2000);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|