lazycodex-ai 5.1.64 → 5.1.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +98 -60
- package/dist/cli/service-auth/closed-device-login.d.ts +16 -0
- package/dist/cli/service-auth/commands.d.ts +9 -2
- package/dist/cli/service-auth/session.d.ts +12 -0
- package/dist/cli-node/index.js +98 -60
- package/package.json +1 -1
- package/packages/omo-codex/plugin/.codex-plugin/plugin.json +1 -1
- package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +19 -0
- package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
- package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/comment-checker/package.json +1 -1
- package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
- package/packages/omo-codex/plugin/components/git-bash/package.json +1 -1
- package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +1 -1
- package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +2 -2
- package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
- package/packages/omo-codex/plugin/components/lsp/package.json +1 -1
- package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
- package/packages/omo-codex/plugin/components/rules/package.json +1 -1
- package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/teammode/package.json +1 -1
- package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/telemetry/package.json +1 -1
- package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/ultrawork/package.json +1 -1
- package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/ulw-execute-continuation/package.json +1 -1
- package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +5 -5
- package/packages/omo-codex/plugin/components/ulw-loop/package.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +1 -1
- package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
- package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
- package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
- package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +1 -1
- package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
- package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
- package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
- package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
- package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
- package/packages/omo-codex/plugin/package-lock.json +12 -12
- package/packages/omo-codex/plugin/package.json +1 -1
- package/packages/omo-codex/plugin/skills/browser/SKILL.md +3 -1
- package/packages/omo-codex/plugin/skills/browser/runtime/omowright/index.js +232 -341
- package/packages/omo-codex/plugin/skills/browser/runtime/omowright/manifest.json +5 -5
- package/packages/omo-codex/plugin/skills/browser/runtime/omowright/page-bundle.js +1586 -1394
- package/packages/omo-codex/plugin/skills/browser/scripts/browser-doctor-report.mjs +68 -0
- package/packages/omo-codex/plugin/skills/browser/scripts/browser-doctor.mjs +8 -43
- package/packages/omo-codex/plugin/skills/browser/scripts/omowright.mjs +7 -1
- package/packages/omo-codex/scripts/install-dist/install-local.mjs +21 -2
- package/packages/shared-skills/skills/browser/SKILL.md +3 -1
- package/packages/shared-skills/skills/browser/runtime/omowright/index.js +232 -341
- package/packages/shared-skills/skills/browser/runtime/omowright/manifest.json +5 -5
- package/packages/shared-skills/skills/browser/runtime/omowright/page-bundle.js +1586 -1394
- package/packages/shared-skills/skills/browser/scripts/browser-doctor-report.mjs +68 -0
- package/packages/shared-skills/skills/browser/scripts/browser-doctor.mjs +8 -43
- package/packages/shared-skills/skills/browser/scripts/omowright.mjs +7 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=createRequire(import.meta.url);var require_constants=__commonJS(function(exports,module){var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS(function(exports,module){var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil");})();module.exports.mask=function(source,mask2,output,offset,length){if(length<48)_mask(source,mask2,output,offset,length);else bufferUtil.mask(source,mask2,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}});var require_limiter=__commonJS(function(exports,module){var kDone=Symbol("kDone");var kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS(function(exports,module){var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;class PerMessageDeflate{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data=new FastBuffer(data.buffer,data.byteOffset,data.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}});var require_validation=__commonJS(function(exports,module){var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}});var require_receiver=__commonJS(function(exports,module){var{Writable}=__require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==undefined?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}}module.exports=Receiver});var require_sender=__commonJS(function(exports,module){var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=undefined}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===undefined){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==undefined){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===undefined){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===undefined||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}});var require_event_target=__commonJS(function(exports,module){var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===undefined?0:options.code;this[kReason]=options.reason===undefined?"":options.reason;this[kWasClean]=options.wasClean===undefined?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===undefined?null:options.error;this[kMessage]=options.message===undefined?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===undefined?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}});var require_extension=__commonJS(function(exports,module){var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===undefined)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}paramName=undefined;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===undefined){push(offers,token,params)}else{if(paramName===undefined){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS(function(exports,module){var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver=require_receiver();var Sender=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===undefined){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:true})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:undefined,hostname:undefined,protocol:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} `+`(supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", `+'"http:", "https:", or "ws+unix:"'}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request3=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key,value]of Object.entries(headers)){options.headers[key.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=undefined}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request3(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request3(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",(res)=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==undefined){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==undefined){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=undefined;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} `+`(${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===undefined)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==undefined){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN){websocket._readyState=WebSocket.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=undefined;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket.CLOSING;this.destroy()}}});var require_stream=__commonJS(function(exports,module){var WebSocket=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err){called=true;callback(err)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS(function(exports,module){var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol=header.slice(start,end);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse}});var require_websocket_server=__commonJS(function(exports,module){var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension=require_extension();var PerMessageDeflate=require_permessage_deflate();var subprotocol=require_subprotocol();var WebSocket=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;class WebSocketServer extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options '+"must be specified")}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===undefined||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==undefined){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==undefined){const perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,undefined,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat(`\r
|
|
1
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import path from"node:path";async function openNtdll(){const{dlopen,ptr}=await import("bun:ffi");const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";const{symbols}=dlopen(path.win32.join(systemRoot,"System32","ntdll.dll"),{NtCreateFile:{args:["buffer","u32","buffer","buffer","ptr","u32","u32","u32","u32","ptr","u32"],returns:"u32"},NtClose:{args:["u64"],returns:"u32"},RtlNtStatusToDosError:{args:["u32"],returns:"u32"}});return{symbols,ptr}}function loadNtdll(){ntdll??=openNtdll().catch((error)=>{ntdll=undefined;throw error});return ntdll}function nativeError(symbols,operation,lockPath,status){const error=symbols.RtlNtStatusToDosError(status);return Object.assign(new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),{code:"ERR_INSTANCE_LOCK"})}async function tryAcquireWindows(lockPath){const{symbols,ptr}=await loadNtdll();const filename=Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/,"\\??\\")}\x00`,"utf16le");const name=Buffer.alloc(16);name.writeUInt16LE(filename.length-2,0);name.writeUInt16LE(filename.length,2);name.writeBigUInt64LE(BigInt(ptr(filename)),8);const attributes=Buffer.alloc(48);attributes.writeUInt32LE(48,0);attributes.writeBigUInt64LE(BigInt(ptr(name)),16);attributes.writeUInt32LE(64,24);const handleOut=Buffer.alloc(8);const ioStatus=Buffer.alloc(16);const status=symbols.NtCreateFile(handleOut,3222274048,attributes,ioStatus,null,128,0,3,96,null,0);if(status===3221225539)return null;if(status>=2147483648)throw nativeError(symbols,"NtCreateFile",lockPath,status);const handle=handleOut.readBigUInt64LE();return{release(){const closeStatus=symbols.NtClose(handle);if(closeStatus>=2147483648)throw nativeError(symbols,"NtClose",lockPath,closeStatus)}}}var ntdll;var init_lock_backend_win32_xbcm60vz=()=>{};import{createRequire}from"node:module";import path3 from"node:path";import{mkdir as mkdir4}from"node:fs/promises";import path2 from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream,promises}from"node:fs";import*as fs$16 from"node:fs/promises";import{spawn}from"node:child_process";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";import{readFile}from"node:fs/promises";import{readFile as readFile2}from"node:fs/promises";import{randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{mkdir as mkdir3,writeFile as writeFile2}from"node:fs/promises";import path22 from"node:path";import{spawn as spawn3}from"node:child_process";import{finished}from"node:stream/promises";import{mkdirSync,readFileSync as readFileSync2,rmSync,writeFileSync}from"node:fs";import path5 from"node:path";import{setTimeout as sleep2}from"node:timers/promises";import{unlink as unlink2}from"node:fs/promises";import{setTimeout as sleep}from"node:timers/promises";import{spawn as spawn2}from"node:child_process";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{execFile}from"node:child_process";import{readFile as readFile3}from"node:fs/promises";import path4 from"node:path";import{promisify}from"node:util";import{spawn as spawn4}from"node:child_process";import{createHash,randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir5,open as open3,readFile as readFile6,readdir,rename,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path8 from"node:path";import{watch}from"node:fs";import{readFile as readFile4,stat}from"node:fs/promises";import path6 from"node:path";import{execFile as execFile2}from"node:child_process";import{chmod,mkdtemp,readFile as readFile5,rm,stat as stat2}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";import{promisify as promisify2}from"node:util";import{readFile as readFile7}from"node:fs/promises";import{connect as connectTcp}from"node:net";import path10 from"node:path";import{existsSync}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";import{randomInt}from"node:crypto";import{mkdir as mkdir6,open as open4,readFile as readFile8,unlink as unlink4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path11 from"node:path";import{spawn as spawn5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path12 from"node:path";import{randomUUID as randomUUID3}from"node:crypto";import path16 from"node:path";import{mkdir as mkdir8,open as open5,readFile as readFile9,readlink,realpath,rename as rename2,lstat,chmod as chmod2}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync as mkdirSync2}from"node:fs";import path14 from"node:path";import{tmpdir as tmpdir4}from"node:os";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import path13 from"node:path";import{execFile as execFile3}from"node:child_process";import{existsSync as existsSync3}from"node:fs";import{mkdir as mkdir7,rmdir,unlink as unlink5}from"node:fs/promises";import path15 from"node:path";import{mkdir as mkdir9,writeFile as writeFile3}from"node:fs/promises";import path17 from"node:path";import{connect as connect2}from"node:net";import{existsSync as existsSync5,readdirSync}from"node:fs";import path19 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path18 from"node:path";import{spawn as spawn6}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{spawn as spawnChild}from"node:child_process";import{randomBytes as randomBytes2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync6}from"node:fs";import{homedir as homedir6}from"node:os";import path222 from"node:path";import{spawn as spawn8}from"node:child_process";import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir4}from"node:os";import path20 from"node:path";import{spawn as spawn7}from"node:child_process";import{existsSync as existsSync7}from"node:fs";import{homedir as homedir5}from"node:os";import path21 from"node:path";import{randomInt as randomInt2}from"node:crypto";import{existsSync as existsSync9,mkdirSync as mkdirSync3,readFileSync as readFileSync7,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{spawn as spawn9}from"node:child_process";import path23 from"node:path";import{execFile as execFile4}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir7}from"node:os";import path24 from"node:path";import{homedir as homedir8}from"node:os";import{existsSync as existsSync10,readFileSync as readFileSync8}from"node:fs";var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var __require=createRequire(import.meta.url);var require_constants=__commonJS(function(exports,module){var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS(function(exports,module){var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil")})();module.exports.mask=function(source,mask2,output,offset,length){if(length<48)_mask(source,mask2,output,offset,length);else bufferUtil.mask(source,mask2,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}});var require_limiter=__commonJS(function(exports,module){var kDone=Symbol("kDone");var kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS(function(exports,module){var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;class PerMessageDeflate{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data=new FastBuffer(data.buffer,data.byteOffset,data.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}});var require_validation=__commonJS(function(exports,module){var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate")})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}});var require_receiver=__commonJS(function(exports,module){var{Writable}=__require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==undefined?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}}module.exports=Receiver});var require_sender=__commonJS(function(exports,module){var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=undefined}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===undefined){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==undefined){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===undefined){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===undefined||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}});var require_event_target=__commonJS(function(exports,module){var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===undefined?0:options.code;this[kReason]=options.reason===undefined?"":options.reason;this[kWasClean]=options.wasClean===undefined?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===undefined?null:options.error;this[kMessage]=options.message===undefined?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===undefined?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}});var require_extension=__commonJS(function(exports,module){var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===undefined)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}paramName=undefined;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===undefined){push(offers,token,params)}else{if(paramName===undefined){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS(function(exports,module){var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver=require_receiver();var Sender=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===undefined){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:true})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:undefined,hostname:undefined,protocol:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} `+`(supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", `+'"http:", "https:", or "ws+unix:"'}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request3=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key,value]of Object.entries(headers)){options.headers[key.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=undefined}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request3(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request3(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",(res)=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==undefined){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==undefined){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=undefined;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} `+`(${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===undefined)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==undefined){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN){websocket._readyState=WebSocket.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=undefined;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket.CLOSING;this.destroy()}}});var require_stream=__commonJS(function(exports,module){var WebSocket=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err){called=true;callback(err)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS(function(exports,module){var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol=header.slice(start,end);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse}});var require_websocket_server=__commonJS(function(exports,module){var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension=require_extension();var PerMessageDeflate=require_permessage_deflate();var subprotocol=require_subprotocol();var WebSocket=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;class WebSocketServer extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options '+"must be specified")}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===undefined||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==undefined){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==undefined){const perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,undefined,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat(`\r
|
|
2
2
|
`).join(`\r
|
|
3
3
|
`));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}}module.exports=WebSocketServer;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
4
4
|
`+Object.keys(headers).map((h)=>`${h}: ${headers[h]}`).join(`\r
|
|
5
5
|
`)+`\r
|
|
6
6
|
\r
|
|
7
|
-
`+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){const err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message,headers)}}});var targetCreationCapability;var init_internal_capability=__esm(()=>{targetCreationCapability=Symbol("omowright.targetCreationCapability")});function validateViewport(viewport){if(!viewport||!Number.isInteger(viewport.width)||viewport.width<=0||!Number.isInteger(viewport.height)||viewport.height<=0)throw new TypeError("viewport width and height must be positive integers");return{width:viewport.width,height:viewport.height}}async function repinViewport(page,viewport,options={}){const size=validateViewport(viewport);const sessionId=await page.resolveSessionId();await page.cdp.send("Emulation.setDeviceMetricsOverride",{...size,deviceScaleFactor:options.deviceScaleFactor??1,mobile:options.mobile??false},sessionId);page.setCachedViewportSize(size);return{...size}}var DEFAULT_AGENT_VIEWPORT;var init_viewport=__esm(()=>{DEFAULT_AGENT_VIEWPORT=Object.freeze({width:1440,height:900})});function optionsKey(options={}){return JSON.stringify({viewport:{...DEFAULT_AGENT_VIEWPORT,...options.viewport??{}},closeTimeoutMs:options.closeTimeoutMs??5000})}class AgentTabManager{#connection;#owned=new Map;#unsubscribers=[];#disposed=false;#closing=new Map;viewport;closeTimeoutMs;ready;constructor(connection,options={}){if(!connection?.cdp)throw new TypeError("createAgentTabs requires a browser connection");this.#connection=connection;this.viewport=Object.freeze({...DEFAULT_AGENT_VIEWPORT,...options.viewport??{}});this.closeTimeoutMs=options.closeTimeoutMs??5000;this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected",()=>{for(const id of[...this.#owned.keys()])this.#destroyed(id,Error("Browser transport disconnected"))}));this.ready=Promise.resolve(connection.cdp.ensureConnected?.())}async create(url="about:blank",options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");await this.ready;const viewport={...this.viewport,...options.viewport??{}};const result=await this.#connection.cdp.send("Target.createTarget",{url,background:true},undefined,{capability:CAPABILITY});const targetId=result.targetId;if(await this.#isHeadless())await this.#connection.cdp.send("Target.activateTarget",{targetId});const record={targetId,page:null,viewport:Object.freeze({...viewport}),repinQueue:Promise.resolve()};this.#owned.set(targetId,record);try{record.page=await this.#connection.attachPage(targetId);await repinViewport(record.page,record.viewport);record.navigationOff=record.page.on?.("framenavigated",(event)=>{if(!event.parentFrameId)this.#repin(record)});return this.#public(record)}catch(error){await this.#connection.cdp.send("Target.closeTarget",{targetId}).catch(()=>{});throw error}}#public(record){return Object.freeze({targetId:record.targetId,page:record.page,viewport:{...record.viewport},close:(options)=>this.close(record.targetId,options)})}get(targetId){const record=this.#owned.get(targetId);return record?this.#public(record):null}list(){return[...this.#owned.values()].map((record)=>this.#public(record))}async#isHeadless(){if(typeof this.#connection.cdp.isHeadless==="boolean")return this.#connection.cdp.isHeadless;const version=await this.#connection.cdp.send("Browser.getVersion").catch(()=>null);return/Headless/i.test(version?.product??"")}#queueRepin(record,viewport,reportErrors=false){const size={...viewport};const operation=record.repinQueue.then(async()=>{try{await repinViewport(record.page,size)}catch(error){if(reportErrors)console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`,error);else throw error}record.viewport=Object.freeze(size);return{...size}});record.repinQueue=operation.catch(()=>{});return operation}async#repin(record){await this.#queueRepin(record,record.viewport,true)}async repin(tabOrTargetId,viewport=this.viewport){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=this.#owned.get(id);if(!record)throw Error(`Target ${id} is not owned by this manager`);return this.#queueRepin(record,viewport)}async close(tabOrTargetId,options={}){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=this.#owned.get(id);if(!record)throw Error(`Target ${id} is not owned by this manager`);const existing=this.#closing.get(id);if(existing)return existing.promise;let resolveOperation,rejectOperation;const promise=new Promise((resolve,reject)=>{resolveOperation=resolve;rejectOperation=reject});const entry={promise,reject:rejectOperation};this.#closing.set(id,entry);this.#close(record,options).then(resolveOperation,rejectOperation).finally(()=>{if(this.#closing.get(id)===entry)this.#closing.delete(id)});return promise}async#close(record,options){let resolveDestroy,rejectDestroy;const destroyed=new Promise((resolve,reject)=>{resolveDestroy=resolve;rejectDestroy=reject});const timeout=setTimeout(()=>rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)),options.timeoutMs??this.closeTimeoutMs);const off=this.#connection.cdp.on("Target.targetDestroyed",(info)=>{if(info?.targetId===record.targetId)resolveDestroy()});const offDisconnect=this.#connection.cdp.transportEvents?.on?.("disconnected",()=>rejectDestroy(Error("Browser transport disconnected")));try{if(options.runBeforeUnload&&record.page)await record.page.cdp.send("Page.close",undefined,await record.page.resolveSessionId()).catch(()=>this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId}));else await this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId});if(this.#owned.has(record.targetId))await destroyed}finally{clearTimeout(timeout);off();offDisconnect?.();if(!this.#owned.has(record.targetId))record.navigationOff?.()}}#destroyed(id,error){const record=this.#owned.get(id);if(!record)return;record.navigationOff?.();this.#owned.delete(id);if(error)this.#closing.get(id)?.reject(error)}async closeAll(options={}){const results=await Promise.allSettled([...this.#owned.keys()].map((id)=>this.close(id,options)));const failures=results.filter((result)=>result.status==="rejected").map((result)=>result.reason);if(failures.length)throw new AggregateError(failures,"Failed to close one or more agent tabs")}async dispose(options={closeOwned:true}){if(this.#disposed)return;let failure;if(options.closeOwned!==false)try{await this.closeAll(options)}catch(error){failure=error}this.#disposed=true;for(const off of this.#unsubscribers)off();this.#unsubscribers=[];if(failure)throw failure}}function createAgentTabs(connection,options={}){const current=managers.get(connection);if(current){if(current._optionsKey!==optionsKey(options))throw new TypeError("Conflicting AgentTabManager options");return current}const manager=new AgentTabManager(connection,options);Object.defineProperty(manager,"_optionsKey",{value:optionsKey(options)});managers.set(connection,manager);return manager}var managers,CAPABILITY;var init_agent_tabs=__esm(()=>{init_viewport();init_internal_capability();managers=new WeakMap;CAPABILITY=targetCreationCapability});var exports_zod={};__export(exports_zod,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>exports_coerce,compile:()=>compile,config:()=>config,core:()=>exports_core2,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,decode:()=>decode2,decodeAsync:()=>decodeAsync2,deepPartial:()=>deepPartial,default:()=>exports_external,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode2,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getDiscriminatedOption:()=>getDiscriminatedOption,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,includes:()=>_includes,input:()=>input,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>exports_iso,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>exports_locales,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,memoizer:()=>memoizer,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,output:()=>output,overwrite:()=>_overwrite,parse:()=>parse3,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,properties:()=>_properties,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>exports_regexes,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,toZod:()=>toZod,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>exports_util,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,validate:()=>validate,validateAsync:()=>validateAsync,void:()=>_void2,withParser:()=>withParser,xid:()=>xid2,xor:()=>xor,z:()=>exports_external});var exports_external={};__export(exports_external,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>exports_coerce,compile:()=>compile,config:()=>config,core:()=>exports_core2,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,decode:()=>decode2,decodeAsync:()=>decodeAsync2,deepPartial:()=>deepPartial,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode2,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getDiscriminatedOption:()=>getDiscriminatedOption,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,includes:()=>_includes,input:()=>input,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>exports_iso,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>exports_locales,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,memoizer:()=>memoizer,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,output:()=>output,overwrite:()=>_overwrite,parse:()=>parse3,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,properties:()=>_properties,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>exports_regexes,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,toZod:()=>toZod,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>exports_util,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,validate:()=>validate,validateAsync:()=>validateAsync,void:()=>_void2,withParser:()=>withParser,xid:()=>xid2,xor:()=>xor});var exports_core2={};__export(exports_core2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperties:()=>$ZodCheckProperties,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCreditCard:()=>$ZodCreditCard,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCyclicError:()=>$ZodCyclicError,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIBAN:()=>$ZodIBAN,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,INVALID:()=>INVALID,JSONSchema:()=>exports_json_schema,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,URL_BAD_FORMAT:()=>URL_BAD_FORMAT,URL_UNPARSEABLE:()=>URL_UNPARSEABLE,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_creditCard:()=>_creditCard,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_iban:()=>_iban,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_properties:()=>_properties,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,base64Charset:()=>base64Charset,base64urlCharset:()=>base64urlCharset,canParseURL:()=>canParseURL,clone:()=>clone,compile:()=>compile,compileFn:()=>compileFn,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,getDiscriminatedOption:()=>getDiscriminatedOption,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,handleUnrepresentable:()=>handleUnrepresentable,initializeContext:()=>initializeContext,isBackEdge:()=>isBackEdge,isRecursiveSchema:()=>isRecursiveSchema,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidCIDRv6:()=>isValidCIDRv6,isValidCreditCard:()=>isValidCreditCard,isValidIBAN:()=>isValidIBAN,isValidIPv6:()=>isValidIPv6,isValidJWT:()=>isValidJWT,locales:()=>exports_locales,memoizer:()=>memoizer,mergeValues:()=>mergeValues,meta:()=>meta,parse:()=>parse,parseAsync:()=>parseAsync,parseURLObject:()=>parseURLObject,prettifyError:()=>prettifyError,process:()=>processSchema,processSchema:()=>processSchema,regexes:()=>exports_regexes,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,standardProps:()=>standardProps,stripTabAndNewline:()=>stripTabAndNewline,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,toZod:()=>toZod,treeifyError:()=>treeifyError,urlHostnameOk:()=>urlHostnameOk,urlProtocolOk:()=>urlProtocolOk,util:()=>exports_util,validate:()=>validate,validateAsync:()=>validateAsync,validateURL:()=>validateURL,version:()=>version,withParser:()=>withParser});var exports_util={};__export(exports_util,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,CONSTANT_CATCH:()=>CONSTANT_CATCH,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,attachSchema:()=>attachSchema,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,codePointLength:()=>codePointLength,constantCatch:()=>constantCatch,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,defineLazyInternal:()=>defineLazyInternal,derived:()=>derived,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,hide:()=>hide,installLazyProp:()=>installLazyProp,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,members:()=>members,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,own:()=>own,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,rawShape:()=>rawShape,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,toZod:()=>toZod,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});var exports_regexes={};__export(exports_regexes,{anyString:()=>anyString,base64:()=>base64,base64url:()=>base64url,bigint:()=>bigint,boolean:()=>boolean,browserEmail:()=>browserEmail,cidrv4:()=>cidrv4,cidrv6:()=>cidrv6,creditCard:()=>creditCard,cuid:()=>cuid,cuid2:()=>cuid2,currencyCode:()=>currencyCode,date:()=>date,datetime:()=>datetime,domain:()=>domain,duration:()=>duration,e164:()=>e164,email:()=>email,emoji:()=>emoji,extendedDuration:()=>extendedDuration,guid:()=>guid,hex:()=>hex,hostname:()=>hostname,html5Email:()=>html5Email,httpProtocol:()=>httpProtocol,iban:()=>iban,idnEmail:()=>idnEmail,integer:()=>integer,ipv4:()=>ipv4,ipv6:()=>ipv6,ksuid:()=>ksuid,lowercase:()=>lowercase,mac:()=>mac,md5_base64:()=>md5_base64,md5_base64url:()=>md5_base64url,md5_hex:()=>md5_hex,nanoid:()=>nanoid,nanoidOfLength:()=>nanoidOfLength,null:()=>_null,number:()=>number,rfc5322Email:()=>rfc5322Email,sha1_base64:()=>sha1_base64,sha1_base64url:()=>sha1_base64url,sha1_hex:()=>sha1_hex,sha256_base64:()=>sha256_base64,sha256_base64url:()=>sha256_base64url,sha256_hex:()=>sha256_hex,sha384_base64:()=>sha384_base64,sha384_base64url:()=>sha384_base64url,sha384_hex:()=>sha384_hex,sha512_base64:()=>sha512_base64,sha512_base64url:()=>sha512_base64url,sha512_hex:()=>sha512_hex,string:()=>string,time:()=>time,ulid:()=>ulid,undefined:()=>_undefined,unicodeEmail:()=>unicodeEmail,uppercase:()=>uppercase,uuid:()=>uuid,uuid4:()=>uuid4,uuid6:()=>uuid6,uuid7:()=>uuid7,xid:()=>xid});var exports_locales={};__export(exports_locales,{ar:()=>ar_default,az:()=>az_default,be:()=>be_default,bg:()=>bg_default,bn:()=>bn_default,ca:()=>ca_default,ckb:()=>ckb_default,cs:()=>cs_default,da:()=>da_default,de:()=>de_default,el:()=>el_default,en:()=>en_default,eo:()=>eo_default,es:()=>es_default,fa:()=>fa_default,fi:()=>fi_default,fr:()=>fr_default,frCA:()=>fr_CA_default,gu:()=>gu_default,he:()=>he_default,hi:()=>hi_default,hr:()=>hr_default,hu:()=>hu_default,hy:()=>hy_default,id:()=>id_default,is:()=>is_default,it:()=>it_default,ja:()=>ja_default,ka:()=>ka_default,kh:()=>kh_default,km:()=>km_default,kn:()=>kn_default,ko:()=>ko_default,lt:()=>lt_default,mk:()=>mk_default,ms:()=>ms_default,ne:()=>ne_default,nl:()=>nl_default,nn:()=>nn_default,no:()=>no_default,ota:()=>ota_default,pl:()=>pl_default,ps:()=>ps_default,pt:()=>pt_default,ptBR:()=>pt_BR_default,ro:()=>ro_default,ru:()=>ru_default,sk:()=>sk_default,sl:()=>sl_default,sv:()=>sv_default,ta:()=>ta_default,tg:()=>tg_default,th:()=>th_default,tk:()=>tk_default,tr:()=>tr_default,ua:()=>ua_default,uk:()=>uk_default,ur:()=>ur_default,uz:()=>uz_default,vi:()=>vi_default,yo:()=>yo_default,zhCN:()=>zh_CN_default,zhTW:()=>zh_TW_default});var exports_json_schema={};var exports_schemas2={};__export(exports_schemas2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var exports_checks2={};__export(exports_checks2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var exports_iso={};__export(exports_iso,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});var exports_coerce={};__export(exports_coerce,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});import path2 from"node:path";import{mkdir as mkdir2}from"node:fs/promises";var import_stream=__toESM(require_stream(),1);var import_extension=__toESM(require_extension(),1);var import_permessage_deflate=__toESM(require_permessage_deflate(),1);var import_receiver=__toESM(require_receiver(),1);var import_sender=__toESM(require_sender(),1);var import_subprotocol=__toESM(require_subprotocol(),1);var import_websocket=__toESM(require_websocket(),1);var import_websocket_server=__toESM(require_websocket_server(),1);var wrapper_default=import_websocket.default;function assertEqual(val){return val}function assertNotEqual(val){return val}function toZod(){return(schema)=>schema}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){const numericValues=Object.values(entries).filter((v)=>typeof v==="number");const values=Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v);return values}function joinValues(array,separator="|"){return array.map((val)=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){if(typeof value==="bigint")return value.toString();return value}class Cached{constructor(getter){this._getter=getter;this._value=undefined}get value(){const getter=this._getter;if(getter!==undefined){this._value=getter();this._getter=undefined}return this._value}}function cached(getter){return new Cached(getter)}function nullish(input){return input===null||input===undefined}function cleanRegex(source){const start=source.startsWith("^")?1:0;const end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){const ratio=val/step;const roundedRatio=Math.round(ratio);const tolerance=4*Number.EPSILON*Math.max(Math.abs(ratio),1);if(Math.abs(ratio-roundedRatio)<tolerance)return 0;return ratio-roundedRatio}var EVALUATING=Symbol("evaluating");function defineLazy(object,key,getter){let value=undefined;Object.defineProperty(object,key,{get(){if(value===EVALUATING){return}if(value===undefined){value=EVALUATING;value=getter()}return value},set(v){Object.defineProperty(object,key,{value:v})},configurable:true})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:true,enumerable:true,configurable:true})}function rawShape(def){const desc=Object.getOwnPropertyDescriptor(def,"shape");return desc?.get?desc.get.raw:desc?.value}function sourceShape(schema){return rawShape(schema._zod.def)??schema._zod.def.shape}function deferProp(target,key,getter){Object.defineProperty(target,key,{get(){const value=getter();assignProp(this,key,value);return value},enumerable:true,configurable:true})}function putProp(target,key,value){if(key in target)assignProp(target,key,value);else target[key]=value}function mirrorShape(target,source,keys,wrap){const raw=sourceShape(source);for(const key of keys){const desc=Object.getOwnPropertyDescriptor(raw,key);if(!desc.enumerable)continue;if(desc.get){deferProp(target,key,()=>{const value=source._zod.def.shape[key];return wrap?wrap(value,key):value})}else putProp(target,key,wrap?wrap(desc.value,key):desc.value)}}function mirrorProps(target,source){for(const key of Reflect.ownKeys(source)){const desc=Object.getOwnPropertyDescriptor(source,key);if(!desc.enumerable)continue;if(desc.get)deferProp(target,key,()=>source[key]);else putProp(target,key,desc.value)}}function mergeDefs(...defs){const mergedDescriptors={};for(const def of defs){const descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){if(!path)return obj;return path.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){const keys=Object.keys(promisesObj);const promises2=keys.map((key)=>promisesObj[key]);return Promise.all(promises2).then((results)=>{const resolvedObj={};for(let i=0;i<keys.length;i++){resolvedObj[keys[i]]=results[i]}return resolvedObj})}function randomString(length=10){const chars="abcdefghijklmnopqrstuvwxyz";let str="";for(let i=0;i<length;i++){str+=chars[Math.floor(Math.random()*chars.length)]}return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}var allowsEval=cached(()=>{if(globalConfig.jitless){return false}if(typeof navigator!=="undefined"&&navigator?.userAgent?.includes("Cloudflare")){return false}try{const F=Function;new F("");return true}catch(_){return false}});function isPlainObject(o){if(isObject(o)===false)return false;const ctor=o.constructor;if(ctor===undefined)return true;if(typeof ctor!=="function")return true;const prot=ctor.prototype;if(isObject(prot)===false)return false;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===false){return false}return true}function shallowClone(o){if(isPlainObject(o))return{...o};if(Array.isArray(o))return[...o];if(o instanceof Map)return new Map(o);if(o instanceof Set)return new Set(o);return o}function numKeys(data){let keyCount=0;for(const key in data){if(Object.prototype.hasOwnProperty.call(data,key)){keyCount++}}return keyCount}var getParsedType=(data)=>{const t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data)){return"array"}if(data===null){return"null"}if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function"){return"promise"}if(typeof Map!=="undefined"&&data instanceof Map){return"map"}if(typeof Set!=="undefined"&&data instanceof Set){return"set"}if(typeof Date!=="undefined"&&data instanceof Date){return"date"}if(typeof File!=="undefined"&&data instanceof File){return"file"}return"object";default:throw new Error(`Unknown data type: ${t}`)}};var propertyKeyTypes=new Set(["string","number","symbol"]);var primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){const cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){const params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==undefined){if(params?.error!==undefined)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}delete params.message;if(typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){target??(target=getter());return Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){target??(target=getter());return Reflect.set(target,prop,value,receiver)},has(_,prop){target??(target=getter());return Reflect.has(target,prop)},deleteProperty(_,prop){target??(target=getter());return Reflect.deleteProperty(target,prop)},ownKeys(_){target??(target=getter());return Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){target??(target=getter());return Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){target??(target=getter());return Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin!==undefined&&shape[k]._zod.optout==="optional"})}var NUMBER_FORMAT_RANGES=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))();var BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".pick() cannot be used on object schemas containing refinements")}const newShape={};mirrorShape(newShape,schema,maskedKeys(schema,mask));return clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema,mask){const raw=sourceShape(schema);const keys=[];for(const key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw,key)?.enumerable){throw new Error(`Unrecognized key: "${String(key)}"`)}if(mask[key])keys.push(key)}return keys}function omit(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".omit() cannot be used on object schemas containing refinements")}const omitted=new Set(maskedKeys(schema,mask));const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)).filter((key)=>!omitted.has(key)));return clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to extend: expected a plain object")}const checks=schema._zod.def.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){const existingShape=sourceShape(schema);for(const key of Reflect.ownKeys(shape)){if(Object.getOwnPropertyDescriptor(existingShape,key)!==undefined){throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}}}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function extended(schema,shape){const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)));mirrorProps(newShape,shape);return newShape}function safeExtend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to safeExtend: expected a plain object")}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function merge(a,b){if(!b?._zod?.def){throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.")}if(a._zod.def.checks?.length){throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.")}const newShape={};mirrorShape(newShape,a,Reflect.ownKeys(sourceShape(a)));mirrorShape(newShape,b,Reflect.ownKeys(sourceShape(b)));const def=mergeDefs(a._zod.def,{shape:newShape,get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask,name="partial"){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(`.${name}() cannot be used on object schemas containing refinements`)}const selected=mask?new Set(maskedKeys(schema,mask)):undefined;const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),Class2&&((value,key)=>selected&&!selected.has(key)?value:new Class2({type:"optional",innerType:value})));return clone(schema,mergeDefs(schema._zod.def,{shape:newShape,checks:[]}))}function required(Class2,schema,mask){const selected=mask?new Set(maskedKeys(schema,mask)):undefined;const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),(value,key)=>selected&&!selected.has(key)?value:new Class2({type:"nonoptional",innerType:value}));return clone(schema,mergeDefs(schema._zod.def,{shape:newShape}))}function aborted(x,startIndex=0){if(x.aborted===true)return true;for(let i=startIndex;i<x.issues.length;i++){if(x.issues[i]?.continue!==true){return true}}return false}function explicitlyAborted(x,startIndex=0){if(x.aborted===true)return true;for(let i=startIndex;i<x.issues.length;i++){if(x.issues[i]?.continue===false){return true}}return false}function prefixIssues(path,issues){return issues.map((iss)=>{var _a;(_a=iss).path??(_a.path=[]);iss.path.unshift(path);return iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function attachSchema(issues,start,inst){var _a;for(let i=start;i<issues.length;i++){(_a=issues[i]).schema??(_a.schema=inst)}}function finalizeIssue(iss,ctx,config){var _a;const traits=iss.inst?._zod?.traits;if(traits?.has("$ZodType")){if(traits.has("$ZodCheck"))(_a=iss).schema??(_a.schema=iss.inst);else iss.schema=iss.inst}const schemaError=iss.schema!==iss.inst?iss.schema?._zod.def?.error:undefined;const message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(schemaError?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config.customError?.(iss))??unwrapMessage(config.localeError?.(iss))??"Invalid input";const full={};for(const k of Object.keys(iss)){if(k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__")continue;full[k]=iss[k]}full.path??(full.path=[]);full.message=message;if(ctx?.reportInput){full.input=iss.input}return full}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}var highSurrogate=/[\uD800-\uDBFF]/;function codePointLength(str){const units=str.length;if(!highSurrogate.test(str))return units;let count=units;for(let i=0;i<units-1;i++){if((str.charCodeAt(i)&64512)===55296&&(str.charCodeAt(i+1)&64512)===56320){count--;i++}}return count}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function parsedType(data){const t=typeof data;switch(t){case"number":{return Number.isNaN(data)?"nan":"number"}case"object":{if(data===null){return"null"}if(Array.isArray(data)){return"array"}const obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor){return obj.constructor.name}}}return t}function issue(...args){const[iss,input,inst]=args;if(typeof iss==="string"){return{message:iss,code:"custom",input,inst}}return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array(base64){const binaryString=atob(base64);const bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++){bytes[i]=binaryString.charCodeAt(i)}return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++){binaryString+=String.fromCharCode(bytes[i])}return btoa(binaryString)}function base64urlToUint8Array(base64url){const base64=base64url.replace(/-/g,"+").replace(/_/g,"/");const padding="=".repeat((4-base64.length%4)%4);return base64ToUint8Array(base64+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){const cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0){throw new Error("Invalid hex string length")}const bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2){bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16)}return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class{constructor(..._args){}}function members(proto,table){for(const key in table){const desc=Object.getOwnPropertyDescriptor(table,key);if(desc.get)Object.defineProperty(proto,key,{...desc,enumerable:false});else defineBound(proto,key,desc.value)}}function own(inst,key,value,enumerable=true){Object.defineProperty(inst,key,{configurable:true,writable:true,enumerable,value});return value}function hide(inst,key,value){return own(inst,key,value,false)}function derived(computes,table){for(const key in computes){const compute=computes[key];Object.defineProperty(table,key,{configurable:true,enumerable:true,get(){return own(this,key,compute(this))},set(value){own(this,key,value)}})}return table}function defineBound(proto,key,fn){Object.defineProperty(proto,key,{configurable:true,get(){return this==null?fn:own(this,key,fn.bind(this))},set(value){own(this,key,value)}})}function claim(inst,sentinel){const proto=Object.getPrototypeOf(inst);return sentinel in proto?undefined:proto}var installing;var broke=false;var breaker={configurable:true,get(){broke=true;return}};function defineLazyInternal(inst,key,compute){const proto=Object.getPrototypeOf(inst._zod);if(key in proto&&installing!==inst._zod){installing=undefined;return}installing=inst._zod;Object.defineProperty(proto,key,{configurable:true,get(){Object.defineProperty(this,key,breaker);const outer=broke;broke=false;try{const value=compute(this);if(broke)delete this[key];else Object.defineProperty(this,key,{configurable:true,writable:true,value});broke=broke||outer;return value}catch(err){delete this[key];broke=broke||outer;throw err}},set(value){Object.defineProperty(this,key,{configurable:true,writable:true,value})}})}function installLazyProp(inst,key,make,enumerable){const proto=claim(inst,key);if(!proto)return;Object.defineProperty(proto,key,{configurable:true,get(){const desc={configurable:true,writable:true,enumerable,value:undefined};Object.defineProperty(this,key,desc);desc.value=make(this);Object.defineProperty(this,key,desc);return desc.value},set(value){Object.defineProperty(this,key,{configurable:true,writable:true,enumerable,value})}})}var CONSTANT_CATCH="~constantCatch";function constantCatch(value){const fn=()=>value;fn[CONSTANT_CATCH]=true;return fn}var _a;var NEVER=Object.freeze({status:"aborted"});var _zodDesc={value:undefined,enumerable:false};var _E="captureStackTrace"in Error?Error:null;function newError(Definition){const E=_E;if(E){const saved=E.stackTraceLimit;if(typeof saved==="number"){try{E.stackTraceLimit=0}catch{_E=null;return new Definition}try{return new Definition}finally{E.stackTraceLimit=saved}}}return new Definition}function $constructor(name,initializer,proto,params){const zodProto={};function Internals(def){this.def=def;this.constr=_;this.traits=new Set}Internals.prototype=zodProto;const protoMembers=proto;const initialized=protoMembers&&new WeakSet;function init(inst,def){if(!inst._zod){_zodDesc.value=new Internals(def);try{Object.defineProperty(inst,"_zod",_zodDesc)}finally{_zodDesc.value=undefined}}else if(inst._zod.traits.has(name)){return}inst._zod.traits.add(name);initializer(inst,def);if(initialized){const own=Object.getPrototypeOf(inst);const ctorProto=inst._zod.constr.prototype;let up=own;while(up&&up!==ctorProto)up=Object.getPrototypeOf(up);const target=up??own;if(!initialized.has(target)){initialized.add(target);members(target,protoMembers)}}const proto=_.prototype;for(const k in proto){if(!Object.prototype.hasOwnProperty.call(proto,k))continue;if(!(k in inst)){inst[k]=proto[k].bind(inst)}}}const Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){const inst=params?.Parent?newError(Definition):this;init(inst,def);const deferred=inst._zod.deferred;if(deferred){for(const fn of deferred){fn()}inst._zod.deferred=undefined}const pp=globalThis.__zod_globalConfig?.postProcessor;if(pp)pp(inst);return inst}Object.defineProperty(_,"init",{value:init});Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return true;return inst?._zod?.traits?.has(name)}});Object.defineProperty(_,"name",{value:name});return _}var $brand=Symbol("zod_brand");class $ZodAsyncError extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}}class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}}(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});var globalConfig=globalThis.__zod_globalConfig;function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return globalConfig}function _getMessage(){const internals=this._zod;internals.message??(internals.message=JSON.stringify(internals.def,jsonStringifyReplacer,2));return internals.message}function _setMessage(value){this._zod.message=value}var _messageDesc={get:_getMessage,set:_setMessage,enumerable:true,configurable:true};var _issuesDesc={value:undefined,enumerable:false};var _installedToString=new WeakSet([Object.prototype,Error.prototype]);var initializer=(inst,def)=>{inst.name="$ZodError";_issuesDesc.value=def;Object.defineProperty(inst,"issues",_issuesDesc);_issuesDesc.value=undefined;Object.defineProperty(inst,"message",_messageDesc);const proto=Object.getPrototypeOf(inst);if(!_installedToString.has(proto)){_installedToString.add(proto);Object.defineProperty(proto,"toString",{configurable:true,enumerable:false,get(){const value=()=>this.message;Object.defineProperty(this,"toString",{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,"toString",{value,configurable:true,writable:true})}})}};var $ZodError=$constructor("$ZodError",initializer);var $ZodRealError=$constructor("$ZodError",initializer,undefined,{Parent:Error});function node(obj,key,make){if(!Object.prototype.hasOwnProperty.call(obj,key)){if(key==="__proto__"){Object.defineProperty(obj,key,{value:make(),writable:true,enumerable:true,configurable:true})}else{obj[key]=make()}}return obj[key]}function flattenError(error,mapper=(issue)=>issue.message){const fieldErrors={};const formErrors=[];for(const sub of error.issues){if(sub.path.length>0){node(fieldErrors,sub.path[0],()=>[]).push(mapper(sub))}else{formErrors.push(mapper(sub))}}return{formErrors,fieldErrors}}function formatError(error,mapper=(issue)=>issue.message){const fieldErrors={_errors:[]};const processError=(error,path=[])=>{for(const issue of error.issues){if(issue.code==="invalid_union"&&issue.errors.length){issue.errors.map((issues)=>processError({issues},[...path,...issue.path]))}else if(issue.code==="invalid_key"){processError({issues:issue.issues},[...path,...issue.path])}else if(issue.code==="invalid_element"){processError({issues:issue.issues},[...path,...issue.path])}else{const fullpath=[...path,...issue.path];if(fullpath.length===0){fieldErrors._errors.push(mapper(issue))}else{let curr=fieldErrors;let i=0;while(i<fullpath.length){const el=fullpath[i];const terminal=i===fullpath.length-1;if(el==="_errors"){if(terminal)curr._errors.push(mapper(issue));i++;continue}if(!Object.prototype.hasOwnProperty.call(curr,el)){Object.defineProperty(curr,el,{value:{_errors:[]},enumerable:true,writable:true,configurable:true})}const node=curr[el];if(terminal){node._errors.push(mapper(issue))}curr=node;i++}}}}};processError(error);return fieldErrors}function treeifyError(error,mapper=(issue)=>issue.message){const result={errors:[]};const processError=(error,path=[])=>{var _a;for(const issue of error.issues){if(issue.code==="invalid_union"&&issue.errors.length){issue.errors.map((issues)=>processError({issues},[...path,...issue.path]))}else if(issue.code==="invalid_key"){processError({issues:issue.issues},[...path,...issue.path])}else if(issue.code==="invalid_element"){processError({issues:issue.issues},[...path,...issue.path])}else{const fullpath=[...path,...issue.path];if(fullpath.length===0){result.errors.push(mapper(issue));continue}let curr=result;let i=0;while(i<fullpath.length){const el=fullpath[i];const terminal=i===fullpath.length-1;if(typeof el==="string"){curr.properties??(curr.properties={});if(!Object.prototype.hasOwnProperty.call(curr.properties,el)){Object.defineProperty(curr.properties,el,{value:{errors:[]},enumerable:true,writable:true,configurable:true})}curr=curr.properties[el]}else{curr.items??(curr.items=[]);(_a=curr.items)[el]??(_a[el]={errors:[]});curr=curr.items[el]}if(terminal){curr.errors.push(mapper(issue))}i++}}}};processError(error);return result}function toDotPath(_path){const segs=[];const path=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(const seg of path){if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}}return segs.join("")}function prettifyError(error){const lines=[];const issues=[...error.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(const issue of issues){lines.push(`✖ ${issue.message}`);if(issue.path?.length)lines.push(` → at ${toDotPath(issue.path)}`)}return lines.join(`
|
|
7
|
+
`+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){const err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message,headers)}}});var exports_zod={};__export(exports_zod,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>exports_coerce,compile:()=>compile,config:()=>config,core:()=>exports_core2,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,decode:()=>decode2,decodeAsync:()=>decodeAsync2,deepPartial:()=>deepPartial,default:()=>exports_external,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode2,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getDiscriminatedOption:()=>getDiscriminatedOption,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,includes:()=>_includes,input:()=>input,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>exports_iso,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>exports_locales,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,memoizer:()=>memoizer,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,output:()=>output,overwrite:()=>_overwrite,parse:()=>parse3,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,properties:()=>_properties,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>exports_regexes,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,toZod:()=>toZod,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>exports_util,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,validate:()=>validate,validateAsync:()=>validateAsync,void:()=>_void2,withParser:()=>withParser,xid:()=>xid2,xor:()=>xor,z:()=>exports_external});var exports_external={};__export(exports_external,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>exports_coerce,compile:()=>compile,config:()=>config,core:()=>exports_core2,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,decode:()=>decode2,decodeAsync:()=>decodeAsync2,deepPartial:()=>deepPartial,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode2,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getDiscriminatedOption:()=>getDiscriminatedOption,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,includes:()=>_includes,input:()=>input,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>exports_iso,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>exports_locales,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,memoizer:()=>memoizer,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,output:()=>output,overwrite:()=>_overwrite,parse:()=>parse3,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,properties:()=>_properties,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>exports_regexes,registry:()=>registry,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,toZod:()=>toZod,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>exports_util,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,validate:()=>validate,validateAsync:()=>validateAsync,void:()=>_void2,withParser:()=>withParser,xid:()=>xid2,xor:()=>xor});var exports_core2={};__export(exports_core2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperties:()=>$ZodCheckProperties,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCreditCard:()=>$ZodCreditCard,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCyclicError:()=>$ZodCyclicError,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIBAN:()=>$ZodIBAN,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,INVALID:()=>INVALID,JSONSchema:()=>exports_json_schema,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,URL_BAD_FORMAT:()=>URL_BAD_FORMAT,URL_UNPARSEABLE:()=>URL_UNPARSEABLE,ZodCompileAsyncError:()=>ZodCompileAsyncError,ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_creditCard:()=>_creditCard,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_iban:()=>_iban,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_properties:()=>_properties,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,base64Charset:()=>base64Charset,base64urlCharset:()=>base64urlCharset,canParseURL:()=>canParseURL,clone:()=>clone,compile:()=>compile,compileFn:()=>compileFn,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,getDiscriminatedOption:()=>getDiscriminatedOption,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,handleUnrepresentable:()=>handleUnrepresentable,initializeContext:()=>initializeContext,isBackEdge:()=>isBackEdge,isRecursiveSchema:()=>isRecursiveSchema,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidCIDRv6:()=>isValidCIDRv6,isValidCreditCard:()=>isValidCreditCard,isValidIBAN:()=>isValidIBAN,isValidIPv6:()=>isValidIPv6,isValidJWT:()=>isValidJWT,locales:()=>exports_locales,memoizer:()=>memoizer,mergeValues:()=>mergeValues,meta:()=>meta,parse:()=>parse,parseAsync:()=>parseAsync,parseURLObject:()=>parseURLObject,prettifyError:()=>prettifyError,process:()=>processSchema,processSchema:()=>processSchema,regexes:()=>exports_regexes,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,standardProps:()=>standardProps,stripTabAndNewline:()=>stripTabAndNewline,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,toZod:()=>toZod,treeifyError:()=>treeifyError,urlHostnameOk:()=>urlHostnameOk,urlProtocolOk:()=>urlProtocolOk,util:()=>exports_util,validate:()=>validate,validateAsync:()=>validateAsync,validateURL:()=>validateURL,version:()=>version,withParser:()=>withParser});var exports_util={};__export(exports_util,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,CONSTANT_CATCH:()=>CONSTANT_CATCH,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,attachSchema:()=>attachSchema,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,codePointLength:()=>codePointLength,constantCatch:()=>constantCatch,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,defineLazyInternal:()=>defineLazyInternal,derived:()=>derived,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,hide:()=>hide,installLazyProp:()=>installLazyProp,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,members:()=>members,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,own:()=>own,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,rawShape:()=>rawShape,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,toZod:()=>toZod,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});var exports_regexes={};__export(exports_regexes,{anyString:()=>anyString,base64:()=>base64,base64url:()=>base64url,bigint:()=>bigint,boolean:()=>boolean,browserEmail:()=>browserEmail,cidrv4:()=>cidrv4,cidrv6:()=>cidrv6,creditCard:()=>creditCard,cuid:()=>cuid,cuid2:()=>cuid2,currencyCode:()=>currencyCode,date:()=>date,datetime:()=>datetime,domain:()=>domain,duration:()=>duration,e164:()=>e164,email:()=>email,emoji:()=>emoji,extendedDuration:()=>extendedDuration,guid:()=>guid,hex:()=>hex,hostname:()=>hostname,html5Email:()=>html5Email,httpProtocol:()=>httpProtocol,iban:()=>iban,idnEmail:()=>idnEmail,integer:()=>integer,ipv4:()=>ipv4,ipv6:()=>ipv6,ksuid:()=>ksuid,lowercase:()=>lowercase,mac:()=>mac,md5_base64:()=>md5_base64,md5_base64url:()=>md5_base64url,md5_hex:()=>md5_hex,nanoid:()=>nanoid,nanoidOfLength:()=>nanoidOfLength,null:()=>_null,number:()=>number,rfc5322Email:()=>rfc5322Email,sha1_base64:()=>sha1_base64,sha1_base64url:()=>sha1_base64url,sha1_hex:()=>sha1_hex,sha256_base64:()=>sha256_base64,sha256_base64url:()=>sha256_base64url,sha256_hex:()=>sha256_hex,sha384_base64:()=>sha384_base64,sha384_base64url:()=>sha384_base64url,sha384_hex:()=>sha384_hex,sha512_base64:()=>sha512_base64,sha512_base64url:()=>sha512_base64url,sha512_hex:()=>sha512_hex,string:()=>string,time:()=>time,ulid:()=>ulid,undefined:()=>_undefined,unicodeEmail:()=>unicodeEmail,uppercase:()=>uppercase,uuid:()=>uuid,uuid4:()=>uuid4,uuid6:()=>uuid6,uuid7:()=>uuid7,xid:()=>xid});var exports_locales={};__export(exports_locales,{ar:()=>ar_default,az:()=>az_default,be:()=>be_default,bg:()=>bg_default,bn:()=>bn_default,ca:()=>ca_default,ckb:()=>ckb_default,cs:()=>cs_default,da:()=>da_default,de:()=>de_default,el:()=>el_default,en:()=>en_default,eo:()=>eo_default,es:()=>es_default,fa:()=>fa_default,fi:()=>fi_default,fr:()=>fr_default,frCA:()=>fr_CA_default,gu:()=>gu_default,he:()=>he_default,hi:()=>hi_default,hr:()=>hr_default,hu:()=>hu_default,hy:()=>hy_default,id:()=>id_default,is:()=>is_default,it:()=>it_default,ja:()=>ja_default,ka:()=>ka_default,kh:()=>kh_default,km:()=>km_default,kn:()=>kn_default,ko:()=>ko_default,lt:()=>lt_default,mk:()=>mk_default,ms:()=>ms_default,ne:()=>ne_default,nl:()=>nl_default,nn:()=>nn_default,no:()=>no_default,ota:()=>ota_default,pl:()=>pl_default,ps:()=>ps_default,pt:()=>pt_default,ptBR:()=>pt_BR_default,ro:()=>ro_default,ru:()=>ru_default,sk:()=>sk_default,sl:()=>sl_default,sv:()=>sv_default,ta:()=>ta_default,tg:()=>tg_default,th:()=>th_default,tk:()=>tk_default,tr:()=>tr_default,ua:()=>ua_default,uk:()=>uk_default,ur:()=>ur_default,uz:()=>uz_default,vi:()=>vi_default,yo:()=>yo_default,zhCN:()=>zh_CN_default,zhTW:()=>zh_TW_default});var exports_json_schema={};var exports_schemas2={};__export(exports_schemas2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var exports_checks2={};__export(exports_checks2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var exports_iso={};__export(exports_iso,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});var exports_coerce={};__export(exports_coerce,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});class CdpCommandError extends Error{constructor(name,message,details){super(message);Object.assign(this,details);this.name=name}}class CdpCommandTimeoutError extends CdpCommandError{constructor(message,details){super("CdpCommandTimeoutError",message,details)}}class CdpPipeClosedError extends CdpCommandError{constructor(message,details){super("CdpPipeClosedError",message,details)}}class CdpSessionDetachedError extends CdpCommandError{constructor(message,details){super("CdpSessionDetachedError",message,details)}}class CdpSessionCrashedError extends CdpCommandError{constructor(message,details){super("CdpSessionCrashedError",message,details)}}var import_stream=__toESM(require_stream(),1);var import_extension=__toESM(require_extension(),1);var import_permessage_deflate=__toESM(require_permessage_deflate(),1);var import_receiver=__toESM(require_receiver(),1);var import_sender=__toESM(require_sender(),1);var import_subprotocol=__toESM(require_subprotocol(),1);var import_websocket=__toESM(require_websocket(),1);var import_websocket_server=__toESM(require_websocket_server(),1);var escapedChars=new Set(["$","^","+",".","*","(",")","|","\\","?","{","}","[","]"]);function globToRegexPattern(glob){const tokens=["^"];let inGroup=false;for(let i=0;i<glob.length;++i){const c=glob.charAt(i);if(c==="\\"&&i+1<glob.length){const char=glob.charAt(++i);tokens.push(escapedChars.has(char)?"\\"+char:char);continue}if(c==="*"){const charBefore=glob[i-1];let starCount=1;while(glob[i+1]==="*"){starCount++;i++}if(starCount>1){const charAfter=glob[i+1];if(charAfter==="/"){if(charBefore==="/")tokens.push("((.+/)|)");else tokens.push("(.*/)");++i}else{tokens.push("(.*)")}}else{tokens.push("([^/]*)")}continue}switch(c){case"{":if(inGroup)throw new Error(`Invalid glob pattern ${JSON.stringify(glob)}: nested '{' is not supported`);inGroup=true;tokens.push("(");break;case"}":if(!inGroup)throw new Error(`Invalid glob pattern ${JSON.stringify(glob)}: unmatched '}'`);inGroup=false;tokens.push(")");break;case",":if(inGroup){tokens.push("|");break}tokens.push("\\"+c);break;default:tokens.push(escapedChars.has(c)?"\\"+c:c)}}if(inGroup)throw new Error(`Invalid glob pattern ${JSON.stringify(glob)}: unmatched '{'`);tokens.push("$");return tokens.join("")}function resolveGlob(match){if(match.startsWith("*"))return match;const tokenMap=new Map;function mapToken(original,replacement){if(original.length===0)return"";tokenMap.set(replacement,original);return replacement}match=match.replaceAll(/\\\\\?/g,"?");if(match.startsWith("about:")||match.startsWith("data:")||match.startsWith("chrome:")||match.startsWith("edge:")||match.startsWith("file:"))return match;const relativePath=match.split("/").map((token,index)=>{if(token==="."||token===".."||token==="")return token;if(index===0&&token.endsWith(":")){if(token.indexOf("*")!==-1||token.indexOf("{")!==-1)return mapToken(token,"http:");return token}if(!/[*?{}\\]/.test(token))return token;const questionIndex=token.indexOf("?");if(questionIndex===-1)return mapToken(token,`$_${index}_$`);const newPrefix=mapToken(token.substring(0,questionIndex),`$_${index}_$`);const newSuffix=mapToken(token.substring(questionIndex),`?$_${index}_$`);return newPrefix+newSuffix}).join("/");const result=resolveURL(relativePath);let resolved=result.resolved;for(const[token,original]of tokenMap){const normalize=result.caseInsensitivePart?.includes(token);const replacement=normalize?original.toLowerCase():original;resolved=resolved.replace(token,()=>replacement)}return resolved}function resolveURL(givenURL){try{const url=new URL(givenURL);return{resolved:url.toString(),caseInsensitivePart:url.origin}}catch{return{resolved:givenURL}}}function parseURL(url){try{return new URL(url)}catch{return null}}function isRegExp(value){return value instanceof RegExp||Object.prototype.toString.call(value)==="[object RegExp]"}async function urlMatches(urlString,match){if(match===undefined||match==="")return true;if(typeof match==="string")match=new RegExp(globToRegexPattern(resolveGlob(match)));if(isRegExp(match)){match.lastIndex=0;return match.test(urlString)}if(typeof match!=="function")throw new TypeError("url parameter should be string, RegExp or function");const url=parseURL(urlString);if(!url)return false;return Boolean(await match(url))}var sessions=new WeakMap;var streams=new WeakMap;function acquireNetwork(cdp,sessionId){let active=sessions.get(cdp);if(!active)sessions.set(cdp,active=new Map);let state=active.get(sessionId);if(!state){state={users:0};active.set(sessionId,state);state.ready=cdp.send("Network.enable",undefined,sessionId).catch(()=>{})}state.users++;const held=state;const activeSessions=active;let released=false;const release=()=>{if(released)return;released=true;if(--held.users)return;activeSessions.delete(sessionId);cdp.send("Network.disable",undefined,sessionId).catch(()=>{})};release.ready=held.ready;return release}class NetworkBodyUnavailableError extends Error{constructor(message,cause){super(message,{cause});this.name="NetworkBodyUnavailableError"}}function headers(values={}){return Object.fromEntries(Object.entries(values).map(([key,value])=>[key.toLowerCase(),String(value)]))}function bodyReaders(body){return{body,async text(){return(await body()).toString("utf8")},async json(){return JSON.parse(await this.text())}}}function recordFor(cdp,sessionId,params){const request=params.request??{};const finished=Promise.withResolvers();let rawBody;const record={exposed:false,finish:finished.resolve,rawBody(){return rawBody??=finished.promise.then(async(failure)=>{try{if(failure)throw failure;return await cdp.send("Network.getResponseBody",{requestId:params.requestId},sessionId)}catch(cause){throw new NetworkBodyUnavailableError(`Response body is unavailable for ${request.url}`,cause)}})},request:{url:()=>request.url??params.documentURL??"",method:()=>request.method??"GET",headers:()=>headers(request.headers),...bodyReaders(async()=>Buffer.from(request.postData??"","utf8"))},setResponse:(response)=>{record.response={url:()=>response.url??record.request.url(),method:record.request.method,headers:()=>headers(response.headers),status:()=>response.status,ok:()=>response.status!==undefined&&response.status>=200&&response.status<=299,...bodyReaders(async()=>{const result=await record.rawBody();return Buffer.from(result.body??"",result.base64Encoded?"base64":"utf8")})}}};return record}function subscribeNetwork(page,handlers){let stream=streams.get(page);if(!stream){const observers=new Set;const inflight=new Map;const unsubscribers=[];let sessionId;let release;let closed=false;const ready=Promise.resolve(page.resolveSessionId()).then(async(id)=>{sessionId=id;if(!closed){release=acquireNetwork(page.cdp,id);await release.ready}});ready.catch(()=>{});const close=(force=false)=>{if(closed||!force&&(observers.size||inflight.size))return;closed=true;for(const record of inflight.values())record.finish(Error("Page network capture disposed"));inflight.clear();observers.clear();for(const off of unsubscribers)off();release?.();streams.delete(page)};const notify=(method,params,record)=>{for(const observer of observers)observer[method]?.(params,record)};const dispatch=(event)=>{const{params}=event;let record=inflight.get(params.requestId);if(event.method==="Network.requestWillBeSent"){record?.finish(Error("Request redirected"));const created=recordFor(page.cdp,sessionId,event.params);record=created;inflight.set(params.requestId,created);notify(event.method,event.params,created)}else if(event.method==="Network.responseReceived"){record?.setResponse(event.params.response??{});notify(event.method,event.params,record)}else if(event.method==="Network.loadingFailed"){record?.finish(Error(event.params.errorText??"Request failed"));notify(event.method,event.params,record)}else{record?.finish(null);notify(event.method,event.params,record)}if(event.method==="Network.loadingFinished"||event.method==="Network.loadingFailed"){const done=record?.exposed&&record.response?record.rawBody().catch(()=>{}):Promise.resolve();done.finally(()=>{if(inflight.get(params.requestId)===record)inflight.delete(params.requestId);close()})}};const onEvent=(event,meta)=>{if(closed)return;if(sessionId===undefined){ready.then(()=>{if(!closed&&meta?.sessionId===sessionId)dispatch(event)}).catch(()=>{})}else if(meta?.sessionId===sessionId)dispatch(event)};unsubscribers.push(page.cdp.on("Network.requestWillBeSent",(params,meta)=>onEvent({method:"Network.requestWillBeSent",params},meta)),page.cdp.on("Network.responseReceived",(params,meta)=>onEvent({method:"Network.responseReceived",params},meta)),page.cdp.on("Network.loadingFinished",(params,meta)=>onEvent({method:"Network.loadingFinished",params},meta)),page.cdp.on("Network.loadingFailed",(params,meta)=>onEvent({method:"Network.loadingFailed",params},meta)));stream={observers,close,inflight,ready};streams.set(page,stream)}const subscribed=stream;subscribed.observers.add(handlers);return()=>{subscribed.observers.delete(handlers);for(const[id,record]of subscribed.inflight){if(!record.exposed&&!subscribed.observers.size){record.finish(Error("Network capture disposed"));subscribed.inflight.delete(id)}}subscribed.close()}}function trackDocumentResponses(page,frameId){const documents=new Map;const dispose=subscribeNetwork(page,{"Network.requestWillBeSent":(params,record)=>{if(params.type!=="Document"||params.frameId!==frameId)return;record.exposed=true;documents.set(params.loaderId,record)}});return{ready:networkReady(page),response:(loaderId)=>loaderId===undefined?null:documents.get(loaderId)?.response??null,dispose}}function disposeNetwork(page){streams.get(page)?.close(true)}function networkReady(page){return streams.get(page)?.ready}function subscribePageNetworkEvents(page){const emit=(name,value)=>page.events.emit(name,value).catch((error)=>console.warn("[network] page event listener failed",error));return subscribeNetwork(page,{"Network.requestWillBeSent":(_params,record)=>emit("request",record.request),"Network.responseReceived":(_params,record)=>{if(!record)return;record.exposed=true;emit("response",record.response)}})}function networkPredicate(match){if(typeof match==="function")return match;if(match instanceof RegExp)return(value)=>{match.lastIndex=0;return match.test(value.url())};if(typeof match==="string")return(value)=>urlMatches(value.url(),match);throw new TypeError("urlOrPredicate must be a URL string, RegExp or predicate")}function assertEqual(val){return val}function assertNotEqual(val){return val}function toZod(){return(schema)=>schema}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){const numericValues=Object.values(entries).filter((v)=>typeof v==="number");const values=Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v);return values}function joinValues(array,separator="|"){return array.map((val)=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){if(typeof value==="bigint")return value.toString();return value}class Cached{constructor(getter){this._getter=getter;this._value=undefined}get value(){const getter=this._getter;if(getter!==undefined){this._value=getter();this._getter=undefined}return this._value}}function cached(getter){return new Cached(getter)}function nullish(input){return input===null||input===undefined}function cleanRegex(source){const start=source.startsWith("^")?1:0;const end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){const ratio=val/step;const roundedRatio=Math.round(ratio);const tolerance=4*Number.EPSILON*Math.max(Math.abs(ratio),1);if(Math.abs(ratio-roundedRatio)<tolerance)return 0;return ratio-roundedRatio}var EVALUATING=Symbol("evaluating");function defineLazy(object,key,getter){let value=undefined;Object.defineProperty(object,key,{get(){if(value===EVALUATING){return}if(value===undefined){value=EVALUATING;value=getter()}return value},set(v){Object.defineProperty(object,key,{value:v})},configurable:true})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:true,enumerable:true,configurable:true})}function rawShape(def){const desc=Object.getOwnPropertyDescriptor(def,"shape");return desc?.get?desc.get.raw:desc?.value}function sourceShape(schema){return rawShape(schema._zod.def)??schema._zod.def.shape}function deferProp(target,key,getter){Object.defineProperty(target,key,{get(){const value=getter();assignProp(this,key,value);return value},enumerable:true,configurable:true})}function putProp(target,key,value){if(key in target)assignProp(target,key,value);else target[key]=value}function mirrorShape(target,source,keys,wrap){const raw=sourceShape(source);for(const key of keys){const desc=Object.getOwnPropertyDescriptor(raw,key);if(!desc.enumerable)continue;if(desc.get){deferProp(target,key,()=>{const value=source._zod.def.shape[key];return wrap?wrap(value,key):value})}else putProp(target,key,wrap?wrap(desc.value,key):desc.value)}}function mirrorProps(target,source){for(const key of Reflect.ownKeys(source)){const desc=Object.getOwnPropertyDescriptor(source,key);if(!desc.enumerable)continue;if(desc.get)deferProp(target,key,()=>source[key]);else putProp(target,key,desc.value)}}function mergeDefs(...defs){const mergedDescriptors={};for(const def of defs){const descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){if(!path)return obj;return path.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){const keys=Object.keys(promisesObj);const promises2=keys.map((key)=>promisesObj[key]);return Promise.all(promises2).then((results)=>{const resolvedObj={};for(let i=0;i<keys.length;i++){resolvedObj[keys[i]]=results[i]}return resolvedObj})}function randomString(length=10){const chars="abcdefghijklmnopqrstuvwxyz";let str="";for(let i=0;i<length;i++){str+=chars[Math.floor(Math.random()*chars.length)]}return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}var allowsEval=cached(()=>{if(globalConfig.jitless){return false}if(typeof navigator!=="undefined"&&navigator?.userAgent?.includes("Cloudflare")){return false}try{const F=Function;new F("");return true}catch(_){return false}});function isPlainObject(o){if(isObject(o)===false)return false;const ctor=o.constructor;if(ctor===undefined)return true;if(typeof ctor!=="function")return true;const prot=ctor.prototype;if(isObject(prot)===false)return false;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===false){return false}return true}function shallowClone(o){if(isPlainObject(o))return{...o};if(Array.isArray(o))return[...o];if(o instanceof Map)return new Map(o);if(o instanceof Set)return new Set(o);return o}function numKeys(data){let keyCount=0;for(const key in data){if(Object.prototype.hasOwnProperty.call(data,key)){keyCount++}}return keyCount}var getParsedType=(data)=>{const t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data)){return"array"}if(data===null){return"null"}if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function"){return"promise"}if(typeof Map!=="undefined"&&data instanceof Map){return"map"}if(typeof Set!=="undefined"&&data instanceof Set){return"set"}if(typeof Date!=="undefined"&&data instanceof Date){return"date"}if(typeof File!=="undefined"&&data instanceof File){return"file"}return"object";default:throw new Error(`Unknown data type: ${t}`)}};var propertyKeyTypes=new Set(["string","number","symbol"]);var primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){const cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){const params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==undefined){if(params?.error!==undefined)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}delete params.message;if(typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){target??(target=getter());return Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){target??(target=getter());return Reflect.set(target,prop,value,receiver)},has(_,prop){target??(target=getter());return Reflect.has(target,prop)},deleteProperty(_,prop){target??(target=getter());return Reflect.deleteProperty(target,prop)},ownKeys(_){target??(target=getter());return Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){target??(target=getter());return Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){target??(target=getter());return Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin!==undefined&&shape[k]._zod.optout==="optional"})}var NUMBER_FORMAT_RANGES=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))();var BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".pick() cannot be used on object schemas containing refinements")}const newShape={};mirrorShape(newShape,schema,maskedKeys(schema,mask));return clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema,mask){const raw=sourceShape(schema);const keys=[];for(const key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw,key)?.enumerable){throw new Error(`Unrecognized key: "${String(key)}"`)}if(mask[key])keys.push(key)}return keys}function omit(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".omit() cannot be used on object schemas containing refinements")}const omitted=new Set(maskedKeys(schema,mask));const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)).filter((key)=>!omitted.has(key)));return clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to extend: expected a plain object")}const checks=schema._zod.def.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){const existingShape=sourceShape(schema);for(const key of Reflect.ownKeys(shape)){if(Object.getOwnPropertyDescriptor(existingShape,key)!==undefined){throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}}}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function extended(schema,shape){const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)));mirrorProps(newShape,shape);return newShape}function safeExtend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to safeExtend: expected a plain object")}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function merge(a,b){if(!b?._zod?.def){throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.")}if(a._zod.def.checks?.length){throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.")}const newShape={};mirrorShape(newShape,a,Reflect.ownKeys(sourceShape(a)));mirrorShape(newShape,b,Reflect.ownKeys(sourceShape(b)));const def=mergeDefs(a._zod.def,{shape:newShape,get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask,name="partial"){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(`.${name}() cannot be used on object schemas containing refinements`)}const selected=mask?new Set(maskedKeys(schema,mask)):undefined;const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),Class2&&((value,key)=>selected&&!selected.has(key)?value:new Class2({type:"optional",innerType:value})));return clone(schema,mergeDefs(schema._zod.def,{shape:newShape,checks:[]}))}function required(Class2,schema,mask){const selected=mask?new Set(maskedKeys(schema,mask)):undefined;const newShape={};mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),(value,key)=>selected&&!selected.has(key)?value:new Class2({type:"nonoptional",innerType:value}));return clone(schema,mergeDefs(schema._zod.def,{shape:newShape}))}function aborted(x,startIndex=0){if(x.aborted===true)return true;for(let i=startIndex;i<x.issues.length;i++){if(x.issues[i]?.continue!==true){return true}}return false}function explicitlyAborted(x,startIndex=0){if(x.aborted===true)return true;for(let i=startIndex;i<x.issues.length;i++){if(x.issues[i]?.continue===false){return true}}return false}function prefixIssues(path,issues){return issues.map((iss)=>{var _a;(_a=iss).path??(_a.path=[]);iss.path.unshift(path);return iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function attachSchema(issues,start,inst){var _a;for(let i=start;i<issues.length;i++){(_a=issues[i]).schema??(_a.schema=inst)}}function finalizeIssue(iss,ctx,config){var _a;const traits=iss.inst?._zod?.traits;if(traits?.has("$ZodType")){if(traits.has("$ZodCheck"))(_a=iss).schema??(_a.schema=iss.inst);else iss.schema=iss.inst}const schemaError=iss.schema!==iss.inst?iss.schema?._zod.def?.error:undefined;const message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(schemaError?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config.customError?.(iss))??unwrapMessage(config.localeError?.(iss))??"Invalid input";const full={};for(const k of Object.keys(iss)){if(k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__")continue;full[k]=iss[k]}full.path??(full.path=[]);full.message=message;if(ctx?.reportInput){full.input=iss.input}return full}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}var highSurrogate=/[\uD800-\uDBFF]/;function codePointLength(str){const units=str.length;if(!highSurrogate.test(str))return units;let count=units;for(let i=0;i<units-1;i++){if((str.charCodeAt(i)&64512)===55296&&(str.charCodeAt(i+1)&64512)===56320){count--;i++}}return count}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function parsedType(data){const t=typeof data;switch(t){case"number":{return Number.isNaN(data)?"nan":"number"}case"object":{if(data===null){return"null"}if(Array.isArray(data)){return"array"}const obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor){return obj.constructor.name}}}return t}function issue(...args){const[iss,input,inst]=args;if(typeof iss==="string"){return{message:iss,code:"custom",input,inst}}return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array(base64){const binaryString=atob(base64);const bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++){bytes[i]=binaryString.charCodeAt(i)}return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++){binaryString+=String.fromCharCode(bytes[i])}return btoa(binaryString)}function base64urlToUint8Array(base64url){const base64=base64url.replace(/-/g,"+").replace(/_/g,"/");const padding="=".repeat((4-base64.length%4)%4);return base64ToUint8Array(base64+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){const cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0){throw new Error("Invalid hex string length")}const bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2){bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16)}return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class{constructor(..._args){}}function members(proto,table){for(const key in table){const desc=Object.getOwnPropertyDescriptor(table,key);if(desc.get)Object.defineProperty(proto,key,{...desc,enumerable:false});else defineBound(proto,key,desc.value)}}function own(inst,key,value,enumerable=true){Object.defineProperty(inst,key,{configurable:true,writable:true,enumerable,value});return value}function hide(inst,key,value){return own(inst,key,value,false)}function derived(computes,table){for(const key in computes){const compute=computes[key];Object.defineProperty(table,key,{configurable:true,enumerable:true,get(){return own(this,key,compute(this))},set(value){own(this,key,value)}})}return table}function defineBound(proto,key,fn){Object.defineProperty(proto,key,{configurable:true,get(){return this==null?fn:own(this,key,fn.bind(this))},set(value){own(this,key,value)}})}function claim(inst,sentinel){const proto=Object.getPrototypeOf(inst);return sentinel in proto?undefined:proto}var installing;var broke=false;var breaker={configurable:true,get(){broke=true;return}};function defineLazyInternal(inst,key,compute){const proto=Object.getPrototypeOf(inst._zod);if(key in proto&&installing!==inst._zod){installing=undefined;return}installing=inst._zod;Object.defineProperty(proto,key,{configurable:true,get(){Object.defineProperty(this,key,breaker);const outer=broke;broke=false;try{const value=compute(this);if(broke)delete this[key];else Object.defineProperty(this,key,{configurable:true,writable:true,value});broke=broke||outer;return value}catch(err){delete this[key];broke=broke||outer;throw err}},set(value){Object.defineProperty(this,key,{configurable:true,writable:true,value})}})}function installLazyProp(inst,key,make,enumerable){const proto=claim(inst,key);if(!proto)return;Object.defineProperty(proto,key,{configurable:true,get(){const desc={configurable:true,writable:true,enumerable,value:undefined};Object.defineProperty(this,key,desc);desc.value=make(this);Object.defineProperty(this,key,desc);return desc.value},set(value){Object.defineProperty(this,key,{configurable:true,writable:true,enumerable,value})}})}var CONSTANT_CATCH="~constantCatch";function constantCatch(value){const fn=()=>value;fn[CONSTANT_CATCH]=true;return fn}var _a;var NEVER=Object.freeze({status:"aborted"});var _zodDesc={value:undefined,enumerable:false};var _E="captureStackTrace"in Error?Error:null;function newError(Definition){const E=_E;if(E){const saved=E.stackTraceLimit;if(typeof saved==="number"){try{E.stackTraceLimit=0}catch{_E=null;return new Definition}try{return new Definition}finally{E.stackTraceLimit=saved}}}return new Definition}function $constructor(name,initializer,proto,params){const zodProto={};function Internals(def){this.def=def;this.constr=_;this.traits=new Set}Internals.prototype=zodProto;const protoMembers=proto;const initialized=protoMembers&&new WeakSet;function init(inst,def){if(!inst._zod){_zodDesc.value=new Internals(def);try{Object.defineProperty(inst,"_zod",_zodDesc)}finally{_zodDesc.value=undefined}}else if(inst._zod.traits.has(name)){return}inst._zod.traits.add(name);initializer(inst,def);if(initialized){const own=Object.getPrototypeOf(inst);const ctorProto=inst._zod.constr.prototype;let up=own;while(up&&up!==ctorProto)up=Object.getPrototypeOf(up);const target=up??own;if(!initialized.has(target)){initialized.add(target);members(target,protoMembers)}}const proto=_.prototype;for(const k in proto){if(!Object.prototype.hasOwnProperty.call(proto,k))continue;if(!(k in inst)){inst[k]=proto[k].bind(inst)}}}const Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){const inst=params?.Parent?newError(Definition):this;init(inst,def);const deferred=inst._zod.deferred;if(deferred){for(const fn of deferred){fn()}inst._zod.deferred=undefined}const pp=globalThis.__zod_globalConfig?.postProcessor;if(pp)pp(inst);return inst}Object.defineProperty(_,"init",{value:init});Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return true;return inst?._zod?.traits?.has(name)}});Object.defineProperty(_,"name",{value:name});return _}var $brand=Symbol("zod_brand");class $ZodAsyncError extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}}class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}}(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});var globalConfig=globalThis.__zod_globalConfig;function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return globalConfig}function _getMessage(){const internals=this._zod;internals.message??(internals.message=JSON.stringify(internals.def,jsonStringifyReplacer,2));return internals.message}function _setMessage(value){this._zod.message=value}var _messageDesc={get:_getMessage,set:_setMessage,enumerable:true,configurable:true};var _issuesDesc={value:undefined,enumerable:false};var _installedToString=new WeakSet([Object.prototype,Error.prototype]);var initializer=(inst,def)=>{inst.name="$ZodError";_issuesDesc.value=def;Object.defineProperty(inst,"issues",_issuesDesc);_issuesDesc.value=undefined;Object.defineProperty(inst,"message",_messageDesc);const proto=Object.getPrototypeOf(inst);if(!_installedToString.has(proto)){_installedToString.add(proto);Object.defineProperty(proto,"toString",{configurable:true,enumerable:false,get(){const value=()=>this.message;Object.defineProperty(this,"toString",{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,"toString",{value,configurable:true,writable:true})}})}};var $ZodError=$constructor("$ZodError",initializer);var $ZodRealError=$constructor("$ZodError",initializer,undefined,{Parent:Error});function node(obj,key,make){if(!Object.prototype.hasOwnProperty.call(obj,key)){if(key==="__proto__"){Object.defineProperty(obj,key,{value:make(),writable:true,enumerable:true,configurable:true})}else{obj[key]=make()}}return obj[key]}function flattenError(error,mapper=(issue)=>issue.message){const fieldErrors={};const formErrors=[];for(const sub of error.issues){if(sub.path.length>0){node(fieldErrors,sub.path[0],()=>[]).push(mapper(sub))}else{formErrors.push(mapper(sub))}}return{formErrors,fieldErrors}}function formatError(error,mapper=(issue)=>issue.message){const fieldErrors={_errors:[]};const processError=(error,path=[])=>{for(const issue of error.issues){if(issue.code==="invalid_union"&&issue.errors.length){issue.errors.map((issues)=>processError({issues},[...path,...issue.path]))}else if(issue.code==="invalid_key"){processError({issues:issue.issues},[...path,...issue.path])}else if(issue.code==="invalid_element"){processError({issues:issue.issues},[...path,...issue.path])}else{const fullpath=[...path,...issue.path];if(fullpath.length===0){fieldErrors._errors.push(mapper(issue))}else{let curr=fieldErrors;let i=0;while(i<fullpath.length){const el=fullpath[i];const terminal=i===fullpath.length-1;if(el==="_errors"){if(terminal)curr._errors.push(mapper(issue));i++;continue}if(!Object.prototype.hasOwnProperty.call(curr,el)){Object.defineProperty(curr,el,{value:{_errors:[]},enumerable:true,writable:true,configurable:true})}const node=curr[el];if(terminal){node._errors.push(mapper(issue))}curr=node;i++}}}}};processError(error);return fieldErrors}function treeifyError(error,mapper=(issue)=>issue.message){const result={errors:[]};const processError=(error,path=[])=>{var _a;for(const issue of error.issues){if(issue.code==="invalid_union"&&issue.errors.length){issue.errors.map((issues)=>processError({issues},[...path,...issue.path]))}else if(issue.code==="invalid_key"){processError({issues:issue.issues},[...path,...issue.path])}else if(issue.code==="invalid_element"){processError({issues:issue.issues},[...path,...issue.path])}else{const fullpath=[...path,...issue.path];if(fullpath.length===0){result.errors.push(mapper(issue));continue}let curr=result;let i=0;while(i<fullpath.length){const el=fullpath[i];const terminal=i===fullpath.length-1;if(typeof el==="string"){curr.properties??(curr.properties={});if(!Object.prototype.hasOwnProperty.call(curr.properties,el)){Object.defineProperty(curr.properties,el,{value:{errors:[]},enumerable:true,writable:true,configurable:true})}curr=curr.properties[el]}else{curr.items??(curr.items=[]);(_a=curr.items)[el]??(_a[el]={errors:[]});curr=curr.items[el]}if(terminal){curr.errors.push(mapper(issue))}i++}}}};processError(error);return result}function toDotPath(_path){const segs=[];const path=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(const seg of path){if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}}return segs.join("")}function prettifyError(error){const lines=[];const issues=[...error.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(const issue of issues){lines.push(`✖ ${issue.message}`);if(issue.path?.length)lines.push(` → at ${toDotPath(issue.path)}`)}return lines.join(`
|
|
8
8
|
`)}function finalizeParams(callee,params){return{callee:params?.callee??callee,Err:params?.Err}}var _parse=(_Err)=>{const fn=(schema,value,_ctx,_params)=>{const ctx=_ctx?{..._ctx,async:false}:{async:false};const result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise){throw new $ZodAsyncError}if(result.issues.length){const e=new(_params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())));captureStackTrace(e,_params?.callee??fn);throw e}return result.value};return fn};var parse=_parse($ZodRealError);var _parseAsync=(_Err)=>{const fn=async(schema,value,_ctx,params)=>{const ctx=_ctx?{..._ctx,async:true}:{async:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){const e=new(params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())));captureStackTrace(e,params?.callee??fn);throw e}return result.value};return fn};var parseAsync=_parseAsync($ZodRealError);var _safeParse=(_Err)=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:false}:{async:false};const result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise){throw new $ZodAsyncError}return result.issues.length?failure(_Err,result.issues,ctx):{success:true,data:result.value}};var safeParse=_safeParse($ZodRealError);function failure(Err,issues,ctx){let error;return{success:false,get error(){if(!error){error=new Err(issues.map((iss)=>finalizeIssue(iss,ctx,config())));issues=undefined;ctx=undefined}return error},set error(e){error=e;issues=undefined;ctx=undefined}}}var _safeParseAsync=(_Err)=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:true}:{async:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?failure(_Err,result.issues,ctx):{success:true,data:result.value}};var safeParseAsync=_safeParseAsync($ZodRealError);var COMPILE_INVALID=Symbol.for("zod.compile.invalid");var COMPILE_FALLBACK=Symbol.for("zod.compile.fallback");var validate=(schema,value,_ctx)=>{const validator=schema._zod.bag.validator;if(validator!==undefined){if(validator(value)!==COMPILE_INVALID)return true;if(validator.definite===true&&_ctx===undefined)return false}return validateFallback(schema,value,_ctx)};function validateFallback(schema,value,_ctx){const ctx=_ctx?{..._ctx,async:false,abortEarly:true}:{async:false,abortEarly:true};const fallbackRun=schema._zod.bag.fallbackRun;let result;if(fallbackRun){ctx[COMPILE_FALLBACK]=true;result=fallbackRun({value,issues:[]},ctx)}else{result=schema._zod.run({value,issues:[]},ctx)}if(result instanceof Promise){throw new $ZodAsyncError}return result.issues.length===0}var validateAsync=async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:true,abortEarly:true}:{async:true,abortEarly:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length===0};var _encode=(_Err)=>{const parse=_parse(_Err);const fn=(schema,value,_ctx,_params)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return parse(schema,value,ctx,finalizeParams(fn,_params))};return fn};var encode=_encode($ZodRealError);var _decode=(_Err)=>{const parse=_parse(_Err);const fn=(schema,value,_ctx,_params)=>{return parse(schema,value,_ctx,finalizeParams(fn,_params))};return fn};var decode=_decode($ZodRealError);var _encodeAsync=(_Err)=>{const parseAsync=_parseAsync(_Err);const fn=async(schema,value,_ctx,_params)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return await parseAsync(schema,value,ctx,finalizeParams(fn,_params))};return fn};var encodeAsync=_encodeAsync($ZodRealError);var _decodeAsync=(_Err)=>{const parseAsync=_parseAsync(_Err);const fn=async(schema,value,_ctx,_params)=>{return await parseAsync(schema,value,_ctx,finalizeParams(fn,_params))};return fn};var decodeAsync=_decodeAsync($ZodRealError);var _safeEncode=(_Err)=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)};var safeEncode=_safeEncode($ZodRealError);var _safeDecode=(_Err)=>(schema,value,_ctx)=>{return _safeParse(_Err)(schema,value,_ctx)};var safeDecode=_safeDecode($ZodRealError);var _safeEncodeAsync=(_Err)=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)};var safeEncodeAsync=_safeEncodeAsync($ZodRealError);var _safeDecodeAsync=(_Err)=>async(schema,value,_ctx)=>{return _safeParseAsync(_Err)(schema,value,_ctx)};var safeDecodeAsync=_safeDecodeAsync($ZodRealError);var cuid=/^[cC][0-9a-z]{6,}$/;var cuid2=/^[0-9a-z]+$/;var ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;var xid=/^[0-9a-vA-V]{20}$/;var ksuid=/^[A-Za-z0-9]{27}$/;var nanoid=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(length){return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`)}var duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;var guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;var uuid=(version)=>{if(!version)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var uuid4=uuid(4);var uuid6=uuid(6);var uuid7=uuid(7);var email=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;var rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;var unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;var idnEmail=unicodeEmail;var browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;var _emoji=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function emoji(){return new RegExp(_emoji,"u")}var ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;var ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var mac=(delimiter)=>{const escapedDelim=escapeRegex(delimiter??":");return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`)};var cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;var cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;var base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;var base64url=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var domain=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/;var httpProtocol=/^https?$/;var e164=/^\+[1-9]\d{6,14}$/;var creditCard=/^\d(?:[ -]?\d){11,18}$/;var currencyCode=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;var iban=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/;var dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function anchor(source){return new RegExp(`^${source}$`)}var date=anchor(dateSource);function timeSource(args){const hhmm=`(?:[01]\\d|2[0-3]):[0-5]\\d`;const regex=typeof args.precision==="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:args.seconds?`${hhmm}:[0-5]\\d(?:\\.\\d+)?`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;return regex}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){const opts=["Z"];if(args.offset)opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);const qualified=`${timeSource({precision:args.precision,seconds:true})}(?:${opts.join("|")})`;const timeRegex=args.local?`${qualified}|${timeSource({precision:args.precision})}`:qualified;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var anyString=/^[\s\S]{0,}$/;var string=(params)=>{const regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:`[\\s\\S]*`;return new RegExp(`^${regex}$`)};var bigint=/^-?\d+n?$/;var integer=/^-?\d+$/;var number=/^-?\d+(?:\.\d+)?$/;var boolean=/^(?:true|false)$/i;var _null=/^null$/i;var _undefined=/^undefined$/i;var lowercase=/^[^A-Z]*$/;var uppercase=/^[^a-z]*$/;var hex=/^[0-9a-fA-F]*$/;function fixedBase64(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var md5_hex=/^[0-9a-fA-F]{32}$/;var md5_base64=fixedBase64(22,"==");var md5_base64url=fixedBase64url(22);var sha1_hex=/^[0-9a-fA-F]{40}$/;var sha1_base64=fixedBase64(27,"=");var sha1_base64url=fixedBase64url(27);var sha256_hex=/^[0-9a-fA-F]{64}$/;var sha256_base64=fixedBase64(43,"=");var sha256_base64url=fixedBase64url(43);var sha384_hex=/^[0-9a-fA-F]{96}$/;var sha384_base64=fixedBase64(64,"");var sha384_base64url=fixedBase64url(64);var sha512_hex=/^[0-9a-fA-F]{128}$/;var sha512_base64=fixedBase64(86,"==");var sha512_base64url=fixedBase64url(86);var $ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a;inst._zod??(inst._zod={});inst._zod.def=def;(_a=inst._zod).onattach??(_a.onattach=[])});var _whenHasSize=(payload)=>{const val=payload.value;return!nullish(val)&&val.size!==undefined};var _whenHasLength=(payload)=>{const val=payload.value;return!nullish(val)&&val.length!==undefined};var numericOriginMap={number:"number",bigint:"bigint",object:"date"};var $ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);const origin=numericOriginMap[typeof def.value];inst._zod.check=(payload)=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value){return}payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_big",maximum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}});var $ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);const origin=numericOriginMap[typeof def.value];inst._zod.check=(payload)=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value){return}payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_small",minimum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}});var $ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=(payload)=>{if(typeof payload.value!==typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");const isMultiple=typeof payload.value==="bigint"?def.value!==BigInt(0)&&payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0;if(isMultiple)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}});var $ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def);def.format=def.format||"float64";const isInt=def.format?.includes("int");const origin=isInt?"int":"number";const[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.check=(payload)=>{const input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:false,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0){payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:true,continue:!def.abort})}else{payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:true,continue:!def.abort})}return}}if(input<minimum){payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:true,inst,continue:!def.abort})}if(input>maximum){payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:true,inst,continue:!def.abort})}}});var $ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck.init(inst,def);const[minimum,maximum]=BIGINT_FORMAT_RANGES[def.format];inst._zod.check=(payload)=>{const input=payload.value;if(input<minimum){payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:true,inst,continue:!def.abort})}if(input>maximum){payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inclusive:true,inst,continue:!def.abort})}}});var $ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(inst,def)=>{var _a;$ZodCheck.init(inst,def);(_a=inst._zod.def).when??(_a.when=_whenHasSize);inst._zod.check=(payload)=>{const input=payload.value;const size=input.size;if(size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_big",maximum:def.maximum,inclusive:true,input,inst,continue:!def.abort})}});var $ZodCheckMinSize=$constructor("$ZodCheckMinSize",(inst,def)=>{var _a;$ZodCheck.init(inst,def);(_a=inst._zod.def).when??(_a.when=_whenHasSize);inst._zod.check=(payload)=>{const input=payload.value;const size=input.size;if(size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_small",minimum:def.minimum,inclusive:true,input,inst,continue:!def.abort})}});var $ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(inst,def)=>{var _a;$ZodCheck.init(inst,def);(_a=inst._zod.def).when??(_a.when=_whenHasSize);inst._zod.check=(payload)=>{const input=payload.value;const size=input.size;if(size===def.size)return;const tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:true,exact:true,input:payload.value,inst,continue:!def.abort})}});var $ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a;$ZodCheck.init(inst,def);(_a=inst._zod.def).when??(_a.when=_whenHasLength);inst._zod.check=(payload)=>{const input=payload.value;const units=input.length;const length=typeof input==="string"&&units>def.maximum?codePointLength(input):units;if(length<=def.maximum)return;const origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:true,input,inst,continue:!def.abort})}});var $ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a;$ZodCheck.init(inst,def);(_a=inst._zod.def).when??(_a.when=_whenHasLength);inst._zod.check=(payload)=>{const input=payload.value;const units=input.length;const length=typeof input==="string"&&units>=def.minimum&&units<def.minimum*2?codePointLength(input):units;if(length>=def.minimum)return;const origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:true,input,inst,continue:!def.abort})}});var $ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a;$ZodCheck.init(inst,def);(_a=inst._zod.def).when??(_a.when=_whenHasLength);inst._zod.check=(payload)=>{const input=payload.value;const units=input.length;const length=typeof input==="string"&&units>=def.length&&units<=def.length*2?codePointLength(input):units;if(length===def.length)return;const origin=getLengthableOrigin(input);const tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:true,exact:true,input:payload.value,inst,continue:!def.abort})}});var $ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a,_b;$ZodCheck.init(inst,def);if(def.pattern)(_a=inst._zod).check??(_a.check=(payload)=>{def.pattern.lastIndex=0;if(def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})});var $ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def);inst._zod.check=(payload)=>{def.pattern.lastIndex=0;if(def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}});var $ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase);$ZodCheckStringFormat.init(inst,def)});var $ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase);$ZodCheckStringFormat.init(inst,def)});var $ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);const escapedRegex=escapeRegex(def.includes);const pattern=new RegExp(typeof def.position==="number"?`^.{${def.position},}${escapedRegex}`:escapedRegex);def.pattern=pattern;inst._zod.check=(payload)=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}});var $ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);const pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern);inst._zod.check=(payload)=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}});var $ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);const pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern);inst._zod.check=(payload)=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});function handleCheckPropertyResult(result,payload,property){if(result.issues.length){payload.issues.push(...prefixIssues(property,result.issues))}}var $ZodCheckProperty=$constructor("$ZodCheckProperty",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=(payload)=>{const result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise){return result.then((result)=>handleCheckPropertyResult(result,payload,def.property))}handleCheckPropertyResult(result,payload,def.property);return}});var $ZodCheckProperties=$constructor("$ZodCheckProperties",(inst,def)=>{$ZodCheck.init(inst,def);hide(inst,Symbol.iterator,function*(){yield inst});let entries;inst._zod.check=(payload)=>{if(payload.value==null){payload.issues.push({expected:"object",code:"invalid_type",input:payload.value,inst});return}entries??(entries=Reflect.ownKeys(def.shape).map((key)=>[key,def.shape[key]]));const input=payload.value;let proms;for(const[key,schema]of entries){const result=schema._zod.run({value:input[key],issues:[]},{});if(result instanceof Promise){proms??(proms=[]);proms.push(result.then((result)=>handleCheckPropertyResult(result,payload,key)))}else{handleCheckPropertyResult(result,payload,key)}}if(proms)return Promise.all(proms).then(()=>{return});return}});var $ZodCheckMimeType=$constructor("$ZodCheckMimeType",(inst,def)=>{$ZodCheck.init(inst,def);const mimeSet=new Set(def.mime);inst._zod.check=(payload)=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}});var $ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=(payload)=>{payload.value=def.tx(payload.value)}});class Doc{constructor(args=[],closed={}){this.content=[];this.indent=0;this.args=args;this.closed=closed}indented(fn){this.indent+=1;try{fn(this)}finally{this.indent-=1}}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"});arg(this,{execution:"async"});return}const content=arg;const lines=content.split(`
|
|
9
9
|
`).filter((x)=>x);const minIndent=Math.min(...lines.map((x)=>x.length-x.trimStart().length));const dedented=lines.map((x)=>x.slice(minIndent)).map((x)=>" ".repeat(this.indent*2)+x);for(const line of dedented){this.content.push(line)}}compile(){const F=Function;const content=this?.content??[``];const factory=new F(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
10
10
|
${content.join(`
|
|
@@ -63,7 +63,37 @@ ${content.join(`
|
|
|
63
63
|
`);const fullCode=options?.debug?constantNames.length>0?`// Constants: ${constantNames.join(", ")}
|
|
64
64
|
${code}`:code:"";const F=Function;const factoryCode=`return (input) => {
|
|
65
65
|
${code}
|
|
66
|
-
}`;let fn;try{const factory=new F(...constantNames,factoryCode);fn=factory(...constantValues)}catch(err){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`)}if(options?.debug){fn.code=fullCode}fn.definite=ctx.definite;return fn}function addConstant(ctx,value){for(const[name,v]of ctx.constants){if(v===value)return name}const name=`c${ctx.constantCounter++}`;ctx.constants.set(name,value);return name}function addUserConstant(ctx,fn){ctx.definite=false;return addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value){const result=schema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;return r.issues.length===0?r.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=true){const contentLen=doc.content.length;const constantCount=ctx.constants.size;const constantCounter=ctx.constantCounter;const varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err){if(!(err instanceof ZodCompileUnsupportedError)||!err.islandable)throw err;doc.content.length=contentLen;if(ctx.constants.size>constantCount){const trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(const k of trailing)ctx.constants.delete(k)}ctx.constantCounter=constantCounter;ctx.varCounter=varCounter;return emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=false;const schemaConst=addConstant(ctx,schema);const runConst=addConstant(ctx,runtimeRun);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}var WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function generateChecks(doc,ctx,schema,accessor){const schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(const check of schemaChecks){const def=check._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check)){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{const min=numericOperand(def.minimum,"min_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{const max=numericOperand(def.maximum,"max_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max}`);doc.write(`if (${len} > ${max}) return INVALID;`);break}case"length_equals":{const exact=numericOperand(def.length,"length_equals");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{const newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor);currentAccessor=newAccessor;break}default:{throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){const cpLen=addConstant(ctx,codePointLength);const v=newVar(ctx);doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);return v}function numericOperand(value,label){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`)}return`${value}`}function comparisonOperand(ctx,value){if(typeof value==="bigint")return`${value}n`;if(typeof value==="number"){if(Number.isNaN(value))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value}`}if(value instanceof Date){if(Number.isNaN(value.getTime())){throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound")}return addConstant(ctx,value)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){const op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){const op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value==="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{const remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){const format=def.format;switch(format){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`number format ${format}`)}}}function generateBigIntFormatCheck(doc,def,accessor){const format=def.format;if(!format)return;switch(format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`bigint format ${format}`)}}}function generateMimeTypeCheck(doc,ctx,def,accessor){const mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){const mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}doc.write(`if (${accessor} == null) return INVALID;`);const shape=def.shape;for(const key of Reflect.ownKeys(shape)){const keyExpr=typeof key==="symbol"?addConstant(ctx,key):esc(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);compileChild(doc,ctx,shape[key],inputVar,false)}}function generatePropertyCheck(doc,ctx,def,accessor){const propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor){const tx=check._zod.def.tx;if(!tx){throw new ZodCompileUnsupportedError("overwrite check without a transform function")}if(isAsyncFunction(tx)){throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported")}const txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue){this.issues.push(issue)}function generateCustomRefineCheck(doc,ctx,check,accessor){const def=check._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`);return accessor}if(check._zod.check){if(isAsyncFunction(check._zod.check)){throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported")}const checkFn=check._zod.check;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=checkFn(fakePayload);if(result instanceof Promise)throwAsync();return fakePayload.issues.length===0?fakePayload.value:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${helperConst}(${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}var PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=true){const fmt=def.format;if(fmt==="base64"){const validator=addConstant(ctx,isValidBase64);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="base64url"){const validator=addConstant(ctx,isValidBase64URL);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="jwt"){const validator=addConstant(ctx,isValidJWT);const alg=addConstant(ctx,def.alg??null);doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`);return accessor}if(fmt==="ipv6"){const validator=addConstant(ctx,isValidIPv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="cidrv6"){const validator=addConstant(ctx,isValidCIDRv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="credit_card"){const validator=addConstant(ctx,isValidCreditCard);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="iban"){const validator=addConstant(ctx,isValidIBAN);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}const formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==undefined||formatDef.protocol!==undefined){const parseConst=addConstant(ctx,validateURL);const defConst=addConstant(ctx,def);const trimVar=newVar(ctx);const urlVar=newVar(ctx);doc.write(`const ${trimVar} = ${accessor}.trim();`);doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`);doc.write(`if (typeof ${urlVar} === "number") return INVALID;`);if(formatDef.hostname!==undefined){const hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==undefined){const protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;const outputVar=newVar(ctx);const outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;doc.write(`const ${outputVar} = ${outputExpr};`);return outputVar}const customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);const fnConst=addConstant(ctx,customFn);doc.write(`if (!${fnConst}(${accessor})) return INVALID;`);return accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){const patternConst=addConstant(ctx,def.pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);return accessor}const format=def.format;switch(format){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{const prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{const suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:{throw new ZodCompileUnsupportedError(`string format ${format}`)}}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=true){const def=schema._zod.def;const type=def.type;if(def.coerce){throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`)}const buildsValue=needsValue||!!def.checks?.length;let typeAccessor;switch(type){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;");typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{const innerOut=generateWrapperCheck(doc,ctx,schema,accessor);const frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`);typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor);typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:{throw new ZodCompileUnsupportedError(`schema type ${type}`)}}if(typeAccessor===null)return null;return generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=true){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const def=schema._zod.def;if(def.format===undefined)return accessor;return generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);const def=schema._zod.def;if(def.check==="number_format"&&def.format){generateNumberFormatCheck(doc,{format:def.format},accessor)}return accessor}function generateBooleanCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`);return accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);const def=schema._zod.def;if(def.format){switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}}return accessor}function generateSymbolCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`);return accessor}function generateUndefinedCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNullCheck(doc,accessor){doc.write(`if (${accessor} !== null) return INVALID;`);return accessor}function generateVoidCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNaNCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`);return accessor}function generateDateCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`);return accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);const shape=def.shape;const keys=Object.keys(shape);const symbolKeys=Object.getOwnPropertySymbols(shape);const allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;const keyExpr=(k)=>typeof k==="symbol"?addConstant(ctx,k):esc(k);const propKey=(k)=>typeof k==="symbol"?`[${keyExpr(k)}]`:esc(k);const propShape=shape;if(keys.includes("__proto__")){throw new ZodCompileUnsupportedError('object shape key "__proto__"')}const propOutputs=new Map;for(const key of allKeys){const propSchema=propShape[key];const kx=keyExpr(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${kx}];`);if(propSchema._zod.optin!==undefined){const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)});doc.write(`})();`);if(propSchema._zod.optout==="optional"){doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`if (${kx} in ${accessor}) return INVALID;`);d.write(`${outputVar} = undefined;`)});doc.write(`}`)}else{doc.write(`if (${outputVar} === INVALID) return INVALID;`)}propOutputs.set(key,outputVar)}else{if(requiresPresenceCheck(propSchema)){doc.write(`if (!(${kx} in ${accessor})) return INVALID;`)}const outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);if(outputAccessor!==null)propOutputs.set(key,outputAccessor)}}const catchall=def.catchall;let unknownKeysMode="none";if(catchall){const catchallType=catchall._zod.def.type;if(catchallType==="never"){const condition=keys.map((k)=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${condition}) return INVALID;`)});doc.write(`}`)}else if((catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length){unknownKeysMode="passthrough"}else{unknownKeysMode="schema"}}const outputVar=newVar(ctx);const hasConditionalKeys=allKeys.some((k)=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);compileChild(d,ctx,catchall,valVar,false)});doc.write(`}`)}return null}if(!hasConditionalKeys){const propLiterals=allKeys.map((k)=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}else{doc.write(`const ${outputVar} = {};`);for(const k of allKeys){const kx=keyExpr(k);const out=propOutputs.get(k);if(dropsWhenAbsent(propShape[k])){doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else if(mayOmitUndefined(propShape[k])){doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else{doc.write(`${outputVar}[${kx}] = ${out};`)}}}if(unknownKeysMode!=="none"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);if(unknownKeysMode==="passthrough"){d.write(`${outputVar}[k] = ${accessor}[k];`)}else{const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);const catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}});doc.write(`}`)}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;if(isExactOptional(schema)){return generateCheck(doc,ctx,def.innerType,accessor,buildsValue)}if(def.innerType._zod.optin==="defaulted"){const outputVar=newVar(ctx);const branchVar=newVar(ctx);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`const ${branchVar} = (() => {`);d.indented((d2)=>{const innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)});d.write(`})();`);d.write(`if (${branchVar} !== INVALID) ${outputVar} = ${branchVar};`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===true}function requiresPresenceCheck(schema){return schema._zod.optin===undefined&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return true;const def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return true;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return false;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):true;case"catch":return true;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):true;case"intersection":if(!def.left||!def.right)return true;return fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):true;default:return true}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){const def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":return true;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):true;case"union":return def.options?def.options.some(mayOutputUndefined):true;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):true;default:return true}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar} = null;`);doc.write(`if (${accessor} !== null) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const outputVar=buildsValue?newVar(ctx):null;const iVar=newVar(ctx);const elemVar=newVar(ctx);if(outputVar)doc.write(`const ${outputVar} = new Array(${accessor}.length);`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);if(outputVar&&elemOutput!==null)d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`);return outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const values=def.values;if(values.length!==1){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}const value=values[0];if(typeof value==="number"&&Number.isNaN(value)){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}if(typeof value==="string"){doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`)}else if(typeof value==="number"||typeof value==="boolean"){doc.write(`if (${accessor} !== ${value}) return INVALID;`)}else if(value===null){doc.write(`if (${accessor} !== null) return INVALID;`)}else if(value===undefined){doc.write(`if (${accessor} !== undefined) return INVALID;`)}else if(typeof value==="bigint"){doc.write(`if (${accessor} !== ${value}n) return INVALID;`)}else{throw new ZodCompileUnsupportedError(`literal type ${typeof value}`)}return accessor}function generateEnumCheck(doc,ctx,schema,accessor){const values=schema._zod.values;if(!values){throw new ZodCompileUnsupportedError("enum schema without enumerated values")}const enumSet=addConstant(ctx,values);doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);return accessor}function generateWrapperCheck(doc,ctx,schema,accessor){const def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const descriptor=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue");const defaultGetter=descriptor?()=>schema._zod.def.defaultValue:undefined;if(schema._zod.def.type==="prefault"){if(!defaultGetter){return generateCheck(doc,ctx,def.innerType,accessor)}const defaultFn=addConstant(ctx,defaultGetter);const inputVar=newVar(ctx);doc.write(`let ${inputVar} = ${accessor};`);doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);return generateCheck(doc,ctx,def.innerType,inputVar)}const outputVar=newVar(ctx);if(defaultGetter){const defaultFn=addConstant(ctx,defaultGetter);const cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)});doc.write(`}`)}else{doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`)}return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const innerOutput=generateCheck(doc,ctx,def.innerType,accessor);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${innerOutput};`);doc.write(`if (${outputVar} === undefined) return INVALID;`);return outputVar}function generateTupleCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const items=def.items;const rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const optinStart=getTupleOptStart2(items,"optin");const optoutStart=getTupleOptStart2(items,"optout");if(rest){doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`)}else{doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`)}const outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){const itemSchema=items[i];if(i>=optoutStart){doc.write(`if (${outputVar}.length === ${i}) {`);doc.indented((d)=>{d.write(`if (${i} < ${accessor}.length) {`);d.indented((d2)=>{const elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)});d.write(`} else {`);d.indented((d2)=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}const elemVar=newVar(ctx);const branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`);d2.write(`const ${branchVar} = (() => {`);d2.indented((d3)=>{const elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)});d2.write(`})();`);d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);d2.write(`else ${outputVar}[${i}] = ${branchVar};`)});d.write(`}`)});doc.write(`}`)}else{const elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){const iVar=newVar(ctx);const elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`)}return outputVar}function getTupleOptStart2(items,key){for(let i=items.length-1;i>=0;i--){const omittable=key==="optin"?items[i]._zod.optin!==undefined:items[i]._zod.optout==="optional";if(!omittable)return i+1}return 0}function generateUnionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const options=def.options;if(def.discriminator){return generateDiscriminatedUnionCheck(doc,ctx,def,accessor)}if(def.inclusive===false){throw new ZodCompileUnsupportedError("exclusive unions (z.xor)")}if(options.length===0){doc.write("return INVALID;");return accessor}if(options.length===1){return generateCheck(doc,ctx,options[0],accessor)}const allLiterals=options.every((opt)=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length);if(allLiterals){const values=new Set(options.flatMap((opt)=>opt._zod.def.values));const valuesConst=addConstant(ctx,values);doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);return accessor}const outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){const opt=options[i];if(i===0){doc.write(`${outputVar} = (() => {`)}else{doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`)}doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)});doc.write(`})();`)}doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback){throw new ZodCompileUnsupportedError("discriminated union with unionFallback")}if(def.options.length===0){doc.write("return INVALID;");return accessor}const discVar=newVar(ctx);const outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);doc.write(`let ${outputVar};`);let firstBranch=true;const claimed=new Set;for(const option of def.options){const values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0){throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values")}for(const value of values){if(claimed.has(value)){throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`)}claimed.add(value)}const conditions=Array.from(values,(value)=>literalEquality(ctx,discVar,value));const prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`);doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)});doc.write(`}`);firstBranch=false}doc.write(`else { return INVALID; }`);return outputVar}function literalEquality(ctx,accessor,value){if(typeof value==="string")return`${accessor} === ${esc(value)}`;if(typeof value==="number"){if(Number.isNaN(value))return`Number.isNaN(${accessor})`;return`${accessor} === ${value}`}if(typeof value==="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===undefined)return`${accessor} === undefined`;if(typeof value==="bigint")return`${accessor} === ${value}n`;if(typeof value==="symbol"){const symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;ctx.definite=false;const leftOutput=compileChild(doc,ctx,def.left,accessor);const rightOutput=compileChild(doc,ctx,def.right,accessor);const mergeConst=addConstant(ctx,mergeValues);const mergedVar=newVar(ctx);doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);doc.write(`if (!${mergedVar}.valid) return INVALID;`);return`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);const recordDef=def;const keyValues=recordDef.partial?undefined:def.keyType._zod.values;if(keyValues){const inputKeys=[];for(const key of keyValues){if(!(typeof key==="string"||typeof key==="number"||typeof key==="symbol")){throw new ZodCompileUnsupportedError(`record key value ${String(key)}`)}const inputKey=typeof key==="number"?key.toString():key;if(inputKey==="__proto__"){throw new ZodCompileUnsupportedError('record key "__proto__"')}inputKeys.push(inputKey);const keyConst=addConstant(ctx,key);const outKey=generateCheck(doc,ctx,def.keyType,keyConst);const valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);const valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}const knownKeysConst=addConstant(ctx,new Set(inputKeys));doc.write(`for (const ${kVar} in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);if(recordDef.mode==="loose"){d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`)}else{d.write(`return INVALID;`)}});doc.write(`}`);return outputVar}const keyDef=def.keyType._zod.def;const keyIsBareString=keyDef.type==="string"&&keyDef.format===undefined&&!keyDef.coerce&&(keyDef.checks?.length??0)===0;if(!keyIsBareString){const isLoose=def.mode==="loose";const keyFn=compileFn(def.keyType);if(keyFn.definite===false)ctx.definite=false;const keyFast=addConstant(ctx,keyFn);const numericConst=addConstant(ctx,number);const outKeyVar=newVar(ctx);emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);if(isLoose){d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`)}else{d.write(`if (${outKeyVar} === INVALID) return INVALID;`)}d.write(`if (${outKeyVar} === "__proto__") continue;`);const valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)});return outputVar}emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},`return INVALID;`);return outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){const propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable);const symsVar=newVar(ctx);const keysVar=newVar(ctx);const iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`);d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);body(d)});doc.write(`}`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`);d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);if(onSymbol)d.write(onSymbol);else body(d)});doc.write(`}`)}function literalPropertyKey(ctx,key){if(typeof key==="string")return esc(key);return addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Map();`);doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);doc.indented((d)=>{const keyOutput=generateCheck(d,ctx,def.keyType,kVar);const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)});doc.write(`}`);return outputVar}function generateSetCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);const outputVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Set();`);doc.write(`for (const ${valVar} of ${accessor}) {`);doc.indented((d)=>{const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)});doc.write(`}`);return outputVar}function generateFileCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);return accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const pattern=schema._zod.pattern;if(pattern){const patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const getterConst=addUserConstant(ctx,def.getter);const cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`);doc.indented((d)=>{d.write(`const inner = ${getterConst}();`);d.write(`${cacheConst}.parser = function(input) {`);d.indented((d2)=>{d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);d2.write(`return result.issues.length === 0 ? result.value : INVALID;`)});d.write(`};`)});doc.write(`}`);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generatePipeCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const transformedVar=newVar(ctx);doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);doc.write(`if (${transformedVar} === INVALID) return INVALID;`);return generateCheck(doc,ctx,def.out,transformedVar)}else{return generateCheck(doc,ctx,def.out,inputOutput)}}function isAsyncFunction(fn){return typeof fn==="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`)}else{throw new ZodCompileUnsupportedError("custom schema without a predicate function")}return accessor}function runtimeCatch(innerSchema,catchValue,value){const result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;if(r.issues.length===0)return r.value;return catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH]){throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",false)}const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)});doc.write(`})();`);const innerConst=addConstant(ctx,def.innerType);const catchConst=addUserConstant(ctx,def.catchValue);const catchHelperConst=addConstant(ctx,runtimeCatch);doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);d.write(`if (${outputVar} === INVALID) return INVALID;`)});doc.write(`}`);return outputVar}function generateTransformCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}return accessor}function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return def}function _string(Class,params){return new Class(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class,params){return new Class(snapshotChecks({type:"string",coerce:true,...normalizeParams(params)}))}function _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class,params){return new Class({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _creditCard(Class,params){return new Class({type:"string",format:"credit_card",check:"string_format",abort:false,...normalizeParams(params)})}function _iban(Class,params){return new Class({type:"string",format:"iban",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class,params){return new Class(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class,params){return new Class(snapshotChecks({type:"number",coerce:true,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class,params){return new Class({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class,params){return new Class({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class,params){return new Class({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class,params){return new Class({type:"symbol",...normalizeParams(params)})}function _undefined2(Class,params){return new Class({type:"undefined",...normalizeParams(params)})}function _null2(Class,params){return new Class({type:"null",...normalizeParams(params)})}function _any(Class){return new Class({type:"any"})}function _unknown(Class){return new Class({type:"unknown"})}function _never(Class,params){return new Class({type:"never",...normalizeParams(params)})}function _void(Class,params){return new Class({type:"void",...normalizeParams(params)})}function _date(Class,params){return new Class({type:"date",...normalizeParams(params)})}function _coercedDate(Class,params){return new Class({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class,params){return new Class({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class,element,params){return new Class({type:"array",element,...normalizeParams(params)})}function _union(Class,options,params){return new Class({type:"union",options,...normalizeParams(params)})}function _xor(Class,options,params){return new Class({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class,discriminator,options,params){return new Class({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class,left,right){return new Class({type:"intersection",left,right})}function _tuple(Class,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class,keyType,valueType,params){return new Class({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class,keyType,valueType,params){return new Class({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class,valueType,params){return new Class({type:"set",valueType,...normalizeParams(params)})}function _enum(Class,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class,entries,params){return new Class({type:"enum",entries,...normalizeParams(params)})}function _literal(Class,value,params){return new Class({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class,params){return new Class({type:"file",...normalizeParams(params)})}function _transform(Class,fn){return new Class({type:"transform",transform:fn})}function _optional(Class,innerType){return new Class({type:"optional",innerType})}function _nullable(Class,innerType){return new Class({type:"nullable",innerType})}function _default(Class,innerType,defaultValue){return new Class({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class,innerType,params){return new Class({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class,innerType){return new Class({type:"success",innerType})}function _catch(Class,innerType,catchValue){return new Class({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class,in_,out){return new Class({type:"pipe",in:in_,out})}function _readonly(Class,innerType){return new Class({type:"readonly",innerType})}function _templateLiteral(Class,parts,params){return new Class({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class,getter){return new Class({type:"lazy",getter})}function _promise(Class,innerType){return new Class({type:"promise",innerType})}function _custom(Class,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class,fn,_params){const schema=new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:false});return{}}},reverseTransform:(input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}},error:params.error});codec._zod.bag.truthy=truthyArray;codec._zod.bag.falsy=falsyArray;codec._zod.bag.case=params.case??"insensitive";return codec}function _stringFormat(Class,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class(def);return inst}function assignProps(target,...sources){for(const source of sources){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProp(target,key,source[key])}}}return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:undefined,sharedEmitDoneFor:undefined,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??undefined}}function handleUnrepresentable(schema,ctx,json,params,message){const result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return false;if(result===undefined||result==="throw")throw new Error(message);Object.assign(json,result);return true}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);ctx.sharedDefsExtractedFor=undefined;ctx.sharedEmitDoneFor=undefined;const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a=result.schema).default??(_a.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id)=>id);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id){return{ref:uriPrefix}}const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema=seen.schema;for(const key in schema){delete schema[key]}schema.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry)}}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){const options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==undefined)return;const types=[];for(const option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);const keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;const type=option.type;for(const member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf;schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]);var UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){const extra=member.additionalProperties;if(extra===undefined||extra===false||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){const objects=[];for(const member of members){if(typeof member!=="object"||member.type!=="object")return null;for(const key in member){if(!FOLDABLE_KEYS.has(key))return null}objects.push(member)}const properties={};const required=new Set;for(const object of objects){for(const key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;const parts=[];for(const other of objects){const part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===undefined)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}const merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(const key of object.required??[])required.add(key)}const folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===false)){folded.additionalProperties=false}else{const constraints=[];for(const object of objects){const constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(constraints.length>1)folded.additionalProperties={allOf:constraints}}return folded}function foldIntersection(json){const allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(const key of FOLDABLE_KEYS)if(key in json)return;const unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k])));let folded=null;if(!unions.length){folded=foldObjects(allOf)}else{const union=unions[0];const keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;const rest=allOf.filter((m)=>m!==union);const branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf;assignProps(json,folded)}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema=seen.def??seen.schema;const _cached={...schema};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema.allOf=schema.allOf??[];schema.allOf.push(refSchema)}else{assignProps(schema,refSchema)}assignProps(schema,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])){delete schema[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])){delete schema[key]}}}}}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}if(ctx.target!=="openapi-3.0"){for(const entry of ctx.seen.entries()){compactTypeUnion(entry[1].def??entry[1].schema)}}for(const rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){const carriers=new Map;for(const seen of ctx.seen.values()){for(const json of[seen.schema,seen.def]){const allOf=json?.allOf;if(!Array.isArray(allOf))continue;const existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}}for(const allOf of ctx.intersections){for(const json of carriers.get(allOf)??[])foldIntersection(json)}}}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===undefined||value>agg[key])agg[key]=value};var narrowMax=(agg,key,value)=>{if(agg[key]===undefined||value<agg[key])agg[key]=value};var narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value);narrowMax(agg,"maximum",value)};var addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]);if(!agg.multipleOf.includes(value))agg.multipleOf.push(value)};var addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set);agg.patterns.add(pattern)};var intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]};var setFormat=(agg,format)=>{agg.format=format;if(format.includes("int"))agg.isInt=true};var minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum);var maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum);var formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);const[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum);narrowMax(agg,"maximum",maximum)};var contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format);if(def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=true},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){const agg={};const def=schema._zod.def;const list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(const ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);const bag=schema._zod.bag;if(bag.minimum!==undefined)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==undefined)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==undefined)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==undefined)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==undefined)addDivisor(agg,bag.multipleOf);if(bag.format!==undefined){agg.format??(agg.format=bag.format);if(bag.format.includes("int"))agg.isInt=true}if(bag.mime)intersectMime(agg,bag.mime);for(const pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]);var exactPattern=(p)=>exactPatterns.get(p)??p;var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"||laxFormat){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(patternList.length>1){json.allOf=[...patternList.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};var numberProcessor=(schema,ctx,_json,params)=>{const json=_json;const{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(multipleOf){const divisors=new Set;for(const divisor of multipleOf){if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`)}const[first,...rest]=divisors;if(first!==undefined)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")};var symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0"){json.type="string";json.nullable=true;json.enum=[null]}else{json.type="null"}};var undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")};var voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Void cannot be represented in JSON Schema")};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var anyProcessor=(_schema,_ctx,_json,_params)=>{};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var dateProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;if(def.values.length===0){json.not={};return}const vals=[];for(const val of def.values){if(val===undefined){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")};var templateLiteralProcessor=(schema,_ctx,json,_params)=>{const _json=json;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};var fileProcessor=(schema,_ctx,json,_params)=>{const _json=json;_json.type="string";_json.format="binary";_json.contentEncoding="binary";const{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==undefined)_json.minLength=minimum;if(maximum!==undefined)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))};var successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")};var setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){const def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")){return inputOptin(def.out)}if(def.type==="catch"){return inputOptin(def.innerType)}return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const shape=def.shape;const symbolKeys=Object.getOwnPropertySymbols(shape);if(symbolKeys.length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema")){return}json.type="object";json.properties={};for(const key in shape){assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}))}const requiredKeys=[];for(const key of Object.keys(shape)){const field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===undefined:field._zod.optout===undefined){requiredKeys.push(key)}}if(requiredKeys.length>0){json.required=requiredKeys}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf;ctx.intersections.push(allOf)};var tupleProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;let minItems=def.items.length;while(minItems>0){const item=def.items[minItems-1];const optional=ctx.io==="input"?inputOptin(item)!==undefined:item._zod.optout==="optional";if(!optional)break;minItems--}const maxItems=def.items.length;const isClosed=!def.rest;if(ctx.target==="draft-2020-12"){json.prefixItems=prefixItems;if(isClosed){json.items=false}else if(rest){json.items=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){json.items={anyOf:prefixItems};if(rest){json.items.anyOf.push(rest)}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{json.items=prefixItems;if(isClosed){json.additionalItems=false}else if(rest){json.additionalItems=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);const def=bySchema.get(json)?.def;if(!def)return json;const inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(const keyword of["anyOf","oneOf"]){const branches=json[keyword];if(!Array.isArray(branches))continue;const mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}const types=Array.isArray(json.type)?json.type:[json.type];const numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer");const values=json.enum??(json.const!==undefined?[json.const]:undefined);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;const{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;rest.type="string";if(!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){const bySchema=new Map;for(const entry of ctx.seen.values()){if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry)}const rewrites=new Map;for(const record of pendingRecords.get(ctx)??[]){const seen=ctx.seen.get(record);const names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===true||rewrites.has(names))continue;const rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(const entry of ctx.seen.values()){for(const carrier of[entry.schema,entry.def]){const rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}}var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);if(!pending){pending=[];pendingRecords.set(ctx,pending);ctx.deferred.push(()=>rewriteKeyNames(ctx))}pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;const omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==undefined;if(keyValues&&!def.partial&&!omittableOnInput){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues.map(String)}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=false;const serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;unrepresentable=true;return null});if(!unrepresentable)return JSON.parse(serialized);handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema");return UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io!=="input")return;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){const registry=input;const ctx=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry._idmap.entries()){const[_,schema]=entry;processSchema(schema,ctx)}const schemas={};const external={registry,uri:params?.uri,defs};ctx.external=external;for(const entry of registry._idmap.entries()){const[key,schema]=entry;extractDefs(ctx,schema);assignProp(schemas,key,finalize(ctx,schema))}if(Object.keys(defs).length>0){const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});processSchema(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}this.ctx.sharedDefsExtractedFor=undefined;this.ctx.sharedEmitDoneFor=undefined;extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const value=make(this);Object.defineProperty(this,key,{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,key,{value,configurable:true,writable:true})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";const proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_installedErrorProtos.add(proto);_lazyMethod(proto,"format",(self)=>(mapper)=>formatError(self,mapper));_lazyMethod(proto,"flatten",(self)=>(mapper)=>flattenError(self,mapper));_lazyMethod(proto,"addIssue",(self)=>(issue)=>{self.issues.push(issue);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});_lazyMethod(proto,"addIssues",(self)=>(issues)=>{self.issues.push(...issues);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});Object.defineProperty(proto,"isEmpty",{configurable:true,enumerable:false,get(){return this.issues.length===0}})};var ZodError=$constructor("ZodError",initializer2);var ZodRealError=$constructor("ZodError",initializer2,undefined,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode2=_encode(ZodRealError);var decode2=_decode(ZodRealError);var encodeAsync2=_encodeAsync(ZodRealError);var decodeAsync2=_decodeAsync(ZodRealError);var safeEncode2=_safeEncode(ZodRealError);var safeDecode2=_safeDecode(ZodRealError);var safeEncodeAsync2=_safeEncodeAsync(ZodRealError);var safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{_ensureDefaultLocale();$ZodType.init(inst,def);inst.def=def;inst.type=def.type;return inst},{check(...chks){const def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){reg.add(this,meta);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get "~standard"(){return hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){own(this,"~standard",value)},parse:function _parse(data,params){return parse3(this,data,params,{callee:_parse})},parseAsync:async function _parseAsync(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode(data,params){return encode2(this,data,params,{callee:_encode})},decode:function _decode(data,params){return decode2(this,data,params,{callee:_decode})},encodeAsync:async function _encodeAsync(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},derived({format:(inst)=>aggregateChecks(inst).format??null,minLength:(inst)=>aggregateChecks(inst).minimum??null,maxLength:(inst)=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));var ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def);ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def);ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=exports_regexes[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);inst.isFinite=true},derived({minValue:(inst)=>{const{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{const{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{const{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:(inst)=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},derived({minValue:(inst)=>aggregateChecks(inst).minimum??null,maxValue:(inst)=>aggregateChecks(inst).maximum??null,format:(inst)=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params))},derived({minDate:(inst)=>{const{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:(inst)=>{const{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer();$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);installLazyProp(inst,"shape",(self)=>self._zod.def.shape,false)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:undefined}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit(this,mask)},partial(...args){return partial(ZodOptional,this,args[0])},exactPartial(...args){return partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return required(ZodNonOptional,this,args[0])}});function object(shape,params){const def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer();$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){const def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map((item)=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer();$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params),partial:true})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer();$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer();$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=[...inst._zod.values];const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer();$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst);payload.issues.push(issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output)=>{payload.value=output;return payload})}payload.value=output;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe;var meta2=meta;var ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){const inst=new ZodInstanceOf({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:true,...normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=(payload)=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){const jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map){config({customError:map})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...exports_schemas2,...exports_checks2,iso:exports_iso};var RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1]===undefined?undefined:decodeJSONPointerSegment(path[1]);if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const value=payload.value;if(typeof value!=="object"||value===null||Array.isArray(value))return;const keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==undefined&&keys.length<guards.minProperties){payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:true,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.maxProperties!==undefined&&keys.length>guards.maxProperties){payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:true,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.keySchema){for(const key of keys){const result=guards.keySchema.safeParse(key);if(result.success)continue;payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:true})}}});return guard.pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";const type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;const raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){const parts=[];for(const item of value){const key=canonicalKey(item,seen);if(key===null)return null;parts.push(key)}return`a${parts.length}:[${parts.join(",")}]`}const keys=Object.keys(value).sort();const parts=[];for(const k of keys){const key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]);var SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value){if(typeof value!=="object"||value===null)return false;if(Array.isArray(value))return value.some(containsRef);if(typeof value.$ref==="string")return true;return Object.entries(value).some(([key,sub])=>{if(SCHEMA_KEYWORDS.has(key))return containsRef(sub);if(!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!=="object"||sub===null)return false;return Object.values(sub).some(containsRef)})}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const items=payload.value;if(!Array.isArray(items))return;if(guards.uniqueItems===true){const firstSeen=new Map;for(let i=0;i<items.length;i++){const key=canonicalKey(items[i],new Set);if(key===null)continue;const first=firstSeen.get(key);if(first===undefined){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:true})}}if(guards.containsSchema){const minContains=guards.minContains??1;const ceiling=guards.maxContains!==undefined?guards.maxContains+1:Number.POSITIVE_INFINITY;let matches=0;for(const item of items){if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break}if(matches<minContains){payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:true})}if(guards.maxContains!==undefined&&matches>guards.maxContains){payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:true})}}});return guard.pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema===false){return}if(restSchema===undefined||restSchema===true){return z.any()}return convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==undefined){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==undefined){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==undefined){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==undefined||schema.then!==undefined||schema.else!==undefined){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==undefined||schema.dependentRequired!==undefined){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema);ctx.processing.delete(refPath);return zodSchema}if(schema.enum!==undefined){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every((v)=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==undefined){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map((t)=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime({offset:true}))}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.regex(fullTime))}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="hostname"){stringSchema=stringSchema.check(z.hostname())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="credit_card"){stringSchema=stringSchema.check(z.creditCard())}else if(format==="iban"){stringSchema=stringSchema.check(z.iban())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"&&schema.exclusiveMinimum!==true){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"&&schema.exclusiveMaximum!==true){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);const additionalSchema=typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):undefined;for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}if(schema.additionalProperties===false){const propertyKeys=Object.keys(shape);const patterns=patternKeys.map((p)=>new RegExp(p));const basePatternSchema=zodSchema;zodSchema=zodSchema.check((payload)=>{if(!isPlainObject(payload.value))return;const unrecognized=[];for(const key of Object.keys(payload.value)){if(propertyKeys.includes(key))continue;if(patterns.some((regex)=>regex.test(key)))continue;unrecognized.push(key)}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})}})}}else{const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(additionalSchema){zodSchema=objectSchema.catchall(additionalSchema)}else{zodSchema=objectSchema.passthrough()}}const hasKeyGuard=schema.propertyNames!==undefined&&schema.propertyNames!==true;const minProperties=typeof schema.minProperties==="number"?schema.minProperties:undefined;const maxProperties=typeof schema.maxProperties==="number"?schema.maxProperties:undefined;if(hasKeyGuard||minProperties!==undefined||maxProperties!==undefined){let keySchema;if(hasKeyGuard){const keyJSONSchema=typeof schema.propertyNames==="object"&&schema.propertyNames.type===undefined?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=prefixItems.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=!Array.isArray(items)?getTupleRest(items,ctx):undefined;const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=items.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=getTupleRest(schema.additionalItems,ctx);const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==undefined){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}if(schema.uniqueItems===true||schema.contains!==undefined){zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===true,containsSchema:schema.contains!==undefined?convertSchema(schema.contains,ctx):undefined,minContains:typeof schema.minContains==="number"?schema.minContains:undefined,maxContains:typeof schema.maxContains==="number"?schema.maxContains:undefined})}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==undefined||schema.const!==undefined;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map((s)=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map((s)=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==undefined){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}if(schema.type==="object"&&schema.$ref===undefined){if(schema.propertyNames!==undefined&&!containsRef(schema.propertyNames)){extraMeta.propertyNames=schema.propertyNames}for(const key of["minProperties","maxProperties"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}if(schema.type==="array"&&schema.$ref===undefined){if(schema.contains!==undefined&&!containsRef(schema.contains)){extraMeta.contains=schema.contains}for(const key of["uniqueItems","minContains","maxContains"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){assignProp(extraMeta,key,schema[key])}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){const fn=typeof fnOrHandlers==="function"?fnOrHandlers:(node,rewritten)=>{const h=fnOrHandlers[node._zod.def.type];return h?h(node,rewritten):node};const cache=new Map;function run(s){const cached=cache.get(s);if(cached===RESOLVING){return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)})}if(cached!==undefined)return cached;cache.set(s,RESOLVING);const inner=mapInner(s);const mapped=fn(inner,inner!==s);cache.set(s,mapped);return mapped}function mapInner(s){const def=s._zod.def;const kind=def.type;switch(kind){case"object":{const oldShape=def.shape;const keys=Object.keys(oldShape);let changed=false;const newShape={};for(const k of keys){const mapped=run(oldShape[k]);if(mapped!==oldShape[k])changed=true;newShape[k]=mapped}let newCatchall=def.catchall;if(def.catchall){newCatchall=run(def.catchall);if(newCatchall!==def.catchall)changed=true}return changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{const mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{const oldItems=def.items;let changed=false;const newItems=[];for(const item of oldItems){const mapped=run(item);if(mapped!==item)changed=true;newItems.push(mapped)}let newRest=def.rest;if(def.rest){newRest=run(def.rest);if(newRest!==def.rest)changed=true}return changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{const newKey=run(def.keyType);const newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{const newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{const oldOptions=def.options;let changed=false;const newOptions=[];for(const opt of oldOptions){const mapped=run(opt);if(mapped!==opt)changed=true;newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{const newLeft=run(def.left);const newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{const newIn=run(def.in);const newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{const newInput=run(def.input);const newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{const original=def.getter;const{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:{return s}}}return run(schema)}function deepPartial(schema){return visit(schema,{object:(s)=>s.partial(),union:(s)=>{const def=s._zod.def;return def.discriminator===undefined?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;const def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:true})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:(s)=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:(s)=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}import path from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream}from"node:fs";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");init_internal_capability();function normalizeDialogPolicy(policy){return policy??{accept:true}}function dialogFromOpening(params={}){return{type:params.type,message:params.message,defaultPrompt:params.defaultPrompt??"",url:params.url}}function decisionFromResult(result){if(typeof result==="boolean")return{accept:result};if(result&&typeof result==="object"){const decision={accept:result.accept!==false};if(result.promptText!==undefined)decision.promptText=result.promptText;return decision}return{accept:true}}async function resolveDialogAction(policy,params={}){try{const result=typeof policy==="function"?await policy(dialogFromOpening(params)):policy;return decisionFromResult(result)}catch{return{accept:true}}}var __defProp2=Object.defineProperty;var __exportAll=(definitions,namespace)=>{const exports={};for(const name in definitions)__defProp2(exports,name,{get:definitions[name],enumerable:true});if(!namespace)__defProp2(exports,Symbol.toStringTag,{value:"Module"});return exports};var __esmMin=(factory,value,error)=>()=>{if(error)throw error[0];try{return factory&&(value=factory(factory=0)),value}catch(caught){error=[caught];throw caught}};if(!Promise.withResolvers){Promise.withResolvers=()=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}class Emittery{#listeners=new Map;on(name,listener){const listeners=this.#listeners.get(name)??new Set;listeners.add(listener);this.#listeners.set(name,listeners);return()=>{listeners.delete(listener)}}async emit(name,data){const event={data,eventName:name};await Promise.all([...this.#listeners.get(name)??[]].map((listener)=>listener(event)))}clearListeners(){this.#listeners.clear()}}var{object:object2,string:string$2,number:number$2,array:array2,union:union$1,unknown:unknown$1,null:_null4}=exports_zod;var SESSION_ARTIFACTS_DIR=path.join(tmpdir(),"omowright-artifacts");var noop=()=>{};var init_emittery=noop;var init_zod=noop;var init_context=noop;var init_utils$13=noop;var init_config=noop;var init_extension_bridge=noop;var init_commands$1=noop;var init_directory=noop;var init_process=noop;var init_event_bus=noop;var init_state_db=noop;var init_schema=noop;var init_store$1=noop;var init_drizzle_orm=noop;var init_types$8=noop;var init_nanoid=noop;function sleep$12(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason??Error("Aborted"));const onAbort=()=>{clearTimeout(timer);reject(signal.reason??Error("Aborted"))};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);signal?.addEventListener("abort",onAbort,{once:true})})}function getCurrentReplAbortSignal(){return}function withCurrentReplAbort(fn){return fn()}function withoutReplContext(fn){return fn()}function replPrint(...values){console.warn(...values)}async function sendCommandToExtension(command){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}var stateDb=()=>{throw new UnsupportedOperationError("Daemon persistence is unavailable")};var NotificationGrantTable={};function spawnCommand(){throw new UnsupportedOperationError("Video recording is unavailable")}async function waitForExitCode(){return 1}function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof Vn.status==`number`&&(Vn.status===401||Vn.status===403)||typeof Vn.response?.status==`number`&&(Vn.response.status===401||Vn.response.status===403)||typeof Vn.error?.status==`number`&&(Vn.error.status===401||Vn.error.status===403)||typeof Vn.cause?.status==`number`&&(Vn.cause.status===401||Vn.cause.status===403)||String(Vn.error?.message??``).includes(`Missing or invalid Authorization header.`)||String(Vn.cause?.message??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}var DEFAULT_COMMAND_TIMEOUT_MS;var DEFAULT_RECONNECT_DELAYS_MS;var jsonVersionSchema;var jsonTargetSchema;var cdpWireMessageSchema;var BrowserCdpCommandError;var CdpClient;var init_client$6=__esmMin(()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=30000,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3000],jsonVersionSchema=object2({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object2({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object2({id:number$2(),sessionId:string$2().optional(),error:object2({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object2({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null4()]),BrowserCdpCommandError=class extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`),this.method=xn,this.code=jn,this.data=Vn}},CdpClient=class{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#l=new Emittery;#u=false;transportEvents=new Emittery;constructor(xn={}){if(typeof xn.cdpUrl!=`string`||xn.cdpUrl===``)throw TypeError(`CdpClient requires a cdpUrl: there is no default endpoint, so a missing URL can never reach a browser on 127.0.0.1:9222`);this.cdpUrl=normalizeBaseUrl(xn.cdpUrl),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS,this.#dialogPolicy=normalizeDialogPolicy(xn.dialogPolicy)}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(xn){this.#dialogPolicy=normalizeDialogPolicy(xn)}get isConnected(){return this.#r?.readyState===wrapper_default.OPEN}start(){this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b()}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array2(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=true,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();let Yn=this.#r;if(!Yn||Yn.readyState!==wrapper_default.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==undefined&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):undefined,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:undefined;if(this.#c.set(Zn,{method:String(xn),reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai,{once:true}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=wrapper_default.OPEN)try{xn.close(1000,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:true});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}async#g(){let xn=null,jn=false;for(let Vn of this.#n){Vn>0&&await sleep$12(Vn);try{await this.#_({forceRefresh:jn});return}catch(Vn){let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=true)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={}){let{headers:jn,wsUrl:Vn}=await this.#m(xn);await new Promise((xn,qn)=>{let Jn=new wrapper_default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{Yn||(Yn=true,this.#v(Jn),xn())}),Jn.addEventListener(`message`,(xn)=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,(xn)=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:true}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch((xn)=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=true,jn&&jn!==xn&&jn.readyState<=wrapper_default.OPEN)try{jn.close(1000,`replaced`)}catch{}}#y(xn){this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch((xn)=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b()}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3000;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b()})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(typeof Vn.id==`number`){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method;if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;resolveDialogAction(this.#dialogPolicy,Vn.params).then((dialogAction)=>{let xn=this.#r;xn?.readyState===wrapper_default.OPEN&&xn.send(JSON.stringify({id:this.#s++,method:`Page.handleJavaScriptDialog`,params:dialogAction,sessionId:dialogSessionId}))})}let jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)})}}}}});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,(xn)=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,(xn)=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map((xn)=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find((jn)=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:true});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}});var init_cdp=__esmMin(()=>{init_client$6(),init_session_manager()});var BUNDLE$1;var init_omowright_world_bundle=__esmMin(()=>{BUNDLE$1=pageBundle});var MAX_BUFFER_SIZE;var CONSOLE_INTERCEPTOR_SCRIPT;var PageConsole;var init_console_capture=__esmMin(()=>{MAX_BUFFER_SIZE=1000,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){
|
|
66
|
+
}`;let fn;try{const factory=new F(...constantNames,factoryCode);fn=factory(...constantValues)}catch(err){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`)}if(options?.debug){fn.code=fullCode}fn.definite=ctx.definite;return fn}function addConstant(ctx,value){for(const[name,v]of ctx.constants){if(v===value)return name}const name=`c${ctx.constantCounter++}`;ctx.constants.set(name,value);return name}function addUserConstant(ctx,fn){ctx.definite=false;return addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value){const result=schema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;return r.issues.length===0?r.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=true){const contentLen=doc.content.length;const constantCount=ctx.constants.size;const constantCounter=ctx.constantCounter;const varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err){if(!(err instanceof ZodCompileUnsupportedError)||!err.islandable)throw err;doc.content.length=contentLen;if(ctx.constants.size>constantCount){const trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(const k of trailing)ctx.constants.delete(k)}ctx.constantCounter=constantCounter;ctx.varCounter=varCounter;return emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=false;const schemaConst=addConstant(ctx,schema);const runConst=addConstant(ctx,runtimeRun);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}var WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function generateChecks(doc,ctx,schema,accessor){const schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(const check of schemaChecks){const def=check._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check)){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{const min=numericOperand(def.minimum,"min_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{const max=numericOperand(def.maximum,"max_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max}`);doc.write(`if (${len} > ${max}) return INVALID;`);break}case"length_equals":{const exact=numericOperand(def.length,"length_equals");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{const newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor);currentAccessor=newAccessor;break}default:{throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){const cpLen=addConstant(ctx,codePointLength);const v=newVar(ctx);doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);return v}function numericOperand(value,label){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`)}return`${value}`}function comparisonOperand(ctx,value){if(typeof value==="bigint")return`${value}n`;if(typeof value==="number"){if(Number.isNaN(value))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value}`}if(value instanceof Date){if(Number.isNaN(value.getTime())){throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound")}return addConstant(ctx,value)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){const op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){const op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value==="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{const remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){const format=def.format;switch(format){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`number format ${format}`)}}}function generateBigIntFormatCheck(doc,def,accessor){const format=def.format;if(!format)return;switch(format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`bigint format ${format}`)}}}function generateMimeTypeCheck(doc,ctx,def,accessor){const mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){const mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}doc.write(`if (${accessor} == null) return INVALID;`);const shape=def.shape;for(const key of Reflect.ownKeys(shape)){const keyExpr=typeof key==="symbol"?addConstant(ctx,key):esc(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);compileChild(doc,ctx,shape[key],inputVar,false)}}function generatePropertyCheck(doc,ctx,def,accessor){const propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor){const tx=check._zod.def.tx;if(!tx){throw new ZodCompileUnsupportedError("overwrite check without a transform function")}if(isAsyncFunction(tx)){throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported")}const txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue){this.issues.push(issue)}function generateCustomRefineCheck(doc,ctx,check,accessor){const def=check._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`);return accessor}if(check._zod.check){if(isAsyncFunction(check._zod.check)){throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported")}const checkFn=check._zod.check;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=checkFn(fakePayload);if(result instanceof Promise)throwAsync();return fakePayload.issues.length===0?fakePayload.value:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${helperConst}(${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}var PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=true){const fmt=def.format;if(fmt==="base64"){const validator=addConstant(ctx,isValidBase64);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="base64url"){const validator=addConstant(ctx,isValidBase64URL);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="jwt"){const validator=addConstant(ctx,isValidJWT);const alg=addConstant(ctx,def.alg??null);doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`);return accessor}if(fmt==="ipv6"){const validator=addConstant(ctx,isValidIPv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="cidrv6"){const validator=addConstant(ctx,isValidCIDRv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="credit_card"){const validator=addConstant(ctx,isValidCreditCard);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="iban"){const validator=addConstant(ctx,isValidIBAN);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}const formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==undefined||formatDef.protocol!==undefined){const parseConst=addConstant(ctx,validateURL);const defConst=addConstant(ctx,def);const trimVar=newVar(ctx);const urlVar=newVar(ctx);doc.write(`const ${trimVar} = ${accessor}.trim();`);doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`);doc.write(`if (typeof ${urlVar} === "number") return INVALID;`);if(formatDef.hostname!==undefined){const hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==undefined){const protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;const outputVar=newVar(ctx);const outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;doc.write(`const ${outputVar} = ${outputExpr};`);return outputVar}const customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);const fnConst=addConstant(ctx,customFn);doc.write(`if (!${fnConst}(${accessor})) return INVALID;`);return accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){const patternConst=addConstant(ctx,def.pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);return accessor}const format=def.format;switch(format){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{const prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{const suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:{throw new ZodCompileUnsupportedError(`string format ${format}`)}}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=true){const def=schema._zod.def;const type=def.type;if(def.coerce){throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`)}const buildsValue=needsValue||!!def.checks?.length;let typeAccessor;switch(type){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;");typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{const innerOut=generateWrapperCheck(doc,ctx,schema,accessor);const frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`);typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor);typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:{throw new ZodCompileUnsupportedError(`schema type ${type}`)}}if(typeAccessor===null)return null;return generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=true){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const def=schema._zod.def;if(def.format===undefined)return accessor;return generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);const def=schema._zod.def;if(def.check==="number_format"&&def.format){generateNumberFormatCheck(doc,{format:def.format},accessor)}return accessor}function generateBooleanCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`);return accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);const def=schema._zod.def;if(def.format){switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}}return accessor}function generateSymbolCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`);return accessor}function generateUndefinedCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNullCheck(doc,accessor){doc.write(`if (${accessor} !== null) return INVALID;`);return accessor}function generateVoidCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNaNCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`);return accessor}function generateDateCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`);return accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);const shape=def.shape;const keys=Object.keys(shape);const symbolKeys=Object.getOwnPropertySymbols(shape);const allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;const keyExpr=(k)=>typeof k==="symbol"?addConstant(ctx,k):esc(k);const propKey=(k)=>typeof k==="symbol"?`[${keyExpr(k)}]`:esc(k);const propShape=shape;if(keys.includes("__proto__")){throw new ZodCompileUnsupportedError('object shape key "__proto__"')}const propOutputs=new Map;for(const key of allKeys){const propSchema=propShape[key];const kx=keyExpr(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${kx}];`);if(propSchema._zod.optin!==undefined){const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)});doc.write(`})();`);if(propSchema._zod.optout==="optional"){doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`if (${kx} in ${accessor}) return INVALID;`);d.write(`${outputVar} = undefined;`)});doc.write(`}`)}else{doc.write(`if (${outputVar} === INVALID) return INVALID;`)}propOutputs.set(key,outputVar)}else{if(requiresPresenceCheck(propSchema)){doc.write(`if (!(${kx} in ${accessor})) return INVALID;`)}const outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);if(outputAccessor!==null)propOutputs.set(key,outputAccessor)}}const catchall=def.catchall;let unknownKeysMode="none";if(catchall){const catchallType=catchall._zod.def.type;if(catchallType==="never"){const condition=keys.map((k)=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${condition}) return INVALID;`)});doc.write(`}`)}else if((catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length){unknownKeysMode="passthrough"}else{unknownKeysMode="schema"}}const outputVar=newVar(ctx);const hasConditionalKeys=allKeys.some((k)=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);compileChild(d,ctx,catchall,valVar,false)});doc.write(`}`)}return null}if(!hasConditionalKeys){const propLiterals=allKeys.map((k)=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}else{doc.write(`const ${outputVar} = {};`);for(const k of allKeys){const kx=keyExpr(k);const out=propOutputs.get(k);if(dropsWhenAbsent(propShape[k])){doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else if(mayOmitUndefined(propShape[k])){doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else{doc.write(`${outputVar}[${kx}] = ${out};`)}}}if(unknownKeysMode!=="none"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);if(unknownKeysMode==="passthrough"){d.write(`${outputVar}[k] = ${accessor}[k];`)}else{const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);const catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}});doc.write(`}`)}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;if(isExactOptional(schema)){return generateCheck(doc,ctx,def.innerType,accessor,buildsValue)}if(def.innerType._zod.optin==="defaulted"){const outputVar=newVar(ctx);const branchVar=newVar(ctx);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`const ${branchVar} = (() => {`);d.indented((d2)=>{const innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)});d.write(`})();`);d.write(`if (${branchVar} !== INVALID) ${outputVar} = ${branchVar};`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===true}function requiresPresenceCheck(schema){return schema._zod.optin===undefined&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return true;const def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return true;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return false;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):true;case"catch":return true;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):true;case"intersection":if(!def.left||!def.right)return true;return fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):true;default:return true}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){const def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":return true;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):true;case"union":return def.options?def.options.some(mayOutputUndefined):true;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):true;default:return true}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar} = null;`);doc.write(`if (${accessor} !== null) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const outputVar=buildsValue?newVar(ctx):null;const iVar=newVar(ctx);const elemVar=newVar(ctx);if(outputVar)doc.write(`const ${outputVar} = new Array(${accessor}.length);`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);if(outputVar&&elemOutput!==null)d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`);return outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const values=def.values;if(values.length!==1){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}const value=values[0];if(typeof value==="number"&&Number.isNaN(value)){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}if(typeof value==="string"){doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`)}else if(typeof value==="number"||typeof value==="boolean"){doc.write(`if (${accessor} !== ${value}) return INVALID;`)}else if(value===null){doc.write(`if (${accessor} !== null) return INVALID;`)}else if(value===undefined){doc.write(`if (${accessor} !== undefined) return INVALID;`)}else if(typeof value==="bigint"){doc.write(`if (${accessor} !== ${value}n) return INVALID;`)}else{throw new ZodCompileUnsupportedError(`literal type ${typeof value}`)}return accessor}function generateEnumCheck(doc,ctx,schema,accessor){const values=schema._zod.values;if(!values){throw new ZodCompileUnsupportedError("enum schema without enumerated values")}const enumSet=addConstant(ctx,values);doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);return accessor}function generateWrapperCheck(doc,ctx,schema,accessor){const def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const descriptor=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue");const defaultGetter=descriptor?()=>schema._zod.def.defaultValue:undefined;if(schema._zod.def.type==="prefault"){if(!defaultGetter){return generateCheck(doc,ctx,def.innerType,accessor)}const defaultFn=addConstant(ctx,defaultGetter);const inputVar=newVar(ctx);doc.write(`let ${inputVar} = ${accessor};`);doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);return generateCheck(doc,ctx,def.innerType,inputVar)}const outputVar=newVar(ctx);if(defaultGetter){const defaultFn=addConstant(ctx,defaultGetter);const cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)});doc.write(`}`)}else{doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`)}return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const innerOutput=generateCheck(doc,ctx,def.innerType,accessor);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${innerOutput};`);doc.write(`if (${outputVar} === undefined) return INVALID;`);return outputVar}function generateTupleCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const items=def.items;const rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const optinStart=getTupleOptStart2(items,"optin");const optoutStart=getTupleOptStart2(items,"optout");if(rest){doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`)}else{doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`)}const outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){const itemSchema=items[i];if(i>=optoutStart){doc.write(`if (${outputVar}.length === ${i}) {`);doc.indented((d)=>{d.write(`if (${i} < ${accessor}.length) {`);d.indented((d2)=>{const elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)});d.write(`} else {`);d.indented((d2)=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}const elemVar=newVar(ctx);const branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`);d2.write(`const ${branchVar} = (() => {`);d2.indented((d3)=>{const elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)});d2.write(`})();`);d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);d2.write(`else ${outputVar}[${i}] = ${branchVar};`)});d.write(`}`)});doc.write(`}`)}else{const elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){const iVar=newVar(ctx);const elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`)}return outputVar}function getTupleOptStart2(items,key){for(let i=items.length-1;i>=0;i--){const omittable=key==="optin"?items[i]._zod.optin!==undefined:items[i]._zod.optout==="optional";if(!omittable)return i+1}return 0}function generateUnionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const options=def.options;if(def.discriminator){return generateDiscriminatedUnionCheck(doc,ctx,def,accessor)}if(def.inclusive===false){throw new ZodCompileUnsupportedError("exclusive unions (z.xor)")}if(options.length===0){doc.write("return INVALID;");return accessor}if(options.length===1){return generateCheck(doc,ctx,options[0],accessor)}const allLiterals=options.every((opt)=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length);if(allLiterals){const values=new Set(options.flatMap((opt)=>opt._zod.def.values));const valuesConst=addConstant(ctx,values);doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);return accessor}const outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){const opt=options[i];if(i===0){doc.write(`${outputVar} = (() => {`)}else{doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`)}doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)});doc.write(`})();`)}doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback){throw new ZodCompileUnsupportedError("discriminated union with unionFallback")}if(def.options.length===0){doc.write("return INVALID;");return accessor}const discVar=newVar(ctx);const outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);doc.write(`let ${outputVar};`);let firstBranch=true;const claimed=new Set;for(const option of def.options){const values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0){throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values")}for(const value of values){if(claimed.has(value)){throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`)}claimed.add(value)}const conditions=Array.from(values,(value)=>literalEquality(ctx,discVar,value));const prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`);doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)});doc.write(`}`);firstBranch=false}doc.write(`else { return INVALID; }`);return outputVar}function literalEquality(ctx,accessor,value){if(typeof value==="string")return`${accessor} === ${esc(value)}`;if(typeof value==="number"){if(Number.isNaN(value))return`Number.isNaN(${accessor})`;return`${accessor} === ${value}`}if(typeof value==="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===undefined)return`${accessor} === undefined`;if(typeof value==="bigint")return`${accessor} === ${value}n`;if(typeof value==="symbol"){const symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;ctx.definite=false;const leftOutput=compileChild(doc,ctx,def.left,accessor);const rightOutput=compileChild(doc,ctx,def.right,accessor);const mergeConst=addConstant(ctx,mergeValues);const mergedVar=newVar(ctx);doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);doc.write(`if (!${mergedVar}.valid) return INVALID;`);return`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);const recordDef=def;const keyValues=recordDef.partial?undefined:def.keyType._zod.values;if(keyValues){const inputKeys=[];for(const key of keyValues){if(!(typeof key==="string"||typeof key==="number"||typeof key==="symbol")){throw new ZodCompileUnsupportedError(`record key value ${String(key)}`)}const inputKey=typeof key==="number"?key.toString():key;if(inputKey==="__proto__"){throw new ZodCompileUnsupportedError('record key "__proto__"')}inputKeys.push(inputKey);const keyConst=addConstant(ctx,key);const outKey=generateCheck(doc,ctx,def.keyType,keyConst);const valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);const valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}const knownKeysConst=addConstant(ctx,new Set(inputKeys));doc.write(`for (const ${kVar} in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);if(recordDef.mode==="loose"){d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`)}else{d.write(`return INVALID;`)}});doc.write(`}`);return outputVar}const keyDef=def.keyType._zod.def;const keyIsBareString=keyDef.type==="string"&&keyDef.format===undefined&&!keyDef.coerce&&(keyDef.checks?.length??0)===0;if(!keyIsBareString){const isLoose=def.mode==="loose";const keyFn=compileFn(def.keyType);if(keyFn.definite===false)ctx.definite=false;const keyFast=addConstant(ctx,keyFn);const numericConst=addConstant(ctx,number);const outKeyVar=newVar(ctx);emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);if(isLoose){d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`)}else{d.write(`if (${outKeyVar} === INVALID) return INVALID;`)}d.write(`if (${outKeyVar} === "__proto__") continue;`);const valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)});return outputVar}emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},`return INVALID;`);return outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){const propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable);const symsVar=newVar(ctx);const keysVar=newVar(ctx);const iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`);d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);body(d)});doc.write(`}`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`);d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);if(onSymbol)d.write(onSymbol);else body(d)});doc.write(`}`)}function literalPropertyKey(ctx,key){if(typeof key==="string")return esc(key);return addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Map();`);doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);doc.indented((d)=>{const keyOutput=generateCheck(d,ctx,def.keyType,kVar);const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)});doc.write(`}`);return outputVar}function generateSetCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);const outputVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Set();`);doc.write(`for (const ${valVar} of ${accessor}) {`);doc.indented((d)=>{const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)});doc.write(`}`);return outputVar}function generateFileCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);return accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const pattern=schema._zod.pattern;if(pattern){const patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const getterConst=addUserConstant(ctx,def.getter);const cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`);doc.indented((d)=>{d.write(`const inner = ${getterConst}();`);d.write(`${cacheConst}.parser = function(input) {`);d.indented((d2)=>{d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);d2.write(`return result.issues.length === 0 ? result.value : INVALID;`)});d.write(`};`)});doc.write(`}`);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generatePipeCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const transformedVar=newVar(ctx);doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);doc.write(`if (${transformedVar} === INVALID) return INVALID;`);return generateCheck(doc,ctx,def.out,transformedVar)}else{return generateCheck(doc,ctx,def.out,inputOutput)}}function isAsyncFunction(fn){return typeof fn==="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`)}else{throw new ZodCompileUnsupportedError("custom schema without a predicate function")}return accessor}function runtimeCatch(innerSchema,catchValue,value){const result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;if(r.issues.length===0)return r.value;return catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH]){throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",false)}const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)});doc.write(`})();`);const innerConst=addConstant(ctx,def.innerType);const catchConst=addUserConstant(ctx,def.catchValue);const catchHelperConst=addConstant(ctx,runtimeCatch);doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);d.write(`if (${outputVar} === INVALID) return INVALID;`)});doc.write(`}`);return outputVar}function generateTransformCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}return accessor}function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return def}function _string(Class,params){return new Class(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class,params){return new Class(snapshotChecks({type:"string",coerce:true,...normalizeParams(params)}))}function _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class,params){return new Class({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _creditCard(Class,params){return new Class({type:"string",format:"credit_card",check:"string_format",abort:false,...normalizeParams(params)})}function _iban(Class,params){return new Class({type:"string",format:"iban",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class,params){return new Class(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class,params){return new Class(snapshotChecks({type:"number",coerce:true,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class,params){return new Class({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class,params){return new Class({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class,params){return new Class({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class,params){return new Class({type:"symbol",...normalizeParams(params)})}function _undefined2(Class,params){return new Class({type:"undefined",...normalizeParams(params)})}function _null2(Class,params){return new Class({type:"null",...normalizeParams(params)})}function _any(Class){return new Class({type:"any"})}function _unknown(Class){return new Class({type:"unknown"})}function _never(Class,params){return new Class({type:"never",...normalizeParams(params)})}function _void(Class,params){return new Class({type:"void",...normalizeParams(params)})}function _date(Class,params){return new Class({type:"date",...normalizeParams(params)})}function _coercedDate(Class,params){return new Class({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class,params){return new Class({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class,element,params){return new Class({type:"array",element,...normalizeParams(params)})}function _union(Class,options,params){return new Class({type:"union",options,...normalizeParams(params)})}function _xor(Class,options,params){return new Class({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class,discriminator,options,params){return new Class({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class,left,right){return new Class({type:"intersection",left,right})}function _tuple(Class,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class,keyType,valueType,params){return new Class({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class,keyType,valueType,params){return new Class({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class,valueType,params){return new Class({type:"set",valueType,...normalizeParams(params)})}function _enum(Class,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class,entries,params){return new Class({type:"enum",entries,...normalizeParams(params)})}function _literal(Class,value,params){return new Class({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class,params){return new Class({type:"file",...normalizeParams(params)})}function _transform(Class,fn){return new Class({type:"transform",transform:fn})}function _optional(Class,innerType){return new Class({type:"optional",innerType})}function _nullable(Class,innerType){return new Class({type:"nullable",innerType})}function _default(Class,innerType,defaultValue){return new Class({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class,innerType,params){return new Class({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class,innerType){return new Class({type:"success",innerType})}function _catch(Class,innerType,catchValue){return new Class({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class,in_,out){return new Class({type:"pipe",in:in_,out})}function _readonly(Class,innerType){return new Class({type:"readonly",innerType})}function _templateLiteral(Class,parts,params){return new Class({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class,getter){return new Class({type:"lazy",getter})}function _promise(Class,innerType){return new Class({type:"promise",innerType})}function _custom(Class,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class,fn,_params){const schema=new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:false});return{}}},reverseTransform:(input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}},error:params.error});codec._zod.bag.truthy=truthyArray;codec._zod.bag.falsy=falsyArray;codec._zod.bag.case=params.case??"insensitive";return codec}function _stringFormat(Class,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class(def);return inst}function assignProps(target,...sources){for(const source of sources){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProp(target,key,source[key])}}}return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:undefined,sharedEmitDoneFor:undefined,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??undefined}}function handleUnrepresentable(schema,ctx,json,params,message){const result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return false;if(result===undefined||result==="throw")throw new Error(message);Object.assign(json,result);return true}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);ctx.sharedDefsExtractedFor=undefined;ctx.sharedEmitDoneFor=undefined;const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a=result.schema).default??(_a.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id)=>id);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id){return{ref:uriPrefix}}const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema=seen.schema;for(const key in schema){delete schema[key]}schema.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry)}}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){const options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==undefined)return;const types=[];for(const option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);const keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;const type=option.type;for(const member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf;schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]);var UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){const extra=member.additionalProperties;if(extra===undefined||extra===false||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){const objects=[];for(const member of members){if(typeof member!=="object"||member.type!=="object")return null;for(const key in member){if(!FOLDABLE_KEYS.has(key))return null}objects.push(member)}const properties={};const required=new Set;for(const object of objects){for(const key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;const parts=[];for(const other of objects){const part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===undefined)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}const merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(const key of object.required??[])required.add(key)}const folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===false)){folded.additionalProperties=false}else{const constraints=[];for(const object of objects){const constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(constraints.length>1)folded.additionalProperties={allOf:constraints}}return folded}function foldIntersection(json){const allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(const key of FOLDABLE_KEYS)if(key in json)return;const unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k])));let folded=null;if(!unions.length){folded=foldObjects(allOf)}else{const union=unions[0];const keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;const rest=allOf.filter((m)=>m!==union);const branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf;assignProps(json,folded)}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema=seen.def??seen.schema;const _cached={...schema};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema.allOf=schema.allOf??[];schema.allOf.push(refSchema)}else{assignProps(schema,refSchema)}assignProps(schema,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])){delete schema[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])){delete schema[key]}}}}}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}if(ctx.target!=="openapi-3.0"){for(const entry of ctx.seen.entries()){compactTypeUnion(entry[1].def??entry[1].schema)}}for(const rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){const carriers=new Map;for(const seen of ctx.seen.values()){for(const json of[seen.schema,seen.def]){const allOf=json?.allOf;if(!Array.isArray(allOf))continue;const existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}}for(const allOf of ctx.intersections){for(const json of carriers.get(allOf)??[])foldIntersection(json)}}}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===undefined||value>agg[key])agg[key]=value};var narrowMax=(agg,key,value)=>{if(agg[key]===undefined||value<agg[key])agg[key]=value};var narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value);narrowMax(agg,"maximum",value)};var addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]);if(!agg.multipleOf.includes(value))agg.multipleOf.push(value)};var addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set);agg.patterns.add(pattern)};var intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]};var setFormat=(agg,format)=>{agg.format=format;if(format.includes("int"))agg.isInt=true};var minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum);var maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum);var formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);const[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum);narrowMax(agg,"maximum",maximum)};var contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format);if(def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=true},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){const agg={};const def=schema._zod.def;const list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(const ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);const bag=schema._zod.bag;if(bag.minimum!==undefined)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==undefined)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==undefined)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==undefined)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==undefined)addDivisor(agg,bag.multipleOf);if(bag.format!==undefined){agg.format??(agg.format=bag.format);if(bag.format.includes("int"))agg.isInt=true}if(bag.mime)intersectMime(agg,bag.mime);for(const pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]);var exactPattern=(p)=>exactPatterns.get(p)??p;var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"||laxFormat){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(patternList.length>1){json.allOf=[...patternList.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};var numberProcessor=(schema,ctx,_json,params)=>{const json=_json;const{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(multipleOf){const divisors=new Set;for(const divisor of multipleOf){if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`)}const[first,...rest]=divisors;if(first!==undefined)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")};var symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0"){json.type="string";json.nullable=true;json.enum=[null]}else{json.type="null"}};var undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")};var voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Void cannot be represented in JSON Schema")};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var anyProcessor=(_schema,_ctx,_json,_params)=>{};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var dateProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;if(def.values.length===0){json.not={};return}const vals=[];for(const val of def.values){if(val===undefined){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")};var templateLiteralProcessor=(schema,_ctx,json,_params)=>{const _json=json;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};var fileProcessor=(schema,_ctx,json,_params)=>{const _json=json;_json.type="string";_json.format="binary";_json.contentEncoding="binary";const{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==undefined)_json.minLength=minimum;if(maximum!==undefined)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))};var successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")};var setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){const def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")){return inputOptin(def.out)}if(def.type==="catch"){return inputOptin(def.innerType)}return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const shape=def.shape;const symbolKeys=Object.getOwnPropertySymbols(shape);if(symbolKeys.length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema")){return}json.type="object";json.properties={};for(const key in shape){assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}))}const requiredKeys=[];for(const key of Object.keys(shape)){const field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===undefined:field._zod.optout===undefined){requiredKeys.push(key)}}if(requiredKeys.length>0){json.required=requiredKeys}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf;ctx.intersections.push(allOf)};var tupleProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;let minItems=def.items.length;while(minItems>0){const item=def.items[minItems-1];const optional=ctx.io==="input"?inputOptin(item)!==undefined:item._zod.optout==="optional";if(!optional)break;minItems--}const maxItems=def.items.length;const isClosed=!def.rest;if(ctx.target==="draft-2020-12"){json.prefixItems=prefixItems;if(isClosed){json.items=false}else if(rest){json.items=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){json.items={anyOf:prefixItems};if(rest){json.items.anyOf.push(rest)}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{json.items=prefixItems;if(isClosed){json.additionalItems=false}else if(rest){json.additionalItems=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);const def=bySchema.get(json)?.def;if(!def)return json;const inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(const keyword of["anyOf","oneOf"]){const branches=json[keyword];if(!Array.isArray(branches))continue;const mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}const types=Array.isArray(json.type)?json.type:[json.type];const numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer");const values=json.enum??(json.const!==undefined?[json.const]:undefined);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;const{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;rest.type="string";if(!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){const bySchema=new Map;for(const entry of ctx.seen.values()){if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry)}const rewrites=new Map;for(const record of pendingRecords.get(ctx)??[]){const seen=ctx.seen.get(record);const names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===true||rewrites.has(names))continue;const rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(const entry of ctx.seen.values()){for(const carrier of[entry.schema,entry.def]){const rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}}var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);if(!pending){pending=[];pendingRecords.set(ctx,pending);ctx.deferred.push(()=>rewriteKeyNames(ctx))}pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;const omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==undefined;if(keyValues&&!def.partial&&!omittableOnInput){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues.map(String)}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=false;const serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;unrepresentable=true;return null});if(!unrepresentable)return JSON.parse(serialized);handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema");return UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io!=="input")return;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){const registry=input;const ctx=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry._idmap.entries()){const[_,schema]=entry;processSchema(schema,ctx)}const schemas={};const external={registry,uri:params?.uri,defs};ctx.external=external;for(const entry of registry._idmap.entries()){const[key,schema]=entry;extractDefs(ctx,schema);assignProp(schemas,key,finalize(ctx,schema))}if(Object.keys(defs).length>0){const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});processSchema(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}this.ctx.sharedDefsExtractedFor=undefined;this.ctx.sharedEmitDoneFor=undefined;extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const value=make(this);Object.defineProperty(this,key,{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,key,{value,configurable:true,writable:true})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";const proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_installedErrorProtos.add(proto);_lazyMethod(proto,"format",(self)=>(mapper)=>formatError(self,mapper));_lazyMethod(proto,"flatten",(self)=>(mapper)=>flattenError(self,mapper));_lazyMethod(proto,"addIssue",(self)=>(issue)=>{self.issues.push(issue);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});_lazyMethod(proto,"addIssues",(self)=>(issues)=>{self.issues.push(...issues);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});Object.defineProperty(proto,"isEmpty",{configurable:true,enumerable:false,get(){return this.issues.length===0}})};var ZodError=$constructor("ZodError",initializer2);var ZodRealError=$constructor("ZodError",initializer2,undefined,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode2=_encode(ZodRealError);var decode2=_decode(ZodRealError);var encodeAsync2=_encodeAsync(ZodRealError);var decodeAsync2=_decodeAsync(ZodRealError);var safeEncode2=_safeEncode(ZodRealError);var safeDecode2=_safeDecode(ZodRealError);var safeEncodeAsync2=_safeEncodeAsync(ZodRealError);var safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{_ensureDefaultLocale();$ZodType.init(inst,def);inst.def=def;inst.type=def.type;return inst},{check(...chks){const def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){reg.add(this,meta);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get "~standard"(){return hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){own(this,"~standard",value)},parse:function _parse(data,params){return parse3(this,data,params,{callee:_parse})},parseAsync:async function _parseAsync(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode(data,params){return encode2(this,data,params,{callee:_encode})},decode:function _decode(data,params){return decode2(this,data,params,{callee:_decode})},encodeAsync:async function _encodeAsync(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},derived({format:(inst)=>aggregateChecks(inst).format??null,minLength:(inst)=>aggregateChecks(inst).minimum??null,maxLength:(inst)=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));var ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def);ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def);ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=exports_regexes[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);inst.isFinite=true},derived({minValue:(inst)=>{const{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{const{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{const{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:(inst)=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},derived({minValue:(inst)=>aggregateChecks(inst).minimum??null,maxValue:(inst)=>aggregateChecks(inst).maximum??null,format:(inst)=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params))},derived({minDate:(inst)=>{const{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:(inst)=>{const{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer();$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);installLazyProp(inst,"shape",(self)=>self._zod.def.shape,false)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:undefined}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit(this,mask)},partial(...args){return partial(ZodOptional,this,args[0])},exactPartial(...args){return partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return required(ZodNonOptional,this,args[0])}});function object(shape,params){const def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer();$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){const def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map((item)=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer();$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params),partial:true})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer();$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer();$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=[...inst._zod.values];const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer();$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst);payload.issues.push(issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output)=>{payload.value=output;return payload})}payload.value=output;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe;var meta2=meta;var ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){const inst=new ZodInstanceOf({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:true,...normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=(payload)=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){const jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map){config({customError:map})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...exports_schemas2,...exports_checks2,iso:exports_iso};var RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1]===undefined?undefined:decodeJSONPointerSegment(path[1]);if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const value=payload.value;if(typeof value!=="object"||value===null||Array.isArray(value))return;const keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==undefined&&keys.length<guards.minProperties){payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:true,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.maxProperties!==undefined&&keys.length>guards.maxProperties){payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:true,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.keySchema){for(const key of keys){const result=guards.keySchema.safeParse(key);if(result.success)continue;payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:true})}}});return guard.pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";const type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;const raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){const parts=[];for(const item of value){const key=canonicalKey(item,seen);if(key===null)return null;parts.push(key)}return`a${parts.length}:[${parts.join(",")}]`}const keys=Object.keys(value).sort();const parts=[];for(const k of keys){const key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]);var SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value){if(typeof value!=="object"||value===null)return false;if(Array.isArray(value))return value.some(containsRef);if(typeof value.$ref==="string")return true;return Object.entries(value).some(([key,sub])=>{if(SCHEMA_KEYWORDS.has(key))return containsRef(sub);if(!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!=="object"||sub===null)return false;return Object.values(sub).some(containsRef)})}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const items=payload.value;if(!Array.isArray(items))return;if(guards.uniqueItems===true){const firstSeen=new Map;for(let i=0;i<items.length;i++){const key=canonicalKey(items[i],new Set);if(key===null)continue;const first=firstSeen.get(key);if(first===undefined){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:true})}}if(guards.containsSchema){const minContains=guards.minContains??1;const ceiling=guards.maxContains!==undefined?guards.maxContains+1:Number.POSITIVE_INFINITY;let matches=0;for(const item of items){if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break}if(matches<minContains){payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:true})}if(guards.maxContains!==undefined&&matches>guards.maxContains){payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:true})}}});return guard.pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema===false){return}if(restSchema===undefined||restSchema===true){return z.any()}return convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==undefined){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==undefined){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==undefined){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==undefined||schema.then!==undefined||schema.else!==undefined){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==undefined||schema.dependentRequired!==undefined){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema);ctx.processing.delete(refPath);return zodSchema}if(schema.enum!==undefined){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every((v)=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==undefined){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map((t)=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime({offset:true}))}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.regex(fullTime))}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="hostname"){stringSchema=stringSchema.check(z.hostname())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="credit_card"){stringSchema=stringSchema.check(z.creditCard())}else if(format==="iban"){stringSchema=stringSchema.check(z.iban())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"&&schema.exclusiveMinimum!==true){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"&&schema.exclusiveMaximum!==true){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);const additionalSchema=typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):undefined;for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}if(schema.additionalProperties===false){const propertyKeys=Object.keys(shape);const patterns=patternKeys.map((p)=>new RegExp(p));const basePatternSchema=zodSchema;zodSchema=zodSchema.check((payload)=>{if(!isPlainObject(payload.value))return;const unrecognized=[];for(const key of Object.keys(payload.value)){if(propertyKeys.includes(key))continue;if(patterns.some((regex)=>regex.test(key)))continue;unrecognized.push(key)}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})}})}}else{const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(additionalSchema){zodSchema=objectSchema.catchall(additionalSchema)}else{zodSchema=objectSchema.passthrough()}}const hasKeyGuard=schema.propertyNames!==undefined&&schema.propertyNames!==true;const minProperties=typeof schema.minProperties==="number"?schema.minProperties:undefined;const maxProperties=typeof schema.maxProperties==="number"?schema.maxProperties:undefined;if(hasKeyGuard||minProperties!==undefined||maxProperties!==undefined){let keySchema;if(hasKeyGuard){const keyJSONSchema=typeof schema.propertyNames==="object"&&schema.propertyNames.type===undefined?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=prefixItems.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=!Array.isArray(items)?getTupleRest(items,ctx):undefined;const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=items.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=getTupleRest(schema.additionalItems,ctx);const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==undefined){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}if(schema.uniqueItems===true||schema.contains!==undefined){zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===true,containsSchema:schema.contains!==undefined?convertSchema(schema.contains,ctx):undefined,minContains:typeof schema.minContains==="number"?schema.minContains:undefined,maxContains:typeof schema.maxContains==="number"?schema.maxContains:undefined})}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==undefined||schema.const!==undefined;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map((s)=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map((s)=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==undefined){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}if(schema.type==="object"&&schema.$ref===undefined){if(schema.propertyNames!==undefined&&!containsRef(schema.propertyNames)){extraMeta.propertyNames=schema.propertyNames}for(const key of["minProperties","maxProperties"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}if(schema.type==="array"&&schema.$ref===undefined){if(schema.contains!==undefined&&!containsRef(schema.contains)){extraMeta.contains=schema.contains}for(const key of["uniqueItems","minContains","maxContains"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){assignProp(extraMeta,key,schema[key])}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){const fn=typeof fnOrHandlers==="function"?fnOrHandlers:(node,rewritten)=>{const h=fnOrHandlers[node._zod.def.type];return h?h(node,rewritten):node};const cache=new Map;function run(s){const cached=cache.get(s);if(cached===RESOLVING){return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)})}if(cached!==undefined)return cached;cache.set(s,RESOLVING);const inner=mapInner(s);const mapped=fn(inner,inner!==s);cache.set(s,mapped);return mapped}function mapInner(s){const def=s._zod.def;const kind=def.type;switch(kind){case"object":{const oldShape=def.shape;const keys=Object.keys(oldShape);let changed=false;const newShape={};for(const k of keys){const mapped=run(oldShape[k]);if(mapped!==oldShape[k])changed=true;newShape[k]=mapped}let newCatchall=def.catchall;if(def.catchall){newCatchall=run(def.catchall);if(newCatchall!==def.catchall)changed=true}return changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{const mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{const oldItems=def.items;let changed=false;const newItems=[];for(const item of oldItems){const mapped=run(item);if(mapped!==item)changed=true;newItems.push(mapped)}let newRest=def.rest;if(def.rest){newRest=run(def.rest);if(newRest!==def.rest)changed=true}return changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{const newKey=run(def.keyType);const newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{const newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{const oldOptions=def.options;let changed=false;const newOptions=[];for(const opt of oldOptions){const mapped=run(opt);if(mapped!==opt)changed=true;newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{const newLeft=run(def.left);const newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{const newIn=run(def.in);const newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{const newInput=run(def.input);const newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{const original=def.getter;const{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:{return s}}}return run(schema)}function deepPartial(schema){return visit(schema,{object:(s)=>s.partial(),union:(s)=>{const def=s._zod.def;return def.discriminator===undefined?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;const def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:true})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:(s)=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:(s)=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");function queryOpenShadowAll(root,selector){const defined=(value,reading)=>{if(value===undefined)throw new TypeError(`Cannot read properties of undefined (reading '${reading}')`);return value};const groups=[];let parts=[],token="",depth=0,quote="",escaped=false,combinator=" ";const flush=()=>{if(!token.trim())return;parts.push({selector:token.trim(),combinator});token="";combinator=" "};for(const char of selector){if(escaped){token+=char;escaped=false;continue}if(char==="\\"){token+=char;escaped=true;continue}if(quote){token+=char;if(char===quote)quote="";continue}if(char==='"'||char==="'"){quote=char;token+=char;continue}if(char==="["||char==="(")depth++;if(char==="]"||char===")")depth--;if(!depth&&(char===","||char===">"||char==="+"||char==="~"||/\s/.test(char))){flush();if(char===","){groups.push(parts);parts=[];combinator=" "}else if(!/\s/.test(char))combinator=char}else token+=char}flush();groups.push(parts);const simple=groups.every((group)=>group.length===1&&!/^:scope\b/.test(defined(group[0],"selector").selector));let rootSelector=selector;if(!simple&&root instanceof Element){const scopedSelectors=[];for(const group of groups){const first=defined(group[0],"selector").selector;const rest=group.slice(1).map((part)=>`${part.combinator} ${part.selector}`).join(" ");const scoped=/^:scope\b/.test(first);scopedSelectors.push(`${scoped?"":":scope "}${first} ${rest}`);if(!scoped&&group.length>1&&root.matches(first))scopedSelectors.push(`:scope ${rest}`)}rootSelector=scopedSelectors.join(", ")}const rootElements=root.querySelectorAll("*");const rootMatches=rootSelector==="*"?rootElements:root.querySelectorAll(rootSelector);const pending=[];for(let index=rootElements.length-1;index>=0;index--){const element=defined(rootElements[index],"shadowRoot");if(element.shadowRoot)pending.push(element.shadowRoot)}if(root instanceof Element&&root.shadowRoot)pending.push(root.shadowRoot);if(pending.length===0)return Array.from(rootMatches);const results=[];for(let index=0;index<rootMatches.length;index++)results.push(defined(rootMatches[index],"index"));const rootOf=(node)=>node.getRootNode();const parent=(node)=>node.parentElement??rootOf(node).host??null;const scope=root instanceof Element?root:root.documentElement;const matches=(node,group,index)=>{if(node===root&&index>0)return false;const part=defined(group[index],"selector");const scoped=/^:scope\b/.test(part.selector);const compound=scoped?part.selector.replace(/^:scope\b/,"*"):part.selector;if(scoped&&node!==scope)return false;if(!node.matches(compound))return false;if(index===0)return true;if(part.combinator===">"){const ancestor=parent(node);return!!ancestor&&matches(ancestor,group,index-1)}if(part.combinator==="+")return!!node.previousElementSibling&&matches(node.previousElementSibling,group,index-1);if(part.combinator==="~"){for(let sibling=node.previousElementSibling;sibling;sibling=sibling.previousElementSibling){if(matches(sibling,group,index-1))return true}return false}for(let ancestor=parent(node);ancestor;ancestor=parent(ancestor)){if(matches(ancestor,group,index-1))return true;if(ancestor===root)break}return false};while(pending.length){const shadow=defined(pending.pop(),"querySelectorAll");const elements=shadow.querySelectorAll("*");for(let index=elements.length-1;index>=0;index--){const element=defined(elements[index],"shadowRoot");if(element.shadowRoot)pending.push(element.shadowRoot)}if(simple){const found=selector==="*"?elements:shadow.querySelectorAll(selector);for(let index=0;index<found.length;index++)results.push(defined(found[index],"index"));continue}for(let index=0;index<elements.length;index++){const node=defined(elements[index],"index");if(groups.some((group)=>matches(node,group,group.length-1)))results.push(node)}}return results}function isElementHiddenForAria(element,cache){const isElement=(node)=>node.nodeType===1;const isFragment=(node)=>node?.nodeType===11;const getStyle=(node)=>node.ownerDocument?.defaultView?.getComputedStyle(node);const isVisibleTextNode=(text)=>{const ownerDocument=text.ownerDocument;if(ownerDocument===null)throw new TypeError("Cannot read properties of null (reading 'createRange')");const range=ownerDocument.createRange();range.selectNode(text);const rect=range.getBoundingClientRect();return rect.width>0&&rect.height>0};const belongsToDisplayNoneOrAriaHiddenOrNonSlotted=(node)=>{let hidden=cache.get(node);if(hidden===undefined){hidden=!!(node.parentElement&&node.parentElement.shadowRoot&&!node.assignedSlot);if(!hidden){const style=getStyle(node);hidden=!style||style.display==="none"||node.getAttribute("aria-hidden")?.toLowerCase()==="true"}if(!hidden){const parentNode=node.parentNode;const parent=node.parentElement??(isFragment(parentNode)?parentNode.host:null);if(parent)hidden=belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent)}cache.set(node,hidden)}return hidden};const tagName=typeof element.tagName==="string"?element.tagName.toUpperCase():"FORM";if(["STYLE","SCRIPT","NOSCRIPT","TEMPLATE"].includes(tagName))return true;const style=getStyle(element);const isSlot=element.nodeName==="SLOT";if(style?.display==="contents"&&!isSlot){for(let child=element.firstChild;child;child=child.nextSibling){if(isElement(child)&&!isElementHiddenForAria(child,cache))return false;if(child.nodeType===3&&isVisibleTextNode(child))return false}return true}const isOptionInsideSelect=element.nodeName==="OPTION"&&!!element.closest("select");if(!isOptionInsideSelect&&!isSlot&&style&&(!element.checkVisibility()||style.visibility!=="visible"))return true;return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element)}function createTextMatching(isHidden=()=>false,getRole=()=>"",includeHidden=false){const isElement=(node)=>node.nodeType===1;const isInput=(node)=>node.nodeName==="INPUT";const isSlot=(node)=>node.nodeName==="SLOT";const isFormField=(node)=>node.nodeName==="INPUT"||node.nodeName==="TEXTAREA"||node.nodeName==="SELECT";const viewOf=(document2)=>{const view=document2.defaultView;if(view===null)throw new TypeError("Cannot read properties of null (reading 'getComputedStyle')");return view};const scopeOf=(node)=>node.getRootNode();const buttonDefaults={submit:"Submit",reset:"Reset"};const nativeCaptions={FIELDSET:"LEGEND",FIGURE:"FIGCAPTION",TABLE:"CAPTION",SVG:"title"};const normalize=(value)=>String(value??"").replace(/[\u200b\u00ad]/g,"").trim().replace(/\s+/g," ");const matches=(value,matcher)=>{if(matcher instanceof RegExp){matcher.lastIndex=0;return matcher.test(value)}const text=normalize(value);return"exact"in matcher?text===normalize(matcher.exact):text.toLowerCase().includes(normalize(matcher.contains).toLowerCase())};const skipped=(node)=>["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"].includes(node.nodeName)||!!node.ownerDocument?.head?.contains(node);const textCache=new Map;const text=(node)=>{const cached=textCache.get(node);if(cached!==undefined)return cached;let value="";if(!skipped(node)){if(isInput(node)&&["submit","button","reset"].includes(node.type))value=node.value;else{for(const child of node.childNodes){if(child.nodeType===3)value+=child.nodeValue;else if(isElement(child))value+=text(child)}if(node.shadowRoot)value+=text(node.shadowRoot)}}textCache.set(node,value);return value};const matchesText=(node,matcher)=>!skipped(node)&&matches(text(node),matcher);const labelledBy=(node)=>{const refs=node.ariaLabelledByElements??(node.getAttribute("aria-labelledby")??"").trim().split(/\s+/).filter(Boolean).map((id)=>scopeOf(node).getElementById?.(id)).filter((ref)=>ref!==null&&ref!==undefined);return refs.length?[...new Set(refs)]:null};const labels=(node)=>{const refs=labelledBy(node);if(refs)return refs.map(text);const ariaLabel=node.getAttribute("aria-label");if(ariaLabel?.trim())return[ariaLabel];return Array.from(node.labels??[],text)};const contentRoles=new Set(["button","cell","checkbox","columnheader","gridcell","heading","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"]);const prohibitedRoles=new Set(["caption","code","definition","deletion","emphasis","generic","insertion","mark","paragraph","presentation","strong","subscript","suggestion","superscript","term","time"]);const accessibleName=(node)=>{const visited=new Set;const alternative=(element,referenced=false,hiddenReference=false,descendant=false,inLabelledBy=false)=>{if(visited.has(element)||skipped(element))return"";if(!includeHidden&&!hiddenReference&&isHidden(element))return"";visited.add(element);const refs=labelledBy(element);if(refs&&!inLabelledBy){const value=refs.map((ref)=>alternative(ref,true,isHidden(ref),false,true)).join(" ");if(value)return value}const ariaLabel=element.getAttribute("aria-label");if(ariaLabel?.trim())return ariaLabel;const tag=element.nodeName;if(isInput(element)&&["button","submit","reset"].includes(element.type))return element.value||buttonDefaults[element.type]||element.getAttribute("title")||"";if(element.labels?.length&&!inLabelledBy)return Array.from(element.labels,(label)=>alternative(label,true,isHidden(label))).join(" ");if(tag==="IMG"||tag==="AREA"||isInput(element)&&element.type==="image")return element.getAttribute("alt")||element.getAttribute("title")||(tag==="INPUT"?"Submit":"");if(isFormField(element)){if(descendant&&["INPUT","TEXTAREA"].includes(tag))return element.value;if(tag==="INPUT"&&element.type==="file")return"Choose File";const usePlaceholder=tag==="TEXTAREA"||["text","password","number","search","tel","email","url"].includes(element.type);return element.getAttribute("title")||(usePlaceholder?element.getAttribute("placeholder"):"")||""}const nativeChild=nativeCaptions[tag];const child=nativeChild&&Array.from(element.children).find((candidate)=>candidate.nodeName===nativeChild);if(child)return alternative(child,true,isHidden(child));if(referenced||descendant||tag==="SUMMARY"||contentRoles.has(getRole(element))){let value="";const assigned=isSlot(element)?element.assignedNodes():[];const children=assigned.length?assigned:[...element.childNodes,...element.shadowRoot?.childNodes??[]];for(const childNode of children){if(!assigned.length&&childNode.assignedSlot)continue;if(childNode.nodeType===3)value+=childNode.nodeValue;else if(isElement(childNode)){const token=alternative(childNode,referenced,hiddenReference,true,inLabelledBy);const display=viewOf(childNode.ownerDocument).getComputedStyle(childNode).display;value+=display!=="inline"||childNode.nodeName==="BR"?` ${token} `:token}}if(normalize(value))return value}return element.getAttribute("title")||""};return prohibitedRoles.has(getRole(node))?"":normalize(alternative(node))};return{normalize,matches,skipped,text,matchesText,labels,accessibleName}}function defined(value,what){if(value===undefined)throw new RangeError(`${what} is missing`);return value}var isInteger=(value)=>Number.isInteger(value);var baselines=new WeakMap;var REF_LINE=/^(\s*)- [^\s"]+(?: "(?:\\.|[^"\\])*")? \[ref=((?:f\d+)?e\d+)\]/;function indexTree(tree){const nodes=new Map;const unreferenced=[];const parents=[];let focused=null;for(const line of tree.split(`
|
|
67
|
+
`)){if(!line)continue;const depth=line.search(/\S/);while(parents.length&&defined(parents.at(-1),"open parent").depth>=depth)parents.pop();const match=REF_LINE.exec(line);if(match){const ref=defined(match[2],"ref group");const node={ref,tree:line.trim().slice(2)};nodes.set(ref,node);parents.push({depth,node});const state=line.slice(match[0].length).match(/"(?:\\.|[^"\\])*"|\[focused\]/g)??[];if(state.includes("[focused]"))focused=ref}else if(parents.length){defined(parents.at(-1),"open parent").node.tree+=` | ${line.trim().slice(2)}`}else if(!/^\s*- [\w-]+:?$/.test(line)){unreferenced.push(line)}}return{nodes,focused,unreferenced:unreferenced.join(`
|
|
68
|
+
`)}}var REF_ATTR=/\[ref=((?:f\d+)?e\d+)\]/g;var QUOTED=/"(?:\\.|[^"\\])*"/g;function validateSnapshotOptions(options){const{diff,find,context}=options;if(find===undefined){if(context!==undefined)throw new TypeError("snapshot({ context }) needs find");return}if(diff===true)throw new TypeError("snapshot() accepts diff or find, not both");if(!(find instanceof RegExp)&&(typeof find!=="string"||find==="")){throw new TypeError("snapshot({ find }) needs a non-empty string or a RegExp")}if(context!==undefined&&(!isInteger(context)||context<0||context>10)){throw new TypeError("snapshot({ context }) must be an integer from 0 to 10")}}function findSnapshotLines(snapshot,find,context=2){const query=find instanceof RegExp?{pattern:new RegExp(find.source,find.flags.replace(/[gy]/g,"")),needle:null}:{pattern:null,needle:find.toLowerCase()};const lines=snapshot.tree?snapshot.tree.split(`
|
|
69
|
+
`):[];const matched=[];lines.forEach((line,index)=>{if(query.pattern?query.pattern.test(line):line.toLowerCase().includes(query.needle))matched.push(index)});const included=new Set;for(const index of matched){for(let i=Math.max(0,index-context);i<=Math.min(lines.length-1,index+context);i++)included.add(i)}const out=[];let previous=-1;for(const index of[...included].toSorted((a,b)=>a-b)){if(out.length&&index>previous+1)out.push("...");out.push(defined(lines[index],"line"));previous=index}const tree=out.join(`
|
|
70
|
+
`);const refs={};for(const match of tree.replace(QUOTED,"").matchAll(REF_ATTR)){const ref=defined(match[1],"ref group");const value=snapshot.refs?.[ref];if(value)refs[ref]=value}return{tree,refs,find:{query:String(find),matches:matched.length}}}function snapshotResult(frameManager,options,snapshot){const{diff,find,context,...scope}=options;if(find!==undefined)return findSnapshotLines(snapshot,find,context);const document2=frameManager.getFrame(frameManager.mainFrameId);const contexts=JSON.stringify(frameManager.collectDescendantFrames(frameManager.mainFrameId).map(({frameId})=>[frameId,frameManager.getFrame(frameId)?.isolatedContextId]));const scopeKey=JSON.stringify(scope);const current=indexTree(snapshot.tree);const previous=baselines.get(frameManager);baselines.set(frameManager,{...current,document:document2,contexts,scopeKey});if(diff!==true)return snapshot;let reason;if(!previous)reason="no-baseline";else if(previous.document!==document2||previous.contexts!==contexts)reason="navigation";else if(previous.scopeKey!==scopeKey)reason="options-changed";else if(previous.unreferenced!==current.unreferenced)reason="unreferenced-content";if(reason)return{...snapshot,full:true,reason};const before=defined(previous,"baseline");const added=[];const changed=[];const removed=[];for(const[ref,node]of current.nodes){const old=before.nodes.get(ref);if(!old)added.push({...node});else if(old.tree!==node.tree){const label=/^[^\s"]+(?: "(?:\\.|[^"\\])*")? /;let tree=node.tree;const heading=label.exec(tree)?.[0];if(heading&&heading===label.exec(old.tree)?.[0])tree=tree.slice(heading.length);const placeholder=/ \[placeholder="(?:\\.|[^"\\])*"\]/.exec(tree)?.[0];if(placeholder&&old.tree.includes(placeholder))tree=tree.replace(placeholder,"");changed.push({ref,tree})}}for(const ref of before.nodes.keys())if(!current.nodes.has(ref))removed.push(ref);const result={diff:{added,changed,removed,focused:current.focused},full:false};if(Buffer.byteLength(JSON.stringify(result),"utf8")>Buffer.byteLength(snapshot.tree,"utf8")){return{...snapshot,full:true,reason:"diff-larger-than-full"}}return result}function subscribeConsoleEvents(page){return page.cdp.on("Runtime.consoleAPICalled",(event,metadata)=>{if(!metadata.sessionId||!page.frameManager.hasSession(metadata.sessionId))return;const text=(event.args??[]).map((arg)=>{if(arg.unserializableValue!==undefined)return arg.unserializableValue;if(arg.value!==undefined)return typeof arg.value==="string"?arg.value:String(arg.value);return arg.description??arg.type}).join(" ");page.events.emit("console",{type:()=>event.type,text:()=>text}).catch((error)=>console.warn("[console] page event listener failed",error))})}var PAGE_EVENT_NAMES=Object.freeze(["close","console","crash","dialog","domcontentloaded","download","filechooser","frameattached","framedetached","framenavigated","load","pageerror","popup","request","response"]);var PAGE_EVENT_NAME_SET=new Set(PAGE_EVENT_NAMES);var RUNTIME_PAGE_EVENTS=new Set(["console","pageerror"]);function assertPageEvent(name){if(!PAGE_EVENT_NAME_SET.has(name)){throw new TypeError(`Unknown page event: ${String(name)}. Supported events: ${PAGE_EVENT_NAMES.join(", ")}`)}}function pageError(details={}){const exception=details.exception??{};const description=typeof exception.description==="string"?exception.description:"";if(exception.subtype!=="error"||!description){const text=exception.value!==undefined?String(exception.value):description||details.text||"Uncaught exception";return new Error(text)}const name=exception.className??"Error";const head=description.split(/\n\s+at /)[0]??description;const error=new Error(head===name?"":head.startsWith(`${name}: `)?head.slice(name.length+2):head);error.name=name;error.stack=description;return error}function subscribePageErrors(page){return page.cdp.on("Runtime.exceptionThrown",(event,meta)=>{if(!meta?.sessionId||!page.frameManager.hasSession(meta.sessionId))return;const details=event.exceptionDetails??{};for(const frame of page.frameManager.frames.values()){if(frame.sessionId===meta.sessionId&&frame.isolatedContextId===details.executionContextId)return}page.events.emit("pageerror",pageError(details)).catch((error)=>console.warn("[pageerror] page event listener failed",error))})}var targetCreationCapability=Symbol("omowright.targetCreationCapability");function normalizeDialogPolicy(policy){return policy??{accept:true}}function dialogFromOpening(params={}){return{type:params.type,message:params.message,defaultPrompt:params.defaultPrompt??"",url:params.url}}function decisionFromResult(result){if(typeof result==="boolean")return{accept:result};if(result&&typeof result==="object"){const decision={accept:result.accept!==false};if(result.promptText!==undefined)decision.promptText=result.promptText;return decision}return{accept:true}}async function resolveDialogAction(policy,params={}){try{const result=typeof policy==="function"?await policy(dialogFromOpening(params)):policy;return decisionFromResult(result)}catch{return{accept:true}}}var isAnswered;var answer;class Dialog{#params;#send;#answered=false;constructor(params,send){this.#params=params??{};this.#send=send}get url(){return this.#params.url}type(){return this.#params.type}message(){return this.#params.message}defaultValue(){return this.#params.defaultPrompt??""}accept(promptText){return this.#answer(promptText===undefined?{accept:true}:{accept:true,promptText})}dismiss(){return this.#answer({accept:false})}async#answer(action){if(this.#answered)throw new Error("this dialog is already handled");this.#answered=true;await this.#send(action)}static{isAnswered=(dialog)=>dialog.#answered;answer=(dialog,action)=>dialog.#answer(action)}}function dialogPolicyParams(params){return typeof params==="object"&¶ms!==null?params:undefined}async function answerWithPolicy(dialog,policy,params){if(isAnswered(dialog))return;const action=await resolveDialogAction(policy,params);if(!isAnswered(dialog))await answer(dialog,action)}var controllers=new WeakMap;function globToRegExp(glob){let source="";for(const char of glob){if(char==="*")source+=".*";else if(char==="?")source+=".";else if("\\^$+{}[]()|.".includes(char))source+=`\\${char}`;else source+=char}return new RegExp(`^${source}$`)}function hasGlobChars(value){return value.includes("*")||value.includes("?")}function matches(match,request){if(typeof match==="function"){return Boolean(match({url:request.url,method:request.method,resourceType:request.resourceType,headers:request.headers}))}if(match instanceof RegExp)return match.test(request.url);if(typeof match==="string"){if(hasGlobChars(match))return globToRegExp(match).test(request.url);return request.url.includes(match)}return false}function sameMatch(left,right){if(left===right)return true;if(left instanceof RegExp&&right instanceof RegExp)return left.source===right.source&&left.flags===right.flags;return false}function toHeaderEntries(headers){if(!headers)return[];if(Array.isArray(headers)){return headers.map((header)=>({name:String(header.name),value:String(header.value??"")}))}return Object.entries(headers).map(([name,value])=>({name,value:String(value??"")}))}function encodeBody(body){if(body==null)return"";if(Buffer.isBuffer(body))return body.toString("base64");if(body instanceof Uint8Array)return Buffer.from(body).toString("base64");return Buffer.from(String(body)).toString("base64")}function buildContinue(requestId,{url,method,headers,postData}={}){const params={requestId};if(url!==undefined)params.url=url;if(method!==undefined)params.method=method;if(headers!==undefined)params.headers=toHeaderEntries(headers);if(postData!==undefined)params.postData=encodeBody(postData);return params}function buildFulfill(requestId,{status=200,headers={},contentType,body=""}={}){const responseHeaders=toHeaderEntries(headers);if(contentType!=null&&String(contentType).length>0){const hasType=responseHeaders.some((header)=>header.name.toLowerCase()==="content-type");if(!hasType)responseHeaders.push({name:"content-type",value:String(contentType)})}return{requestId,responseCode:status,responseHeaders,body:encodeBody(body)}}function createRoutes(page){if(!page?.cdp)throw new TypeError("createRoutes requires a page with cdp");const existing=controllers.get(page);if(existing)return existing;const entries=[];const warned=new WeakSet;const settledIds=new Set;let enabled=false;let sessionId;let unsubscribe=null;let lifecycle=Promise.resolve();let activeRequests=0;function warnOnce(handler,error){if(typeof handler==="function"){if(warned.has(handler))return;warned.add(handler)}if(error)console.warn("[routes] route handler failed; continuing request",error);else console.warn("[routes] route handler did not settle the request; continuing")}async function handlePaused(params,meta){if(!sessionId||meta?.sessionId!==sessionId)return;const requestId=params?.requestId;if(!requestId||settledIds.has(requestId))return;settledIds.add(requestId);activeRequests+=1;const request={url:params.request?.url??"",method:params.request?.method??"GET",headers:params.request?.headers??{},postData:params.request?.postData,resourceType:params.resourceType};let settled=false;const settle=(method,cdpParams)=>{if(settled)return Promise.resolve();settled=true;settledIds.add(requestId);return page.cdp.send(method,cdpParams,sessionId)};const candidates=entries.slice();let index=0;async function dispatch(){while(index<candidates.length){const entry=candidates[index++];if(entry===undefined)break;if(!entries.includes(entry)||!matches(entry.match,request))continue;if(--entry.remaining===0)entries.splice(entries.indexOf(entry),1);let acted=false;let fallbackPromise;const pausedRoute={request,continue(overrides={}){acted=true;return settle("Fetch.continueRequest",buildContinue(requestId,overrides))},fulfill(options={}){acted=true;return settle("Fetch.fulfillRequest",buildFulfill(requestId,options))},abort(errorReason="Failed"){acted=true;return settle("Fetch.failRequest",{requestId,errorReason})},fallback(){if(acted||settled)return Promise.resolve();acted=true;fallbackPromise=dispatch();return fallbackPromise}};try{await entry.handler(pausedRoute);await fallbackPromise}catch(error){warnOnce(entry.handler,error)}if(!acted&&!settled)warnOnce(entry.handler);break}if(!settled)await settle("Fetch.continueRequest",{requestId})}try{await dispatch()}catch(error){warnOnce(undefined,error);if(!settled)await settle("Fetch.continueRequest",{requestId})}finally{activeRequests-=1;if(entries.length===0&&activeRequests===0)await syncFetch()}}function onPaused(params,meta){handlePaused(params,meta).catch((error)=>{console.warn("[routes] requestPaused handling failed",error)})}function syncFetch(){const operation=lifecycle.then(async()=>{if(entries.length>0){if(enabled)return;sessionId=await page.resolveSessionId();if(!unsubscribe)unsubscribe=page.cdp.on("Fetch.requestPaused",onPaused);try{await page.cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]},sessionId)}catch(error){unsubscribe?.();unsubscribe=null;throw error}enabled=true}else if(enabled){await page.cdp.send("Fetch.disable",{},sessionId);enabled=false;unsubscribe?.();unsubscribe=null;settledIds.clear()}});lifecycle=operation.catch(()=>{});return operation}async function route(match,handler,{times=Infinity,prepend=false}={}){if(typeof handler!=="function")throw new TypeError("handler must be a function");if(times!==Infinity&&(!Number.isInteger(times)||times<1))throw new TypeError("times must be a positive integer");const entry={match,handler,remaining:times};if(prepend)entries.unshift(entry);else entries.push(entry);try{await syncFetch()}catch(error){const index=entries.indexOf(entry);if(index!==-1)entries.splice(index,1);throw error}}async function unroute(match,handler){if(match===undefined)entries.length=0;else{for(let index=entries.length-1;index>=0;index-=1){if(sameMatch(entries[index]?.match,match)&&(handler===undefined||entries[index]?.handler===handler))entries.splice(index,1)}}await syncFetch()}async function dispose(){entries.length=0;await syncFetch()}const controller={route,unroute,dispose,get enabled(){return enabled}};controllers.set(page,controller);return controller}var predicates=new WeakMap;var handlers=new WeakMap;var abortReasons={aborted:"Aborted",accessdenied:"AccessDenied",addressunreachable:"AddressUnreachable",blockedbyclient:"BlockedByClient",blockedbyresponse:"BlockedByResponse",connectionaborted:"ConnectionAborted",connectionclosed:"ConnectionClosed",connectionfailed:"ConnectionFailed",connectionrefused:"ConnectionRefused",connectionreset:"ConnectionReset",internetdisconnected:"InternetDisconnected",namenotresolved:"NameNotResolved",timedout:"TimedOut",failed:"Failed"};function urlMatcher(match){if(typeof match==="function"){let predicate=predicates.get(match);if(!predicate){predicate=(request)=>match(new URL(request.url));predicates.set(match,predicate)}return predicate}if(match instanceof RegExp){return new RegExp(match.source,match.flags.replace(/[gy]/g,""))}if(typeof match!=="string")throw new TypeError("url must be a glob string, RegExp or predicate");let source="";let groups=0;for(let index=0;index<match.length;index+=1){const char=match.charAt(index);if(char==="\\"){const literal=match[++index]??"\\";source+=literal.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}else if(char==="*"){const start=index;while(match[index+1]==="*")index+=1;const deep=index>start&&(start===0||match[start-1]==="/")&&(index+1===match.length||match[index+1]==="/");if(deep&&match[index+1]==="/"){source+="(?:.*/)?";index+=1}else source+=deep?".*":"[^/]*"}else if(char==="{"){source+="(?:";groups+=1}else if(char==="}"&&groups>0){source+=")";groups-=1}else if(char===","&&groups>0)source+="|";else source+=char.replace(/[.*+?^$()|[\]\\]/g,"\\$&")}return new RegExp(`^${source}$`)}function adaptHandler(handler){if(typeof handler!=="function")throw new TypeError("handler must be a function");const adapted=handlers.get(handler);if(adapted)return adapted;const created=(raw)=>{const request={url:()=>raw.request.url,method:()=>raw.request.method,headers:()=>Object.fromEntries(Object.entries(raw.request.headers).map(([key,value])=>[key.toLowerCase(),value])),postData:()=>raw.request.postData??null,resourceType:()=>raw.request.resourceType?.toLowerCase()};const route={request:()=>request,continue:(overrides)=>raw.continue(overrides),fallback:()=>raw.fallback(),abort(errorCode="failed"){const reason=abortReasons[errorCode];if(!reason)throw new TypeError(`Unknown error code: ${errorCode}`);return raw.abort(reason)},async fulfill(options={}){let{body,contentType}=options;if(options.json!==undefined){body=JSON.stringify(options.json);contentType??="application/json"}else if(options.path!==undefined){body=await readFile(options.path)}return raw.fulfill({...options,body,contentType})}};return handler(route,request)};handlers.set(handler,created);return created}function pageRoute(page,match,handler,options={}){return createRoutes(page).route(urlMatcher(match),adaptHandler(handler),{times:options.times,prepend:true})}function pageUnroute(page,match,handler){return createRoutes(page).unroute(urlMatcher(match),handler===undefined?undefined:adaptHandler(handler))}function pageUnrouteAll(page){return createRoutes(page).unroute()}var DEFAULT_AGENT_VIEWPORT=Object.freeze({width:1440,height:900});function validateViewport(viewport){const width=viewport?.width;if(!viewport||typeof width!=="number"||!Number.isInteger(width)||width<=0)throw new TypeError("viewport width and height must be positive integers");const height=viewport.height;if(typeof height!=="number"||!Number.isInteger(height)||height<=0)throw new TypeError("viewport width and height must be positive integers");return{width,height}}async function repinViewport(page,viewport,options={}){const size=validateViewport(viewport);const sessionId=await page.resolveSessionId();await page.cdp.send("Emulation.setDeviceMetricsOverride",{...size,screenWidth:size.width,screenHeight:size.height,deviceScaleFactor:options.deviceScaleFactor??1,mobile:options.mobile??false},sessionId);page.setCachedViewportSize(size);return{...size}}function readProperty(value,key){if(value===null||value===undefined){throw new TypeError(`Cannot read properties of ${value} (reading '${String(key)}')`)}return Reflect.get(new Object(value),key)}var states=new WeakMap;function bindingValue(...[value,decode]){if(decode){const[type,data]=value;if(type==="undefined")return;if(type==="number")return data==="-0"?-0:Number(data);if(type==="bigint")return BigInt(data);if(type==="array")return data.map((item)=>bindingValue(item,true));if(type==="object")return Object.fromEntries(data.map(([key,item])=>[key,bindingValue(item,true)]));return data}if(value===undefined)return["undefined"];if(typeof value==="number"&&(!Number.isFinite(value)||Object.is(value,-0)))return["number",Object.is(value,-0)?"-0":String(value)];if(typeof value==="bigint")return["bigint",String(value)];if(Array.isArray(value))return["array",value.map((item)=>bindingValue(item))];if(value!==null&&typeof value==="object")return["object",Object.entries(value).map(([key,item])=>[key,bindingValue(item)])];return["value",value]}function bindingScript(name,internalName){return`(() => {
|
|
71
|
+
const name = ${JSON.stringify(name)};
|
|
72
|
+
if (globalThis[name]?.__omowrightBinding) return;
|
|
73
|
+
const bindingValue = ${bindingValue.toString()};
|
|
74
|
+
const raw = globalThis[${JSON.stringify(internalName)}];
|
|
75
|
+
let sequence = 0;
|
|
76
|
+
const callbacks = new Map();
|
|
77
|
+
const fn = (...args) => new Promise((resolve, reject) => {
|
|
78
|
+
const id = ++sequence;
|
|
79
|
+
callbacks.set(id, { resolve, reject });
|
|
80
|
+
try { raw(JSON.stringify({ id, args: bindingValue(args) })); }
|
|
81
|
+
catch (error) { callbacks.delete(id); reject(error); }
|
|
82
|
+
});
|
|
83
|
+
fn.__omowrightBinding = { callbacks, bindingValue };
|
|
84
|
+
globalThis[name] = fn;
|
|
85
|
+
})()`}function hasPageBindings(page){return(states.get(page)?.bindings.size??0)>0}function setupState(page){const existing=states.get(page);if(existing)return existing;const state={scripts:[],bindings:new Map,sessions:new Map,headers:null,media:null};states.set(page,state);page.frameManager.sessionSetup=(sessionId)=>initializeSession(page,state,sessionId);const offBinding=page.cdp.on("Runtime.bindingCalled",(event,meta)=>{const binding=state.bindings.get(event.name);if(!binding||!state.sessions.has(meta.sessionId??""))return;deliverBinding(page,state,binding,event,meta.sessionId).catch(()=>{})});const offDetached=page.cdp.on("Target.detachedFromTarget",({sessionId})=>{state.sessions.get(sessionId)?.releaseNetwork?.();state.sessions.delete(sessionId)});page.events.on("close",async()=>{offBinding();offDetached();states.delete(page);delete page.frameManager.sessionSetup;for(const[sessionId,session]of state.sessions){session.releaseNetwork?.();for(const identifier of session.scripts.values()){await page.cdp.send("Page.removeScriptToEvaluateOnNewDocument",{identifier},sessionId).catch(()=>{})}for(const name of session.bindings){await page.cdp.send("Runtime.removeBinding",{name},sessionId).catch(()=>{})}if(state.bindings.size)await page.cdp.send("Runtime.disable",undefined,sessionId).catch(()=>{})}});return state}async function deliverBinding(page,state,binding,event,sessionId){const call=JSON.parse(event.payload);let result;try{const args=bindingValue(call.args,true);if(binding.source){const frameId=page.frameManager.mainWorldContexts?.get(`${sessionId}:${event.executionContextId}`);const frame=page.frames().find((candidate)=>candidate.frameId===frameId);if(!frame)throw Error("Binding caller frame is detached");if(page.context===undefined)throw new TypeError("page.context is not a function");args.unshift({context:page.context(),page,frame})}result={value:bindingValue(await binding.callback(...args))}}catch(error){result=error instanceof Error?{error:{name:error.name,message:error.message,stack:error.stack}}:{thrown:bindingValue(error)}}if(states.get(page)!==state||!state.sessions.has(sessionId??""))return;await page.cdp.send("Runtime.evaluate",{contextId:event.executionContextId,expression:`(() => {
|
|
86
|
+
const state = globalThis[${JSON.stringify(binding.name)}].__omowrightBinding;
|
|
87
|
+
const callback = state.callbacks.get(${call.id});
|
|
88
|
+
state.callbacks.delete(${call.id});
|
|
89
|
+
const result = ${JSON.stringify(result)};
|
|
90
|
+
if (result.error) {
|
|
91
|
+
const error = new Error(result.error.message);
|
|
92
|
+
error.name = result.error.name; error.stack = result.error.stack;
|
|
93
|
+
callback.reject(error);
|
|
94
|
+
} else if (result.thrown) callback.reject(state.bindingValue(result.thrown, true));
|
|
95
|
+
else callback.resolve(state.bindingValue(result.value, true));
|
|
96
|
+
})()`},sessionId)}async function installScripts(page,state,sessionId,session){for(const script of state.scripts){if(session.scripts.has(script))continue;const{identifier}=await page.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:script.source,runImmediately:script.binding},sessionId);session.scripts.set(script,identifier)}}function initializeSession(page,state,sessionId){let existing=state.sessions.get(sessionId);if(!existing){existing={scripts:new Map,bindings:new Set,ready:Promise.resolve()};state.sessions.set(sessionId,existing)}const session=existing;const operation=session.ready.then(async()=>{for(const[name]of state.bindings){if(session.bindings.has(name))continue;await page.cdp.send("Runtime.addBinding",{name},sessionId);session.bindings.add(name)}if(state.bindings.size&&!session.runtimeEnabled){await page.cdp.send("Runtime.enable",undefined,sessionId);session.runtimeEnabled=true}await installScripts(page,state,sessionId,session);if(state.headers!==null){session.releaseNetwork??=acquireNetwork(page.cdp,sessionId);await session.releaseNetwork.ready;await page.cdp.send("Network.setExtraHTTPHeaders",{headers:state.headers},sessionId)}if(state.media)await page.cdp.send("Emulation.setEmulatedMedia",state.media,sessionId)});session.ready=operation.catch(()=>{});return operation}async function updateSessions(page,state){const main=await page.resolveSessionId();const sessions=new Set([main,...[...page.frameManager.frames.values()].map((frame)=>frame.sessionId)]);for(const sessionId of sessions){await initializeSession(page,state,sessionId);await page.cdp.send("Target.setAutoAttach",{autoAttach:true,waitForDebuggerOnStart:true,flatten:true},sessionId)}}async function addInitScript(script,arg){let source;if(typeof script==="function"){source=`(() => { const __name = value => value; (${script.toString()})(${JSON.stringify(arg)??"undefined"}); })()`}else if(typeof script==="string")source=script;else if(typeof script?.content==="string")source=script.content;else if(typeof script?.path==="string")source=await readFile2(script.path,"utf8");else throw new TypeError("addInitScript requires a function, string, or { path | content }");const state=setupState(this);state.scripts.push({source,binding:false});await updateSessions(this,state)}async function exposeFunction(name,callback){await registerBinding(this,name,callback,false)}async function exposeBinding(name,callback){await registerBinding(this,name,callback,true)}async function registerBinding(page,name,callback,source){if(typeof name!=="string"||typeof callback!=="function")throw new TypeError(`${source?"exposeBinding":"exposeFunction"} requires a name and function`);const state=setupState(page);if([...state.bindings.values()].some((binding)=>binding.name===name))throw Error(`Function "${name}" has already been registered`);const internalName=`__omowright_binding_${randomUUID().replaceAll("-","")}`;const invoke=(...args)=>Reflect.apply(callback,undefined,args);state.bindings.set(internalName,{name,callback:invoke,source});state.scripts.push({source:bindingScript(name,internalName),binding:true});await updateSessions(page,state)}async function setExtraHTTPHeaders(headers){if(!headers||typeof headers!=="object"||Array.isArray(headers))throw new TypeError("headers must be an object of strings");const checked={};for(const[name,value]of Object.entries(headers)){if(typeof value!=="string")throw new TypeError(`Header "${name}" value must be a string`);checked[name]=value}const state=setupState(this);state.headers=checked;await updateSessions(this,state)}async function setViewportSize(viewport){const size=validateViewport(viewport);const hostSetViewportSize=readProperty(this.browser,"setViewportSize");if(hostSetViewportSize){if(typeof hostSetViewportSize!=="function")throw new TypeError("this.browser.setViewportSize is not a function");await Reflect.apply(hostSetViewportSize,this.browser,[size])}else await repinViewport(this,size)}var mediaFeatures={colorScheme:["prefers-color-scheme",["light","dark","no-preference"]],reducedMotion:["prefers-reduced-motion",["reduce","no-preference"]],forcedColors:["forced-colors",["active","none"]],contrast:["prefers-contrast",["more","no-preference"]]};var mediaFeatureKeys=["colorScheme","reducedMotion","forcedColors","contrast"];async function emulateMedia(options={}){if(options.media!==undefined&&options.media!==null&&!["screen","print"].includes(options.media))throw new TypeError("media must be screen, print or null");for(const key of mediaFeatureKeys){const[,allowed]=mediaFeatures[key];const value=options[key];if(value!==undefined&&value!==null&&!allowed.includes(value))throw new TypeError(`${key} must be ${allowed.join(", ")} or null`)}const state=setupState(this);const previous=new Map(state.media?.features.map((feature)=>[feature.name,feature.value]));for(const key of mediaFeatureKeys){const[name]=mediaFeatures[key];if(options[key]!==undefined)previous.set(name,options[key]??"")}state.media={media:options.media===undefined?state.media?.media??"":options.media??"",features:[...previous].map(([name,value])=>({name,value}))};await updateSessions(this,state)}function definedOrThrow(value){if(value===undefined)throw new TypeError(`Cannot read properties of undefined`);return value}function readOptionalProperty(value,key){return value===null||value===undefined?undefined:readProperty(value,key)}var __defProp2=Object.defineProperty;function __exportAll(definitions,namespace){const exports={};for(const name in definitions)__defProp2(exports,name,{get:definitions[name],enumerable:true});if(!namespace)__defProp2(exports,Symbol.toStringTag,{value:"Module"});return exports}var __esmMin=(factory,value,error)=>()=>{if(error)throw error[0];try{return factory&&(value=factory(factory=0)),value}catch(caught){error=[caught];throw caught}};if(!Promise.withResolvers){Promise.withResolvers=()=>{let resolve=unsetResolver;let reject=unsetResolver;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}function unsetResolver(){}class Emittery{#listeners=new Map;on(name,listener){const listeners=this.#listeners.get(name)??new Set;listeners.add(listener);this.#listeners.set(name,listeners);return()=>{listeners.delete(listener)}}async emit(name,data){const event={data,eventName:name};await Promise.all([...this.#listeners.get(name)??[]].map((listener)=>listener(event)))}clearListeners(){this.#listeners.clear()}listenerCount(name){return this.#listeners.get(name)?.size??0}}var{object:object2,string:string$2,number:number$2,array:array2,union:union$1,unknown:unknown$1,null:_null4}=exports_zod;var SESSION_ARTIFACTS_DIR=path2.join(tmpdir(),"omowright-artifacts");var noop=()=>{};var init_emittery=noop;var init_zod=noop;var init_context=noop;var init_utils$13=noop;var init_config=noop;var init_extension_bridge=noop;var init_commands$1=noop;var init_directory=noop;var init_process=noop;var init_event_bus=noop;var init_state_db=noop;var init_schema=noop;var init_store$1=noop;var init_drizzle_orm=noop;var init_types$8=noop;var init_nanoid=noop;function sleep$12(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason??Error("Aborted"));const onAbort=()=>{clearTimeout(timer);reject(signal?.reason??Error("Aborted"))};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);signal?.addEventListener("abort",onAbort,{once:true})})}function getCurrentReplAbortSignal(){return}function withCurrentReplAbort(fn){return fn()}function withoutReplContext(fn){return fn()}function replPrint(...values){console.warn(...values)}async function sendCommandToExtension(command,..._options){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}var WAIT_FOR_FUNCTION_SOURCE_LIMIT=200;var WAIT_FOR_FUNCTION_RAF_FALLBACK_MS=100;var WAIT_FOR_FUNCTION_CALL_MARGIN_MS=1000;class WaitForFunctionTimeoutError extends Error{constructor(source,timeoutMs){const compact=source.replace(/\s+/g," ").trim();const shown=compact.length>WAIT_FOR_FUNCTION_SOURCE_LIMIT?`${compact.slice(0,WAIT_FOR_FUNCTION_SOURCE_LIMIT)}…`:compact;super(`page.waitForFunction: timed out after ${timeoutMs}ms waiting for ${shown}`);this.name="WaitForFunctionTimeoutError";this.timeoutMs=timeoutMs}}function isNavigationInterruptedError(error){const message=error instanceof Error?error.message:String(error);return isContextDestroyedError(error)||message.includes("Cannot find object with given id")||message.includes("Inspected target navigated or closed")}function isUnserializableResultError(error){const message=error instanceof Error?error.message:String(error);return message.includes("Object reference chain is too long")||message.includes("Object couldn't be returned by value")}function isSessionDetachedError(error){return error instanceof Error&&error.name==="CdpSessionDetachedError"}class VideoRecordingError extends Error{constructor(message,options){super(message,options);this.name="VideoRecordingError"}}function spawnCommand([command,...args],options){const child=spawn(command,args,options);const process2={child,stdin:child.stdin,stderr:"",error:null,ready:new Promise((resolve)=>{child.once("spawn",resolve);child.once("error",resolve)}),exited:new Promise((resolve)=>child.once("close",resolve))};child.once("error",(error)=>{process2.error=error});child.stdin.on("error",(error)=>{if(!isProcessInputClosedError(error))process2.error??=error});child.stderr.setEncoding("utf8");child.stderr.on("data",(chunk)=>{process2.stderr+=chunk});return process2}async function disposeProcess(process2){process2.stdin.destroy();if(process2.child.exitCode===null&&process2.child.signalCode===null)process2.child.kill("SIGKILL");await process2.exited}var ENCODER_EXIT_TIMEOUT_MS=1e4;async function waitForExitCode(process2,timeoutMs){const stalled=Symbol("stalled");let timer;const deadline=new Promise((resolve)=>{timer=setTimeout(resolve,timeoutMs,stalled)});const code=await Promise.race([process2.exited,deadline]).finally(()=>clearTimeout(timer));if(code===stalled){await disposeProcess(process2);throw new Error(`ffmpeg did not exit within ${timeoutMs}ms after its input closed; it was killed.`)}if(process2.error)throw process2.error;return code}function writeProcessChunk(stdin,chunk){if(stdin.destroyed||stdin.writableEnded)return Promise.resolve();return new Promise((resolve,reject)=>stdin.write(chunk,(error)=>error&&!isProcessInputClosedError(error)?reject(error):resolve()))}function endProcessInput(stdin){if(stdin.destroyed||stdin.writableEnded)return Promise.resolve();return new Promise((resolve,reject)=>stdin.end((error)=>error&&!isProcessInputClosedError(error)?reject(error):resolve()))}function isProcessInputClosedError(error){return error?.code==="EPIPE"||error?.code==="ERR_STREAM_DESTROYED"||error?.code==="ERR_STREAM_WRITE_AFTER_END"}function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof readProperty(Vn,"status")==`number`&&(readProperty(Vn,"status")===401||readProperty(Vn,"status")===403)||typeof readOptionalProperty(readProperty(Vn,"response"),"status")==`number`&&(readProperty(readProperty(Vn,"response"),"status")===401||readProperty(readProperty(Vn,"response"),"status")===403)||typeof readOptionalProperty(readProperty(Vn,"error"),"status")==`number`&&(readProperty(readProperty(Vn,"error"),"status")===401||readProperty(readProperty(Vn,"error"),"status")===403)||typeof readOptionalProperty(readProperty(Vn,"cause"),"status")==`number`&&(readProperty(readProperty(Vn,"cause"),"status")===401||readProperty(readProperty(Vn,"cause"),"status")===403)||String(readOptionalProperty(readProperty(Vn,"error"),"message")??``).includes(`Missing or invalid Authorization header.`)||String(readOptionalProperty(readProperty(Vn,"cause"),"message")??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}function dialogOpeningParams(params){return typeof params==`object`?params:undefined}function isCdpWireResponse(message){return typeof message.id==`number`}function createBrowserCdpCommandErrorClass(){return class BrowserCdpCommandError extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`);this.method=xn;this.code=jn;this.data=Vn}}}function createCdpClientClass(){return class CdpClient{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#closedSessions=new Set;#l=new Emittery;#u=false;#closedEpoch=0;transportEvents=new Emittery;constructor(xn={}){if(typeof xn.cdpUrl!=`string`||xn.cdpUrl===``)throw TypeError(`CdpClient requires a cdpUrl: there is no default endpoint, so a missing URL can never reach a browser on 127.0.0.1:9222`);this.cdpUrl=normalizeBaseUrl(xn.cdpUrl),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS,this.#dialogPolicy=normalizeDialogPolicy(xn.dialogPolicy)}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(xn){this.#dialogPolicy=normalizeDialogPolicy(xn)}get isConnected(){return this.#r?.readyState===import_websocket.default.OPEN}start(){let Kn=this.#closedEpoch;this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b())}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array2(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=true,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();if(this.#closedSessions.has(Vn)&&xn!==`Page.close`)throw new CdpSessionDetachedError(`Page closed: ${xn}`,{method:xn,sessionId:Vn});let Yn=this.#r;if(!Yn||Yn.readyState!==import_websocket.default.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==undefined&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):undefined,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:undefined;if(this.#c.set(Zn,{method:String(xn),sessionId:Vn,reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai??noop,{once:true}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}closeSession(sessionId){this.#closedSessions.add(sessionId);for(const[id,entry]of this.#c){if(entry.sessionId!==sessionId)continue;clearTimeout(entry.timeout);this.#c.delete(id);entry.reject(new CdpSessionDetachedError(`Page closed: ${entry.method}`,{method:entry.method,sessionId}))}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#closedEpoch++,this.#i=null,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=import_websocket.default.OPEN)try{xn?.close(1000,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:true});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}async#g(){let xn=null,jn=false,Kn=this.#closedEpoch;for(let Vn of this.#n){if(Vn>0&&await sleep$12(Vn),this.#closedEpoch!==Kn)throw Error(`CDP client closed`);try{await this.#_({forceRefresh:jn},Kn);return}catch(Vn){if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=true)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={},Kn=this.#closedEpoch){let{headers:jn,wsUrl:Vn}=await this.#m(xn);if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);await new Promise((xn,qn)=>{let Jn=new import_websocket.default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{if(!Yn){if(Yn=true,this.#closedEpoch!==Kn){try{Jn.close(1000,`client closed`)}catch{}qn(Error(`CDP client closed`));return}this.#v(Jn),xn()}}),Jn.addEventListener(`message`,(xn)=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,(xn)=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:true}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch((xn)=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=true,jn&&jn!==xn&&jn.readyState<=import_websocket.default.OPEN)try{jn?.close(1000,`replaced`)}catch{}}#y(xn){let Kn=this.#closedEpoch;this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch((xn)=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b())}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3000;let Kn=this.#closedEpoch;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b())})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(isCdpWireResponse(Vn)){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method,jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;jn.meta.dialog=new Dialog(dialogOpeningParams(Vn.params),(dialogAction)=>this.send(`Page.handleJavaScriptDialog`,dialogAction,dialogSessionId))}let dialog=jn.meta.dialog,emitted=this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)});dialog&&emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,dialogPolicyParams(Vn.params))).catch(()=>{})}}}}}function createSessionManagerClass(){return class SessionManager{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,(xn)=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,(xn)=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map((xn)=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find((jn)=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:true});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}}function createPageConsoleClass(){return class PageConsole{#e;constructor(xn){this.#e=xn}async logs(xn={}){return await this.#e.evaluate((xn)=>window.__omowrightConsole?.drain(xn)??[],xn)}async clear(){await this.#e.evaluate(`(window).__omowrightConsole?.clear()`)}}}var DEFAULT_COMMAND_TIMEOUT_MS;var DEFAULT_RECONNECT_DELAYS_MS;var jsonVersionSchema;var jsonTargetSchema;var cdpWireMessageSchema;var BrowserCdpCommandError;var CdpClient;var init_client$6=__esmMin(()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=30000,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3000],jsonVersionSchema=object2({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object2({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object2({id:number$2(),sessionId:string$2().optional(),error:object2({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object2({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null4()]),BrowserCdpCommandError=createBrowserCdpCommandErrorClass(),CdpClient=createCdpClientClass()});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=createSessionManagerClass()});var init_cdp=__esmMin(()=>{init_client$6(),init_session_manager()});var BUNDLE$1;var init_omowright_world_bundle=__esmMin(()=>{BUNDLE$1=pageBundle});var MAX_BUFFER_SIZE;var CONSOLE_INTERCEPTOR_SCRIPT;var PageConsole;var init_console_capture=__esmMin(()=>{MAX_BUFFER_SIZE=1000,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){
|
|
67
97
|
if(window.__omowrightConsole)return;
|
|
68
98
|
var logs=[];
|
|
69
99
|
var orig={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug};
|
|
@@ -100,11 +130,11 @@ ${code}
|
|
|
100
130
|
},
|
|
101
131
|
clear:function(){logs.length=0}
|
|
102
132
|
};
|
|
103
|
-
})();`,PageConsole=
|
|
133
|
+
})();`,PageConsole=createPageConsoleClass()});function presentOrThrow(value){if(value===null||value===undefined)throw new TypeError(`Cannot read properties of ${value}`);return value}function initialized(read){return read()}function isContextDestroyedError(xn){let jn=xn instanceof Error?xn.message:String(xn);return jn.includes(`Cannot find context with specified id`)||jn.includes(`Execution context was destroyed`)}function createFrameManagerClass(){return class FrameManager{cdp;targetId;frames=new Map;mainWorldContexts=new Map;#e=new Set;#t=new Set;#n=new Map;#r=null;#i=null;#a;#o=null;#s=null;#c=[];onSessionInitialized;constructor(xn,jn,Vn){this.cdp=xn,this.targetId=jn,this.#a=Vn}#l(xn,jn){return this.cdp.on(xn,(xn,Vn)=>{this.#v(Vn.sessionId)&&jn(xn)})}async initialize(){this.#c.push(this.cdp.on("Runtime.executionContextCreated",({context},meta={})=>{if(this.#v(meta.sessionId)&&context.auxData?.isDefault)this.mainWorldContexts.set(`${meta.sessionId}:${context.id}`,context.auxData.frameId)}),this.cdp.on("Runtime.executionContextDestroyed",(event,meta={})=>this.mainWorldContexts.delete(`${meta.sessionId}:${event.executionContextId}`)),this.cdp.on("Runtime.executionContextsCleared",(_,meta={})=>{for(const key of this.mainWorldContexts.keys())if(key.startsWith(`${meta.sessionId}:`))this.mainWorldContexts.delete(key)}),this.cdp.on("Target.detachedFromTarget",({sessionId})=>{for(const key of this.mainWorldContexts.keys())if(key.startsWith(`${sessionId}:`))this.mainWorldContexts.delete(key)}));this.#c.push(this.#l(`Target.attachedToTarget`,(xn)=>{if(xn.targetInfo.type!==`iframe`)return;let jn=xn.targetInfo.targetId,Vn=this.frames.get(jn)??{frameId:jn,parentFrameId:xn.targetInfo.parentFrameId??null,url:xn.targetInfo.url??``,name:xn.targetInfo.title??``,sessionId:xn.sessionId};this.frames.set(jn,Vn),Vn.sessionId=xn.sessionId,this.#p(xn.sessionId).then(async()=>{this.onSessionInitialized?.(xn.sessionId);let jn=await this.#m(xn.sessionId,Vn.parentFrameId??xn.targetInfo.parentFrameId??null);await this.ensureInjected(jn)}).catch(()=>{})}));await this.#p(this.#a);let{identifier:xn}=await this.#f(`Page.addScriptToEvaluateOnNewDocument`,{source:BUNDLE$1,worldName:ISOLATED_WORLD_NAME,runImmediately:true});this.#o=xn;let{identifier:jn}=await this.#f(`Page.addScriptToEvaluateOnNewDocument`,{source:CONSOLE_INTERCEPTOR_SCRIPT,runImmediately:true});this.#s=jn,this.#c.push(this.#l(`Page.frameAttached`,(xn)=>{let jn=this.frames.get(xn.frameId);this.frames.set(xn.frameId,{frameId:xn.frameId,parentFrameId:xn.parentFrameId,url:jn?.url??``,name:jn?.name??``,sessionId:jn?.sessionId??this.#a,isolatedContextId:jn?.isolatedContextId})})),this.#c.push(this.#l(`Page.frameNavigated`,(xn)=>{let jn=xn.frame,Vn=this.frames.get(jn.id);for(let{frameId:qn}of this.collectDescendantFrames(jn.id).slice(1)){let Jn=definedOrThrow(this.frames.get(qn));this.#_(Jn),this.#n.delete(qn),this.frames.delete(qn),Jn.sessionId!==this.#a&&!this.hasSession(Jn.sessionId)&&this.#t.delete(Jn.sessionId)}Vn?.isolatedContextId&&this.#e.delete(Vn.isolatedContextId),this.#n.delete(jn.id),this.frames.set(jn.id,{frameId:jn.id,parentFrameId:jn.parentId??null,url:jn.url,name:jn.name??``,sessionId:Vn?.sessionId??this.#a,isolatedContextId:undefined}),jn.parentId||(this.#i=jn.id),this.ensureInjected(jn.id)})),this.#c.push(this.#l(`Page.frameDetached`,(xn)=>{let jn=this.frames.get(xn.frameId);if(jn?.isolatedContextId&&this.#e.delete(jn.isolatedContextId),this.#n.delete(xn.frameId),xn.reason===`swap`){jn&&delete jn.isolatedContextId;return}jn?.sessionId&&this.#t.delete(jn.sessionId),this.frames.delete(xn.frameId),this.#i===xn.frameId&&(this.#i=null)}));let{frameTree:Vn}=await this.#f(`Page.getFrameTree`);this.#d(Vn,null),await this.#u()}async#u(){await Promise.all([...this.frames.keys()].map((xn)=>this.ensureInjected(xn)))}get mainFrameId(){return this.#i}getFrame(xn){return this.frames.get(xn)??null}hasSession(xn){if(this.#a===xn)return true;for(let jn of this.frames.values())if(jn.sessionId===xn)return true;return false}async ensureInjected(xn){let jn=this.frames.get(xn);if(!jn)return null;if(jn.isolatedContextId&&this.#e.has(jn.isolatedContextId))return jn.isolatedContextId;let Vn=this.#n.get(xn);if(Vn)return await Vn;let qn=this.#h(xn);this.#n.set(xn,qn);try{return await qn}finally{this.#n.get(xn)===qn&&this.#n.delete(xn)}}collectDescendantFrames(xn){if(!this.frames.has(xn))return[];let jn=new Map;for(let xn of this.frames.values()){if(!xn.parentFrameId)continue;let Vn=jn.get(xn.parentFrameId)??[];Vn.push(xn.frameId),jn.set(xn.parentFrameId,Vn)}let Vn=[],qn=[{frameId:presentOrThrow(xn),parentFrameId:this.frames.get(xn)?.parentFrameId??null,depth:0}],Jn=new Set;for(;qn.length>0;){let xn=definedOrThrow(qn.shift());if(Jn.has(xn.frameId))continue;Jn.add(xn.frameId),Vn.push(xn);let Yn=jn.get(xn.frameId)??[];for(let jn of Yn)qn.push({frameId:jn,parentFrameId:xn.frameId,depth:xn.depth+1})}return Vn}resolveFrameIdForSnapshotPrefix(xn){if(this.#r){let jn=this.#r.get(xn);if(jn&&this.frames.has(jn))return jn;if(xn)return null}return!xn&&this.#i&&this.frames.has(this.#i)?this.#i:null}setSnapshotFramePrefixMap(xn){this.#r=xn}invalidateContext(xn){let jn=this.frames.get(xn);jn&&this.#_(jn)}async dispose(){for(let xn of this.#c)xn();this.#c=[];this.mainWorldContexts.clear();for(let xn of[this.#o,this.#s])xn&&await this.cdp.send(`Page.removeScriptToEvaluateOnNewDocument`,{identifier:xn},this.#a).catch(()=>{});this.#o=null,this.#s=null}async reconnect(xn){await this.dispose(),this.frames.clear(),this.#e.clear(),this.#t.clear(),this.#n.clear(),this.#r=null,this.#i=null,this.#a=xn,await this.initialize()}#d(xn,jn){let{frame:Vn}=xn,qn=this.frames.get(Vn.id);this.frames.set(Vn.id,{frameId:Vn.id,parentFrameId:jn,url:Vn.url,name:Vn.name??``,sessionId:qn?.sessionId??this.#a,isolatedContextId:qn?.isolatedContextId}),jn||(this.#i=Vn.id);for(let jn of xn.childFrames??[])this.#d(jn,Vn.id)}async#f(xn,jn){return await this.cdp.send(xn,jn,this.#a)}async#p(xn){this.#t.has(xn)||(await this.cdp.send(`Page.enable`,undefined,xn),await this.cdp.send(`DOM.enable`,undefined,xn),await this.cdp.send(`Inspector.enable`,undefined,xn).catch(()=>{}),await this.cdp.send(`Page.setWebLifecycleState`,{state:`active`},xn).catch(()=>{}),await this.cdp.send(`Emulation.setFocusEmulationEnabled`,{enabled:true},xn).catch(()=>{}),await this.cdp.send(`Target.setAutoAttach`,{autoAttach:true,waitForDebuggerOnStart:!!this.sessionSetup,flatten:true},xn),await(async()=>{try{await this.sessionSetup?.(xn)}finally{this.sessionSetup&&await this.cdp.send(`Runtime.runIfWaitingForDebugger`,undefined,xn)}})(),this.#t.add(xn))}async#m(xn,jn){let{frameTree:Vn}=await this.cdp.send(`Page.getFrameTree`,undefined,xn),qn=Vn.frame.parentId??jn??null;return this.#d(Vn,qn),Vn.frame.id}async#h(xn){let jn=this.frames.get(xn);if(!jn)return null;if(jn.isolatedContextId){if(await this.#g(jn))return this.#e.add(jn.isolatedContextId),jn.isolatedContextId;this.#_(jn)}try{let{executionContextId:Vn}=await this.cdp.send(`Page.createIsolatedWorld`,{frameId:xn,worldName:ISOLATED_WORLD_NAME},jn.sessionId||this.#a);jn.isolatedContextId=Vn}catch{return null}try{await this.cdp.send(`Runtime.evaluate`,{expression:BUNDLE$1,contextId:jn.isolatedContextId},jn.sessionId||this.#a)}catch(xn){if(isContextDestroyedError(xn))return this.#_(jn),null}return await this.#g(jn)?(this.#e.add(jn.isolatedContextId),jn.isolatedContextId):(this.#_(jn),null)}async#g(xn){if(!xn.isolatedContextId)return false;let{result:jn}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function() { return typeof globalThis.__omowright; }`,executionContextId:xn.isolatedContextId,returnByValue:true},xn.sessionId||this.#a).catch(()=>({result:{value:`error`}}));return jn.value===`object`}#_(xn){xn.isolatedContextId&&(this.#e.delete(xn.isolatedContextId),delete xn.isolatedContextId)}#v(xn){if(!xn)return false;if(xn===this.#a)return true;for(let jn of this.frames.values())if(jn.sessionId===xn)return true;return false}}}var ISOLATED_WORLD_NAME;var FrameManager;var init_frame_manager=__esmMin(()=>{init_client$6(),init_omowright_world_bundle(),init_console_capture(),ISOLATED_WORLD_NAME=`__omowright_utility`,FrameManager=createFrameManagerClass()});var init_notification_grants=__esmMin(()=>{init_drizzle_orm(),init_schema(),init_state_db()});function formatCallFrame(xn){let jn=xn.url?`${xn.url}:${(xn.lineNumber??0)+1}:${(xn.columnNumber??0)+1}`:null;if(!jn)return null;let Vn=xn.functionName?.trim();return Vn?`at ${Vn} (${jn})`:`at ${jn}`}function formatRuntimeException(xn,jn){if(!xn)return jn;let Vn=typeof xn.exception?.description==`string`&&xn.exception.description.trim()||typeof xn.exception?.value==`string`&&xn.exception.value.trim()||typeof xn.text==`string`&&xn.text.trim()||jn,qn=xn.stackTrace?.callFrames?.map(formatCallFrame).filter((xn)=>!!xn)??[],Jn=qn.some((xn)=>Vn.includes(xn));return qn.length>0&&!Jn?`${Vn}
|
|
104
134
|
${qn.join(`
|
|
105
|
-
`)}`:Vn}var init_errors$3=__esmMin(()=>{});var TRACKING_PARAMS;var init_tracking_params=__esmMin(()=>{TRACKING_PARAMS=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`gclid`,`gclsrc`,`fbclid`,`mc_cid`,`mc_eid`,`msclkid`,`twclid`,`li_fat_id`,`_ga`,`_gl`,`_t`,`_ts`,`_nc`])});function truncateUrlForLLM(xn,jn){let Vn=jn?.maxLength??128,qn;try{qn=new URL(xn)}catch{return xn.length>Vn?xn.slice(0,Vn)+`…`:xn}for(let xn of qn.searchParams.keys())TRACKING_PARAMS.has(xn.toLowerCase())&&qn.searchParams.delete(xn);if(jn?.currentOrigin)try{let xn=new URL(jn.currentOrigin);if(qn.origin===xn.origin){let xn=qn.pathname+qn.search+qn.hash;return xn.length>Vn?truncateQuery(xn,Vn):xn}}catch{}let Jn=qn.toString();return Jn.length<=Vn?Jn:truncateQuery(Jn,Vn)}function truncateQuery(xn,jn){let Vn=xn.indexOf(`?`);return Vn===-1||Vn>=jn?xn.length>jn?xn.slice(0,jn)+`…`:xn:xn.slice(0,jn)+`…`}var init_utils$4=__esmMin(()=>{init_tracking_params()});async function ensureDirForFile$1(xn){await promises.mkdir(
|
|
106
|
-
|
|
107
|
-
|
|
135
|
+
`)}`:Vn}var init_errors$3=__esmMin(()=>{});var TRACKING_PARAMS;var init_tracking_params=__esmMin(()=>{TRACKING_PARAMS=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`gclid`,`gclsrc`,`fbclid`,`mc_cid`,`mc_eid`,`msclkid`,`twclid`,`li_fat_id`,`_ga`,`_gl`,`_t`,`_ts`,`_nc`])});function truncateUrlForLLM(xn,jn){let Vn=jn?.maxLength??128,qn;try{qn=new URL(xn)}catch{return xn.length>Vn?xn.slice(0,Vn)+`…`:xn}for(let xn of qn.searchParams.keys())TRACKING_PARAMS.has(xn.toLowerCase())&&qn.searchParams.delete(xn);if(jn?.currentOrigin)try{let xn=new URL(jn.currentOrigin);if(qn.origin===xn.origin){let xn=qn.pathname+qn.search+qn.hash;return xn.length>Vn?truncateQuery(xn,Vn):xn}}catch{}let Jn=qn.toString();return Jn.length<=Vn?Jn:truncateQuery(Jn,Vn)}function truncateQuery(xn,jn){let Vn=xn.indexOf(`?`);return Vn===-1||Vn>=jn?xn.length>jn?xn.slice(0,jn)+`…`:xn:xn.slice(0,jn)+`…`}var init_utils$4=__esmMin(()=>{init_tracking_params()});async function ensureDirForFile$1(xn){await promises.mkdir(path2.dirname(xn),{recursive:true})}function createOmODownloadClass(){return class OmODownload{#e;#t;#n;#r;#i;#a=null;#o=false;constructor(xn,jn){this.#e=xn,this.#t=jn.guid,this.#n=jn.startedAfterMs,this.#r=jn.suggestedFilename,this.#i=jn.url,this.#a=jn.sourcePath?Promise.resolve(jn.sourcePath):null}page(){return this.#e}suggestedFilename(){return this.#r}url(){return this.#i}async path(){return this.#c(),await this.#s()}async saveAs(xn){this.#c();let jn=await this.#s(),Vn=path2.isAbsolute(xn)?xn:path2.join(SESSION_ARTIFACTS_DIR,xn),qn=await this.#e.browser.ensurePath(Vn,`write`,`download.saveAs`);path2.resolve(jn)!==path2.resolve(qn)&&(await ensureDirForFile$1(qn),await promises.copyFile(jn,qn))}async createReadStream(){return this.#c(),createReadStream(await this.#s())}async failure(){try{return await this.#s(),null}catch(xn){return xn instanceof Error?xn.message:String(xn)}}async cancel(){}async delete(){this.#c(),this.#o=true}async#s(){return this.#a||=this.#e.cdp.send(`OmO.waitForDownload`,{startedAfterMs:this.#n,expectedFilename:this.#r,referrerUrl:this.#e.url()},undefined,{extensionBridge:this.#e.browser.extensionBridgeRoute}).then((xn)=>xn.absolutePath),this.#e.browser.registerReadableDownloadPath(await this.#a)}#c(){if(this.#o)throw Error(`Download has been deleted.`)}get guid(){return this.#t}}}function createRefStaleErrorClass(){return class RefStaleError extends Error{constructor(xn){super(`Ref "${xn}" is stale — the element was removed or the page changed. Take a new snapshot and retry.`);this.name=`RefStaleError`}}}var OmODownload;var init_download=__esmMin(()=>{init_directory(),OmODownload=createOmODownloadClass()});var RefStaleError;var init_types$4=__esmMin(()=>{RefStaleError=createRefStaleErrorClass()});function resolveSmartModifierString(xn){if(xn.length===1)return xn;let jn=xn.trim();return jn.toLowerCase()===`controlormeta`?process.platform===`darwin`?`Meta`:`Control`:jn}function setKey(xn,jn){KEYBOARD_LAYOUT[xn]=jn}function addKey(xn,jn=[]){setKey(xn.key,xn),xn.code!==xn.key&&setKey(xn.code,xn);for(let Vn of jn)setKey(Vn,xn)}function addCodeOnlyKey(xn,jn=[]){setKey(xn.code,xn);for(let Vn of jn)setKey(Vn,xn)}function linkShifted(xn,jn){let Vn={...xn,key:jn,text:jn};return{...xn,shifted:Vn}}function keyCommands(xn,jn){if(process.platform!==`darwin`)return[];let Vn=[...[`Shift`,`Control`,`Alt`,`Meta`].filter((xn)=>jn.includes(xn)),xn].join(`+`),qn=MAC_EDITING_COMMANDS.get(Vn);return(Array.isArray(qn)?qn:qn?[qn]:[]).filter((xn)=>!xn.startsWith(`insert`)).map((xn)=>xn.replace(/:$/,``))}function lookupKeyDescriptor(xn){let jn=resolveSmartModifierString(xn);return KEYBOARD_LAYOUT[jn]??KEYBOARD_LAYOUT[jn.toLowerCase()]??KEYBOARD_LAYOUT[jn.toUpperCase()]}function resolveKeyDescriptor(xn,jn={}){let Vn=lookupKeyDescriptor(xn);if(!Vn)throw Error(`Unknown key: ${xn}`);let qn=new Set([...jn.modifiers??[]].map((xn)=>resolveSmartModifierString(xn)).filter((xn)=>MODIFIER_KEYS.has(xn))),Jn=qn.has(`Shift`)&&Vn.shifted?Vn.shifted:Vn;return Jn.text.length===0||qn.size===0||qn.size===1&&qn.has(`Shift`)?Jn:{...Jn,text:``}}function splitKeyCombo(xn){if(xn.length===1&&KEYBOARD_LAYOUT[xn])return[xn];let jn=xn.trim();if(!jn)return[];let Vn=[],qn=``;for(let xn of jn){if(xn!==`+`){qn+=xn;continue}if(qn.trim()){Vn.push(qn.trim()),qn=``;continue}Vn.push(`+`)}return qn.trim()&&Vn.push(qn.trim()),Vn}async function shouldUseDomInputFallback(xn){return await xn.evaluate(()=>document.visibilityState!==`visible`||!document.hasFocus())}function createModifierStateClass(){return class ModifierState{#e=new Set;#t=new Set;down(xn){MODIFIER_KEYS.has(xn)&&this.#e.add(xn)}up(xn){this.#e.delete(xn)}has(xn){return this.#e.has(xn)}modifiers(){return[...this.#e]}mouseDown(xn){this.#t.add(xn)}mouseUp(xn){this.#t.delete(xn)}toModifiersMask(){let xn=0;return this.#e.has(`Alt`)&&(xn|=1),this.#e.has(`Control`)&&(xn|=2),this.#e.has(`Meta`)&&(xn|=4),this.#e.has(`Shift`)&&(xn|=8),xn}toButtonsMask(){let xn=0;for(let jn of this.#t)xn|=BUTTON_MASKS.get(jn)??0;return xn}}}function createOmOKeyboardClass(){return class OmOKeyboard{context;modifierState;#e=new Set;constructor(xn,jn){this.context=xn,this.modifierState=jn}async down(xn){await this.#n(xn)}async up(xn){await this.#r(xn)}async insertText(xn){await this.#t(xn)}async press(xn,jn={},Vn){let qn=splitKeyCombo(xn);if(qn.length===0)throw Error(`Key combo is empty`);let Jn=qn.slice(0,-1),Yn=qn[qn.length-1],Zn=[],Qn;try{for(let xn of Jn)await this.#n(xn,Vn),Zn.push(xn);await this.#n(definedOrThrow(Yn),Vn),(jn.delay??0)>0&&await sleep$12(jn.delay),await this.#r(definedOrThrow(Yn),Vn)}catch(xn){Qn=xn}let ei;for(let xn=Zn.length-1;xn>=0;--xn)try{await this.#r(definedOrThrow(Zn[xn]),Vn)}catch(xn){ei??=xn}if(Qn)throw Qn;if(ei)throw ei}async type(xn,jn,Vn){let qn=jn?.delay??0;for(let jn of xn){if(jn===`
|
|
136
|
+
`||jn===`\r`||!lookupKeyDescriptor(jn)){qn>0&&await sleep$12(qn),await this.#t(jn,Vn);continue}await this.#a(jn,qn,Vn)}}async#t(xn,jn){await this.context._sendToTarget(`Input.insertText`,{text:xn},this.#i(jn))}async#n(xn,jn){let Vn=resolveKeyDescriptor(xn,{modifiers:this.modifierState.modifiers()}),qn=this.#e.has(Vn.code),Jn=this.modifierState.has(Vn.key);this.#e.add(Vn.code),this.modifierState.down(Vn.key);let Yn=keyCommands(Vn.code,this.modifierState.modifiers());try{await this.context._sendToTarget(`Input.dispatchKeyEvent`,{type:Vn.text?`keyDown`:`rawKeyDown`,key:Vn.key,code:Vn.code,commands:Yn,text:Vn.text,unmodifiedText:Vn.text,windowsVirtualKeyCode:Vn.keyCodeWithoutLocation,autoRepeat:qn,location:Vn.location,isKeypad:Vn.location===3,modifiers:this.modifierState.toModifiersMask()},this.#i(jn))}catch(xn){throw qn||this.#e.delete(Vn.code),Jn||this.modifierState.up(Vn.key),xn}return Vn}async#r(xn,jn){let Vn=resolveKeyDescriptor(xn,{modifiers:this.modifierState.modifiers()}),qn=this.#e.has(Vn.code),Jn=this.modifierState.has(Vn.key);this.#e.delete(Vn.code),this.modifierState.up(Vn.key);try{await this.context._sendToTarget(`Input.dispatchKeyEvent`,{type:`keyUp`,key:Vn.key,code:Vn.code,windowsVirtualKeyCode:Vn.keyCodeWithoutLocation,location:Vn.location,modifiers:this.modifierState.toModifiersMask()},this.#i(jn))}catch(xn){throw qn&&this.#e.add(Vn.code),Jn&&this.modifierState.down(Vn.key),xn}}#i(xn){return xn===undefined?undefined:{preferredSessionId:xn}}async#a(xn,jn,Vn){await this.#n(xn,Vn),jn>0&&await sleep$12(jn),await this.#r(xn,Vn)}}}var KEYBOARD_LAYOUT;var MODIFIER_KEYS;var BUTTON_MASKS;var MAC_EDITING_COMMANDS;var shiftedDigits;var ModifierState;var OmOKeyboard;var init_keyboard=__esmMin(()=>{init_utils$13(),KEYBOARD_LAYOUT={},MODIFIER_KEYS=new Set([`Alt`,`Control`,`Meta`,`Shift`]),BUTTON_MASKS=new Map([[`left`,1],[`right`,2],[`middle`,4],[`back`,8],[`forward`,16]]),MAC_EDITING_COMMANDS=new Map([[`Meta+KeyA`,`selectAll:`],[`Meta+KeyC`,`copy:`],[`Meta+KeyV`,`paste:`],[`Meta+KeyX`,`cut:`],[`Meta+KeyZ`,`undo:`],[`Shift+Meta+KeyZ`,`redo:`]]);for(let xn=0;xn<26;xn+=1){let jn=String.fromCharCode(97+xn),Vn=jn.toUpperCase(),qn=65+xn,Jn=linkShifted({key:jn,code:`Key${Vn}`,keyCode:qn,keyCodeWithoutLocation:qn,text:jn,location:0},Vn);addKey(Jn),setKey(Vn,Jn.shifted)}shiftedDigits=[` )`,`!`,`@`,`#`,`$`,`%`,`^`,`&`,`*`,`(`].map((xn)=>xn.trimStart());for(let xn=0;xn<10;xn+=1){let jn=String(xn),Vn=48+xn,qn=linkShifted({key:jn,code:`Digit${jn}`,keyCode:Vn,keyCodeWithoutLocation:Vn,text:jn,location:0},definedOrThrow(shiftedDigits[xn]));addKey(qn),setKey(qn.shifted.key,qn.shifted)}for(let{key:xn,shifted:jn,code:Vn,keyCode:qn}of[{key:"`",shifted:`~`,code:`Backquote`,keyCode:192},{key:`-`,shifted:`_`,code:`Minus`,keyCode:189},{key:`=`,shifted:`+`,code:`Equal`,keyCode:187},{key:`[`,shifted:`{`,code:`BracketLeft`,keyCode:219},{key:`]`,shifted:`}`,code:`BracketRight`,keyCode:221},{key:`\\`,shifted:`|`,code:`Backslash`,keyCode:220},{key:`;`,shifted:`:`,code:`Semicolon`,keyCode:186},{key:`'`,shifted:`"`,code:`Quote`,keyCode:222},{key:`,`,shifted:`<`,code:`Comma`,keyCode:188},{key:`.`,shifted:`>`,code:`Period`,keyCode:190},{key:`/`,shifted:`?`,code:`Slash`,keyCode:191}]){let Jn=linkShifted({key:xn,code:Vn,keyCode:qn,keyCodeWithoutLocation:qn,text:xn,location:0},jn);addKey(Jn),setKey(jn,Jn.shifted)}for(let[xn,jn]of[[{key:`Backspace`,code:`Backspace`,keyCode:8,keyCodeWithoutLocation:8,text:``,location:0}],[{key:`Tab`,code:`Tab`,keyCode:9,keyCodeWithoutLocation:9,text:` `,location:0},[` `]],[{key:`Enter`,code:`Enter`,keyCode:13,keyCodeWithoutLocation:13,text:`\r`,location:0},[`Return`,`
|
|
137
|
+
`,`\r`]],[{key:`Escape`,code:`Escape`,keyCode:27,keyCodeWithoutLocation:27,text:``,location:0},[`Esc`]],[{key:`Delete`,code:`Delete`,keyCode:46,keyCodeWithoutLocation:46,text:``,location:0},[`Del`]],[{key:`Insert`,code:`Insert`,keyCode:45,keyCodeWithoutLocation:45,text:``,location:0},[`Ins`]],[{key:`Home`,code:`Home`,keyCode:36,keyCodeWithoutLocation:36,text:``,location:0}],[{key:`End`,code:`End`,keyCode:35,keyCodeWithoutLocation:35,text:``,location:0}],[{key:`PageUp`,code:`PageUp`,keyCode:33,keyCodeWithoutLocation:33,text:``,location:0}],[{key:`PageDown`,code:`PageDown`,keyCode:34,keyCodeWithoutLocation:34,text:``,location:0}],[{key:`ArrowUp`,code:`ArrowUp`,keyCode:38,keyCodeWithoutLocation:38,text:``,location:0},[`Up`]],[{key:`ArrowDown`,code:`ArrowDown`,keyCode:40,keyCodeWithoutLocation:40,text:``,location:0},[`Down`]],[{key:`ArrowLeft`,code:`ArrowLeft`,keyCode:37,keyCodeWithoutLocation:37,text:``,location:0},[`Left`]],[{key:`ArrowRight`,code:`ArrowRight`,keyCode:39,keyCodeWithoutLocation:39,text:``,location:0},[`Right`]],[{key:`Shift`,code:`ShiftLeft`,keyCode:16,keyCodeWithoutLocation:16,text:``,location:1}],[{key:`Control`,code:`ControlLeft`,keyCode:17,keyCodeWithoutLocation:17,text:``,location:1},[`Ctrl`]],[{key:`Alt`,code:`AltLeft`,keyCode:18,keyCodeWithoutLocation:18,text:``,location:1},[`Option`]],[{key:`Meta`,code:`MetaLeft`,keyCode:91,keyCodeWithoutLocation:91,text:``,location:1},[`Command`,`Cmd`,`OS`]],[{key:`ContextMenu`,code:`ContextMenu`,keyCode:93,keyCodeWithoutLocation:93,text:``,location:0}],[{key:`CapsLock`,code:`CapsLock`,keyCode:20,keyCodeWithoutLocation:20,text:``,location:0}],[{key:`NumLock`,code:`NumLock`,keyCode:144,keyCodeWithoutLocation:144,text:``,location:0}],[{key:`ScrollLock`,code:`ScrollLock`,keyCode:145,keyCodeWithoutLocation:145,text:``,location:0}],[{key:`Pause`,code:`Pause`,keyCode:19,keyCodeWithoutLocation:19,text:``,location:0}],[{key:`PrintScreen`,code:`PrintScreen`,keyCode:44,keyCodeWithoutLocation:44,text:``,location:0}],[{key:`Space`,code:`Space`,keyCode:32,keyCodeWithoutLocation:32,text:` `,location:0},[` `]]])addKey(xn,jn);for(let xn=1;xn<=12;xn+=1){let jn=`F${xn}`;addKey({key:jn,code:jn,keyCode:111+xn,keyCodeWithoutLocation:111+xn,text:``,location:0})}for(let xn=0;xn<=9;xn+=1)addCodeOnlyKey({key:String(xn),code:`Numpad${xn}`,keyCode:96+xn,keyCodeWithoutLocation:48+xn,text:String(xn),location:3});for(let[xn,jn,Vn,qn]of[[`NumpadMultiply`,106,56,`*`],[`NumpadAdd`,107,187,`+`],[`NumpadSubtract`,109,189,`-`],[`NumpadDecimal`,110,190,`.`],[`NumpadDivide`,111,191,`/`],[`NumpadEnter`,13,13,`\r`]])addCodeOnlyKey({key:qn||xn,code:xn,keyCode:jn,keyCodeWithoutLocation:Vn,text:qn,location:3});ModifierState=createModifierStateClass(),OmOKeyboard=createOmOKeyboardClass()});function isTransientEvaluationError(xn){if(!(xn instanceof Error))return false;let jn=xn.message.toLowerCase();return jn.includes(`execution context was destroyed`)||jn.includes(`cannot find context with specified id`)||jn.includes(`cannot find object with given id`)||jn.includes(`most likely because of a navigation`)||jn.includes(`inspected target navigated or closed`)||jn.includes(`target page, context or browser has been closed`)}function isDomReadyTimeoutError(xn){return xn instanceof Error&&xn.message.includes(`Timed out waiting for document readiness`)}function isPdfViewerUrl(xn){return xn.startsWith(PDF_VIEWER_EXTENSION_PREFIX)||xn.endsWith(`.pdf`)}function getProbeState(xn){return xn.bodyExists?xn.interactiveCount>0||xn.landmarkCount>0||xn.textChars>=MIN_PROBE_TEXT_CHARS||xn.frameset&&xn.documentComplete?`ready`:`sparse`:`missing-body`}function getNaiveRegistrableDomain(xn){try{let jn=new URL(xn).hostname.toLowerCase(),Vn=jn.split(`.`).filter(Boolean);return Vn.length<=2?jn:Vn.slice(-2).join(`.`)}catch{return``}}function isSameSite(xn,jn){return jn?xn===jn||xn.endsWith(`.${jn}`):false}async function waitForDomReady(xn,jn=DOM_READY_TIMEOUT_MS){let Vn=Date.now()+jn;for(;Date.now()<Vn;){try{if(await xn.evaluate(`document.readyState`)!==`loading`)return}catch(xn){if(!isTransientEvaluationError(xn))throw xn}await sleep$12(50)}throw Error(`Timed out waiting for document readiness after ${jn}ms`)}async function takePageProbe(xn){let jn=await xn.evaluate(`(() => {
|
|
108
138
|
const isVisibleElement = (element) => {
|
|
109
139
|
const style = window.getComputedStyle(element);
|
|
110
140
|
if (
|
|
@@ -162,12 +192,22 @@ ${qn.join(`
|
|
|
162
192
|
return {
|
|
163
193
|
bodyExists: true,
|
|
164
194
|
interactiveCount: Array.from(document.querySelectorAll(interactiveSelector))
|
|
165
|
-
.filter((element) =>
|
|
195
|
+
.filter((element) => {
|
|
196
|
+
if (!isVisibleElement(element)) return false;
|
|
197
|
+
if (element.matches('a[href]')) {
|
|
198
|
+
const href = element.getAttribute('href').trim();
|
|
199
|
+
if (href.startsWith('#')) return false;
|
|
200
|
+
if (href.includes('#') && element.href.split('#')[0] === location.href.split('#')[0]) return false;
|
|
201
|
+
}
|
|
202
|
+
return true;
|
|
203
|
+
})
|
|
166
204
|
.slice(0, 25).length,
|
|
167
205
|
landmarkCount: Array.from(document.querySelectorAll(landmarkSelector))
|
|
168
206
|
.filter((element) => isVisibleElement(element))
|
|
169
207
|
.slice(0, 10).length,
|
|
170
208
|
textChars: body.innerText.replace(/\\s+/g, ' ').trim().length,
|
|
209
|
+
documentComplete: document.readyState === 'complete',
|
|
210
|
+
frameset: body.tagName === 'FRAMESET',
|
|
171
211
|
};
|
|
172
212
|
})()`);return{...jn,state:getProbeState(jn)}}async function ensureDomMonitor(xn){await xn.evaluate(`(() => {
|
|
173
213
|
const key = ${JSON.stringify(DOM_MONITOR_KEY)};
|
|
@@ -211,8 +251,8 @@ ${qn.join(`
|
|
|
211
251
|
}
|
|
212
252
|
|
|
213
253
|
return monitor.takeSnapshot();
|
|
214
|
-
})()`)}function collectTrackedSessionIds(xn,jn){let Vn=new Set;jn&&Vn.add(jn);for(let jn of xn.frameManager.frames.values())Vn.add(jn.sessionId);return Vn}async function waitForNavigationReadiness(
|
|
215
|
-
`).replace(/\n+$/g,``);return Vn(xn)===Vn(jn)}function isStaleObjectError(xn){let jn=xn instanceof Error?xn.message:String(xn);return jn.includes(`Cannot find object with given id`)||jn.includes(`Cannot find context with specified id`)||jn.includes(`Object reference chain is too long`)}function quadArea(xn){if(xn.length!==8)return 0;let jn=[{x:xn[0],y:xn[1]},{x:xn[2],y:xn[3]},{x:xn[4],y:xn[5]},{x:xn[6],y:xn[7]}],Vn=0;for(let xn=0;xn<jn.length;xn+=1){let qn=jn[xn],Jn=jn[(xn+1)%jn.length];Vn+=qn.x*Jn.y-Jn.x*qn.y}return Math.abs(Vn/2)}function quadCenter(xn){return{x:(xn[0]+xn[2]+xn[4]+xn[6])/4,y:(xn[1]+xn[3]+xn[5]+xn[7])/4}}async function resolveActionSessionId(xn,jn){return await xn.resolveSessionId(jn?.frameSessionId)}async function callOnElement(xn,jn,Vn,...qn){try{let Jn=qn.map((xn)=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:true,awaitPromise:true,userGesture:true},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));return Zn.value}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function callOnElementSync(xn,jn,Vn,...qn){try{let Jn=qn.map((xn)=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:true,awaitPromise:false,userGesture:true},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));return Zn.value}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function callOnElementHandle(xn,jn,Vn,...qn){try{let Jn=qn.map((xn)=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:false,awaitPromise:true,userGesture:true},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));if(!Zn.objectId)throw Error(`Runtime.callFunctionOn did not return an object handle`);return{objectId:Zn.objectId,frameId:jn.frameId,frameSessionId:jn.frameSessionId,contextId:jn.contextId}}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function resolveClickTarget(xn,jn){return await callOnElementHandle(xn,jn,`function() {
|
|
254
|
+
})()`)}function collectTrackedSessionIds(xn,jn){let Vn=new Set;jn&&Vn.add(jn);for(let jn of xn.frameManager.frames.values())Vn.add(jn.sessionId);return Vn}async function waitForNavigationReadiness(page,mode=`interactive`,timeoutMs=ACTION_MAX_WAIT_MS){let timer;try{return await Promise.race([waitForNavigationReadinessInner(page,mode,timeoutMs),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new NavigationReadinessTimeoutError(mode,timeoutMs)),timeoutMs+1000)})])}finally{clearTimeout(timer)}}async function waitForNavigationDomQuiet(page,budgetMs){if(budgetMs<=0)return;await page.evaluate((budgetMs)=>new Promise((resolve)=>{let observer,quietTimer;const finish=()=>{clearTimeout(quietTimer);clearTimeout(deadlineTimer);window.removeEventListener("load",onLoad);observer?.disconnect();resolve()};const resetQuiet=()=>{clearTimeout(quietTimer);quietTimer=setTimeout(finish,500)};const onLoad=()=>{if(document.body){observer=new MutationObserver(resetQuiet);observer.observe(document.body,{subtree:true,childList:true,characterData:true})}resetQuiet()};const deadlineTimer=setTimeout(finish,budgetMs);if(document.readyState==="complete")onLoad();else window.addEventListener("load",onLoad,{once:true})}),budgetMs)}async function waitForNavigationReadinessInner(page,mode,timeoutMs){if(isPdfViewerUrl(page.url())){await waitForDomReady(page,Math.min(DOM_READY_TIMEOUT_MS,timeoutMs)).catch(()=>{});return{bodyExists:true,interactiveCount:0,landmarkCount:0,textChars:0,state:"ready"}}const deadline=Date.now()+timeoutMs;const sessions=collectTrackedSessionIds(page,await page.resolveSessionId().catch(()=>{return}));const network=new NetworkTracker(page.cdp,sessions);let quietSamples=0,networkStarted=null,navigated=false;const off=page.cdp.on("Page.frameNavigated",(event,meta)=>{if(meta.sessionId&&sessions.has(meta.sessionId)&&!event.frame.parentId)navigated=true});try{await waitForDomReady(page,Math.min(DOM_READY_TIMEOUT_MS,timeoutMs)).catch(()=>{});if(mode==="stable")await ensureDomMonitor(page).catch(()=>{});while(Date.now()<deadline){await sleep$12(PROBE_INTERVAL_MS);try{if(navigated){navigated=false;quietSamples=0;networkStarted=null;await waitForDomReady(page,Math.min(DOM_READY_TIMEOUT_MS,Math.max(deadline-Date.now(),0))).catch(()=>{});if(mode==="stable")await ensureDomMonitor(page).catch(()=>{});continue}const probe=await takePageProbe(page);if(probe.state!=="ready"&&!(probe.state==="sparse"&&probe.documentComplete)){quietSamples=0;continue}if(network.captureTrackedRequests(page.url()).size>0){networkStarted??=Date.now();if(Date.now()-networkStarted<NAVIGATION_NETWORK_BUDGET_MS){quietSamples=0;continue}}const settleDeadline=Math.min(deadline,(networkStarted??Date.now())+NAVIGATION_NETWORK_BUDGET_MS);await waitForNavigationDomQuiet(page,Math.max(settleDeadline-Date.now(),0));if(navigated)continue;if(mode==="interactive")return probe;const sample=await readDomMonitor(page);quietSamples=sample.mutationCount/sample.totalNodes<=QUIET_MUTATION_RATIO?quietSamples+1:0;if(quietSamples>=QUIET_SAMPLE_COUNT)return probe}catch(error){if(!isTransientEvaluationError(error))throw error;quietSamples=0;networkStarted=null;await waitForDomReady(page,Math.min(DOM_READY_TIMEOUT_MS,Math.max(deadline-Date.now(),0)))}}throw new NavigationReadinessTimeoutError(mode,timeoutMs)}finally{off();network.dispose()}}async function waitForDomQuiet(xn,jn={}){let Vn=jn.budgetMs??QUIET_WINDOW_MS,qn=jn.sampleIntervalMs??QUIET_SAMPLE_INTERVAL_MS,Jn=jn.quietMutationRatio??QUIET_MUTATION_RATIO,Yn=jn.quietSampleCount??QUIET_SAMPLE_COUNT,Zn=Date.now()+Vn,Qn=0;try{for(await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,Vn)).catch(()=>{}),await ensureDomMonitor(xn).catch(()=>{});Date.now()<Zn;){await sleep$12(qn);let jn=await readDomMonitor(xn);if(Qn=jn.mutationCount/jn.totalNodes<=Jn?Qn+1:0,Qn>=Yn)return true}}catch(xn){if(!isTransientEvaluationError(xn))throw xn}return false}async function performActionAndWait(xn,jn,Vn={}){let qn=Vn.timeoutMs??ACTION_MAX_WAIT_MS,Jn=Date.now()+qn,Yn=collectTrackedSessionIds(xn,Vn.frameSessionId?await xn.resolveSessionId(Vn.frameSessionId):await xn.resolveSessionId()),Zn=new NetworkTracker(xn.cdp,Yn),Qn=false,ei,ti=await xn.evaluate(()=>location.href).catch(()=>xn.url()),ni=xn.cdp.on(`Page.frameNavigated`,(xn,jn)=>{!jn.sessionId||!Yn.has(jn.sessionId)||xn.frame.parentId||(Qn=true)});try{await Zn.ready;ei=await jn();try{let jn=Math.max(Jn-Date.now(),0);await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,jn))}catch(xn){if(!isTransientEvaluationError(xn)&&!isDomReadyTimeoutError(xn))throw xn}await sleep$12(Vn.hookWindowMs??ACTION_HOOK_WINDOW_MS);let qn=Zn.captureTrackedRequests(xn.url()),Yn=Math.min(Date.now()+(Vn.requestTrackingBudgetMs??ACTION_REQUEST_TRACKING_BUDGET_MS),Jn);for(;qn.size>0&&Date.now()<Yn&&!Qn;){for(let xn of qn)Zn.isFinished(xn)&&qn.delete(xn);qn.size>0&&await sleep$12(NETWORK_TRACK_POLL_MS)}if(Qn)return await waitForNavigationReadiness(xn,`interactive`,Math.max(Jn-Date.now(),DOM_READY_TIMEOUT_MS)),ei;let ni=await xn.evaluate(()=>location.href).catch(()=>xn.url())!==ti,ri=Math.min(Vn.postSettleMs??(ni?SPA_URL_CHANGE_POST_SETTLE_MS:ACTION_POST_SETTLE_MS),Math.max(Jn-Date.now(),0));if(ri>0){let jn=ni?Math.min(SPA_URL_CHANGE_MIN_DWELL_MS,ri):0;ni&&await sleep$12(jn);let Vn=Math.max(ri-jn,0);await waitForDomQuiet(xn,{budgetMs:Vn,sampleIntervalMs:50,quietSampleCount:1}).catch(()=>false)||await sleep$12(Vn)}return ei}finally{ni(),Zn.dispose()}}function createNavigationReadinessTimeoutErrorClass(){return class NavigationReadinessTimeoutError extends Error{mode;timeoutMs;constructor(xn,jn){super(`Timed out waiting for ${xn} page after ${jn}ms`);this.name=`NavigationReadinessTimeoutError`;this.mode=xn;this.timeoutMs=jn}}}function createNetworkTrackerClass(){return class NetworkTracker{#e=new Map;#t=[];#n;constructor(xn,jn){for(let sessionId of jn)this.#t.push(acquireNetwork(xn,sessionId));this.ready=Promise.all(this.#t.map((off)=>off.ready));this.#n=new Set(jn),this.#t.push(xn.on(`Network.requestWillBeSent`,(xn,jn)=>{if(!jn.sessionId||!this.#n.has(jn.sessionId))return;let Vn=``;try{Vn=new URL(xn.request.url).hostname.toLowerCase()}catch{return}this.#e.set(xn.requestId,{hostname:Vn,resourceType:xn.type??`Other`,finished:false,startedAt:Date.now()})}));let Vn=(xn)=>{let jn=this.#e.get(xn);jn&&(jn.finished=true)};this.#t.push(xn.on(`Network.loadingFinished`,(xn,jn)=>{jn.sessionId&&this.#n.has(jn.sessionId)&&Vn(xn.requestId)})),this.#t.push(xn.on(`Network.loadingFailed`,(xn,jn)=>{jn.sessionId&&this.#n.has(jn.sessionId)&&Vn(xn.requestId)}))}captureTrackedRequests(xn){let jn=new Set,Vn=getNaiveRegistrableDomain(xn);for(let[xn,qn]of this.#e)qn.finished||isSameSite(qn.hostname,Vn)&&(REQUEST_SKIP_TYPES.has(qn.resourceType)||jn.add(xn));return jn}isFinished(xn){return this.#e.get(xn)?.finished??true}dispose(){for(let xn of this.#t)xn();this.#t.length=0}}}var DOM_READY_TIMEOUT_MS;var PROBE_INTERVAL_MS;var QUIET_MUTATION_RATIO;var QUIET_WINDOW_MS;var QUIET_SAMPLE_INTERVAL_MS;var QUIET_SAMPLE_COUNT;var MIN_PROBE_TEXT_CHARS;var ACTION_HOOK_WINDOW_MS;var ACTION_REQUEST_TRACKING_BUDGET_MS;var ACTION_POST_SETTLE_MS;var SPA_URL_CHANGE_MIN_DWELL_MS;var SPA_URL_CHANGE_POST_SETTLE_MS;var ACTION_MAX_WAIT_MS;var NETWORK_TRACK_POLL_MS;var NAVIGATION_NETWORK_BUDGET_MS;var DOM_MONITOR_KEY;var REQUEST_SKIP_TYPES;var NavigationReadinessTimeoutError;var PDF_VIEWER_EXTENSION_PREFIX;var NetworkTracker;var init_wait=__esmMin(()=>{init_utils$13(),DOM_READY_TIMEOUT_MS=2000,PROBE_INTERVAL_MS=100,QUIET_MUTATION_RATIO=0.01,QUIET_WINDOW_MS=350,QUIET_SAMPLE_INTERVAL_MS=100,QUIET_SAMPLE_COUNT=2,MIN_PROBE_TEXT_CHARS=20,ACTION_HOOK_WINDOW_MS=150,ACTION_REQUEST_TRACKING_BUDGET_MS=1200,ACTION_POST_SETTLE_MS=300,SPA_URL_CHANGE_MIN_DWELL_MS=500,SPA_URL_CHANGE_POST_SETTLE_MS=750,ACTION_MAX_WAIT_MS=8000,NETWORK_TRACK_POLL_MS=50,NAVIGATION_NETWORK_BUDGET_MS=1500,DOM_MONITOR_KEY=`__omowrightWaitDomMonitor`,REQUEST_SKIP_TYPES=new Set([`WebSocket`,`EventSource`,`Ping`,`Prefetch`,`CSPViolationReport`]),NavigationReadinessTimeoutError=createNavigationReadinessTimeoutErrorClass(),PDF_VIEWER_EXTENSION_PREFIX=`chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai`,NetworkTracker=createNetworkTrackerClass()});function contentEditableValueMatches(xn,jn){if(xn===jn)return true;let Vn=(xn)=>xn.replace(/\u00a0/g,` `).replace(/\r\n/g,`
|
|
255
|
+
`).replace(/\n+$/g,``);return Vn(xn)===Vn(jn)}function indexListOf(value){if(!Array.isArray(value))throw new TypeError(`value.map is not a function`);return value}function pageResult(value){return value}function isFiniteNumber(value){return Number.isFinite(value)}function isFilePathList(files){return files.length===0||typeof files[0]==`string`}function startsWithFilePath(files){return typeof files[0]==`string`}function isStaleObjectError(xn){let jn=xn instanceof Error?xn.message:String(xn);return jn.includes(`Cannot find object with given id`)||jn.includes(`Cannot find context with specified id`)||jn.includes(`Object reference chain is too long`)}function quadArea(xn){if(xn.length!==8)return 0;let jn=[{x:xn[0],y:xn[1]},{x:xn[2],y:xn[3]},{x:xn[4],y:xn[5]},{x:xn[6],y:xn[7]}],Vn=0;for(let xn=0;xn<jn.length;xn+=1){let qn=definedOrThrow(jn[xn]),Jn=definedOrThrow(jn[(xn+1)%jn.length]);Vn+=definedOrThrow(qn.x)*definedOrThrow(Jn.y)-definedOrThrow(Jn.x)*definedOrThrow(qn.y)}return Math.abs(Vn/2)}function quadCenter(xn){return{x:(definedOrThrow(xn[0])+definedOrThrow(xn[2])+definedOrThrow(xn[4])+definedOrThrow(xn[6]))/4,y:(definedOrThrow(xn[1])+definedOrThrow(xn[3])+definedOrThrow(xn[5])+definedOrThrow(xn[7]))/4}}async function resolveActionSessionId(xn,jn){return await xn.resolveSessionId(jn?.frameSessionId)}async function callOnElement(xn,jn,Vn,...qn){try{let Jn=qn.map((xn)=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:true,awaitPromise:true,userGesture:true},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));return Zn.value}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function callOnElementSync(xn,jn,Vn,...qn){try{let Jn=qn.map((xn)=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:true,awaitPromise:false,userGesture:true},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));return Zn.value}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function callOnElementHandle(xn,jn,Vn,...qn){try{let Jn=qn.map((xn)=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:false,awaitPromise:true,userGesture:true},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));if(!Zn.objectId)throw Error(`Runtime.callFunctionOn did not return an object handle`);return{objectId:Zn.objectId,frameId:jn.frameId,frameSessionId:jn.frameSessionId,contextId:jn.contextId}}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function resolveClickTarget(xn,jn){return await callOnElementHandle(xn,jn,`function() {
|
|
216
256
|
const root = globalThis.__omowright?.retarget(this, 'none') || this;
|
|
217
257
|
|
|
218
258
|
// Some sites expose refs that point at semantic wrappers while the actual hit
|
|
@@ -276,7 +316,7 @@ ${qn.join(`
|
|
|
276
316
|
}`,Jn);if(Yn.ok)return await resolvePointerDispatchTarget(xn,jn,Jn);if(!(Yn.error?.includes(`obscured`)&&Vn!==ACTIONABILITY_RETRY_DELAYS_MS[ACTIONABILITY_RETRY_DELAYS_MS.length-1]))throw Error(Yn.error||`Element is not receiving pointer events`)}throw Error(`Element did not become clickable in time`)}async function resolvePointerDispatchTarget(xn,jn,Vn){let qn=await findFrameOwnerContentOffset(xn,jn.frameId);return qn?{point:{x:Vn.x+qn.x,y:Vn.y+qn.y},sessionId:await xn.resolveSessionId()}:{point:Vn,sessionId:await resolveActionSessionId(xn,jn)}}async function findFrameOwnerContentOffset(xn,jn){let Vn=await xn.resolveSessionId(),{root:qn}=await xn.cdp.send(`DOM.getDocument`,{depth:-1,pierce:true},Vn),{nodeIds:Jn}=await xn.cdp.send(`DOM.querySelectorAll`,{nodeId:qn.nodeId,selector:`iframe,frame`},Vn);for(let qn of Jn){let{node:Jn}=await xn.cdp.send(`DOM.describeNode`,{nodeId:qn},Vn);if(Jn.frameId!==jn)continue;let{object:Yn}=await xn.cdp.send(`DOM.resolveNode`,{nodeId:qn},Vn);if(Yn.objectId)try{let{result:jn,exceptionDetails:qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:Yn.objectId,functionDeclaration:`function() {
|
|
277
317
|
const rect = this.getBoundingClientRect();
|
|
278
318
|
return { x: rect.left, y: rect.top };
|
|
279
|
-
}`,returnByValue:true,awaitPromise:true,userGesture:false},Vn);if(qn)throw Error(formatRuntimeException(qn,`Unable to read frame owner rect`));let Jn=jn.value;if(
|
|
319
|
+
}`,returnByValue:true,awaitPromise:true,userGesture:false},Vn);if(qn)throw Error(formatRuntimeException(qn,`Unable to read frame owner rect`));let Jn=jn.value,x=readProperty(Jn,`x`),y=readProperty(Jn,`y`);if(isFiniteNumber(x)&&isFiniteNumber(y))return{x,y}}finally{await xn.cdp.send(`Runtime.releaseObject`,{objectId:Yn.objectId},Vn).catch(()=>{})}}return null}async function getLocalClickPoint(xn,jn){let Vn=await resolveActionSessionId(xn,jn);try{await xn.cdp.send(`DOM.scrollIntoViewIfNeeded`,{objectId:jn.objectId},Vn)}catch{await callOnElementSync(xn,jn,`function() {
|
|
280
320
|
if (this && this.scrollIntoView) {
|
|
281
321
|
this.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
|
|
282
322
|
}
|
|
@@ -307,7 +347,7 @@ ${qn.join(`
|
|
|
307
347
|
if (target && 'blur' in target && typeof target.blur === 'function') {
|
|
308
348
|
target.blur();
|
|
309
349
|
}
|
|
310
|
-
}`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:false,isCheckable:false,isRadio:false,prefersDomActivation:false}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?true:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==false&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===false)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,Zn[jn],qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {
|
|
350
|
+
}`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:false,isCheckable:false,isRadio:false,prefersDomActivation:false}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?true:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==false&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===false)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,definedOrThrow(Zn[jn]),qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {
|
|
311
351
|
const target = globalThis.__omowright?.retarget(this, 'follow-label');
|
|
312
352
|
if (!target) {
|
|
313
353
|
return { mode: 'needsinput', kind: 'input', expectedValue: '', error: 'Unable to retarget element' };
|
|
@@ -533,7 +573,7 @@ ${qn.join(`
|
|
|
533
573
|
width: rect.width,
|
|
534
574
|
height: rect.height,
|
|
535
575
|
};
|
|
536
|
-
}`);if(Vn)return Vn;let qn=await resolveActionSessionId(xn,jn),{model:Jn}=await xn.cdp.send(`DOM.getBoxModel`,{objectId:jn.objectId},qn),Yn=Jn.border;if(!Yn||Yn.length!==8)return null;let Zn=[Yn[0],Yn[2],Yn[4],Yn[6]],Qn=[Yn[1],Yn[3],Yn[5],Yn[7]],ei=Math.min(...Zn),ti=Math.max(...Zn),ni=Math.min(...Qn),ri=Math.max(...Qn);return{x:ei,y:ni,width:ti-ei,height:ri-ni}}catch{return null}}async function isCheckedElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
|
|
576
|
+
}`);if(Vn)return Vn;let qn=await resolveActionSessionId(xn,jn),{model:Jn}=await xn.cdp.send(`DOM.getBoxModel`,{objectId:jn.objectId},qn),Yn=Jn.border;if(!Yn||Yn.length!==8)return null;let Zn=[definedOrThrow(Yn[0]),definedOrThrow(Yn[2]),definedOrThrow(Yn[4]),definedOrThrow(Yn[6])],Qn=[definedOrThrow(Yn[1]),definedOrThrow(Yn[3]),definedOrThrow(Yn[5]),definedOrThrow(Yn[7])],ei=Math.min(...Zn),ti=Math.max(...Zn),ni=Math.min(...Qn),ri=Math.max(...Qn);return{x:ei,y:ni,width:ti-ei,height:ri-ni}}catch{return null}}async function isCheckedElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
|
|
537
577
|
return !!this.checked;
|
|
538
578
|
}`)}async function inputValueElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
|
|
539
579
|
return this.value || '';
|
|
@@ -636,7 +676,7 @@ ${qn.join(`
|
|
|
636
676
|
|| this.closest('[role=dialog], [role=region], section, form, main')?.querySelector('input[type=file]');
|
|
637
677
|
if (nearby) return nearby;
|
|
638
678
|
throw new Error('Element is not an <input type="file">');
|
|
639
|
-
}`);try{if(Vn
|
|
679
|
+
}`);try{if(isFilePathList(Vn)){let jn=await resolveActionSessionId(xn,qn);await xn.cdp.send(`DOM.setFileInputFiles`,{objectId:qn.objectId,files:Vn},jn);return}await callOnElementSync(xn,qn,`function(payloads) {
|
|
640
680
|
const input = this;
|
|
641
681
|
const transfer = new DataTransfer();
|
|
642
682
|
for (const payload of payloads) {
|
|
@@ -670,7 +710,7 @@ ${qn.join(`
|
|
|
670
710
|
}
|
|
671
711
|
this.dispatchEvent(new DragEvent('dragend', { bubbles: true, cancelable: true, dataTransfer }));
|
|
672
712
|
delete globalThis.__omowrightDragDataTransfer;
|
|
673
|
-
}`).catch(()=>{}))}
|
|
713
|
+
}`).catch(()=>{}))}function createOmOFrameClass(){return class xn{#e;frameId;constructor(xn,jn){this.#e=xn,this.frameId=jn}async resolveFrameId(){return this.frameId}label(){let xn=this.#t();return`frame ${xn.name||xn.url||xn.frameId}`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this.#e,this,xn)}async evaluate(xn,jn){return await this.#e.evaluateInFrame(this.frameId,xn,jn)}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}url(){return this.#t().url}name(){return this.#t().name}parentFrame(){let jn=this.#t().parentFrameId;return jn?new xn(this.#e,jn):null}#t(){let xn=this.#e.frameManager.getFrame(this.frameId);if(!xn)throw Error(`Frame is no longer available: ${this.frameId}`);return xn}}}function createFrameLocatorClass(){return class xn{#e;#t;#n;constructor(xn,jn,Vn){this.#e=xn,this.#t=jn,this.#n=Vn}async resolveFrameId(){let xn=await this.#t.resolveFrameId(),jn=await new OmOFrame(this.#e,xn).locator(this.#n).elementHandle().then((xn)=>xn.contentFrame());if(!jn)throw Error(`Frame locator "${this.#n}" did not resolve to an iframe`);return jn.frameId}label(){return`frameLocator(${this.#n})`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(jn){return new xn(this.#e,this,jn)}owner(){return new Locator(this.#e,this.#n,this.#t)}first(){return this.nth(0)}nth(jn){return new xn(this.#e,this.#t,`${this.#n}:nth(${jn})`)}last(){return new xn(this.#e,this.#t,`${this.#n}:nth(last)`)}}}var defaultModifierState;var kSetValueInputTypes;var kTypeIntoInputTypes;var ACTIONABILITY_RETRY_DELAYS_MS;var init_actions=__esmMin(()=>{init_context(),init_utils$13(),init_errors$3(),init_types$4(),init_keyboard(),init_wait(),defaultModifierState=new ModifierState,kSetValueInputTypes=[`color`,`date`,`datetime-local`,`month`,`range`,`time`,`week`],kTypeIntoInputTypes=[``,`email`,`number`,`password`,`search`,`tel`,`text`,`url`],ACTIONABILITY_RETRY_DELAYS_MS=[0,100,200]});var frame_exports=__exportAll({OmOFrame:()=>OmOFrame,FrameLocator:()=>FrameLocator});var OmOFrame;var FrameLocator;var init_frame=__esmMin(()=>{init_locator(),OmOFrame=createOmOFrameClass(),FrameLocator=createFrameLocatorClass()});function parseBackendNodeSelector(xn){if(!xn.startsWith(BACKEND_NODE_SELECTOR_PREFIX))return null;let jn=xn.slice(25),Vn=jn.indexOf(`:`);if(Vn<=0)throw Error(`Invalid backend node selector: ${xn}`);let qn=jn.slice(0,Vn),Jn=Number(jn.slice(Vn+1));if(!Number.isInteger(Jn)||Jn<=0)throw Error(`Invalid backend node selector: ${xn}`);return{frameId:qn,backendNodeId:Jn}}function createBackendNodeLocatorSelector(xn,jn){return`${BACKEND_NODE_SELECTOR_PREFIX}${xn}:${jn}`}function isLocatorResolutionMiss(xn){return xn instanceof RefStaleError?true:xn instanceof Error?xn.message.startsWith(`Selector "`)||xn.message.startsWith(`Role selector not found: `):false}function createLocatorClass(){return class xn{#e;#t;#n;#composition;constructor(xn,jn,Vn,composition){if(typeof jn!=`string`||jn.trim().length===0)throw Error(`Locator selector must be a non-empty string. Take a fresh snapshot and verify the ref exists.`);this.#e=xn,this.#n=Vn;let qn=jn.trim();this.#t=qn.replace(REF_SELECTOR_ALIAS_PATTERN,`$1`);this.#composition=composition;for(const name of Object.getOwnPropertyNames(Object.getPrototypeOf(xn))){if(name.startsWith(`getBy`)&&typeof Reflect.get(xn,name)===`function`)Reflect.set(this,name,(...args)=>{const child=Reflect.apply(Reflect.get(xn,name),xn,args);return this.locator(this.#selectorOf(child))})}}#selectorOf(child){if(typeof child==`object`&&child!==null&&#t in child)return child.#t;throw new TypeError(`Cannot read private member #t from an object whose class did not declare it`)}static createRoleSelector(xn,jn={}){let Vn=`role:${xn}`,qn=(xn,jn)=>{Vn+=`[${xn}=${jn}]`};if(jn.checked!==undefined&&qn(`checked`,String(jn.checked)),jn.disabled!==undefined&&qn(`disabled`,String(jn.disabled)),jn.expanded!==undefined&&qn(`expanded`,String(jn.expanded)),jn.includeHidden!==undefined&&qn(`include-hidden`,String(jn.includeHidden)),jn.level!==undefined&&qn(`level`,String(jn.level)),jn.pressed!==undefined&&qn(`pressed`,String(jn.pressed)),jn.selected!==undefined&&qn(`selected`,String(jn.selected)),jn.name!==undefined){let xn=jn.name;if(isRegExpValue(xn)){let jn=xn;qn(`name-regex`,encodeURIComponent(jn.source)),jn.flags&&qn(`name-regex-flags`,encodeURIComponent(jn.flags))}else qn(jn.exact?`name`:`name*`,encodeURIComponent(String(xn)))}return Vn}async#r(){if(this.#composition){const nodes=await this.#collect();if(!nodes.length)throw Error(`Selector "${this.#t}" not found`);return definedOrThrow(nodes[0])}let xn=parseBackendNodeSelector(this.#t);return xn?await this.#o(xn):isRef2(this.#t)?await this.#a(this.#t):isRoleSelector(this.#t)?await this.#l(this.#t):await this.#c(this.#t)}async#i(xn){try{let jn=await this.#r();if(xn===`attached`)return true;if(xn===`detached`)return false;let Vn=await isVisibleElement(this.#e,jn);return xn===`visible`?Vn:!Vn}catch(jn){if(!isLocatorResolutionMiss(jn))throw jn;return xn===`detached`||xn===`hidden`}}async click(xn){let jn=await this.#r();await clickElement(this.#e,jn,xn,this.#e.modifierState)}async fill(xn){let jn=await this.#r();await fillElement(this.#e,jn,xn)}async selectOption(xn){let jn=await this.#r();return await selectOptionElement(this.#e,jn,xn)}async check(xn){let jn=await this.#r();await checkElement(this.#e,jn,xn?.checked)}async scrollIntoViewIfNeeded(){let xn=await this.#r();await scrollIntoViewElement(this.#e,xn)}async press(xn){let jn=await this.#r();await pressElement(this.#e,jn,xn,this.#e.keyboard)}async pressSequentially(xn,jn={}){let Vn=await this.#r();await pressSequentiallyElement(this.#e,Vn,xn,jn.delay,this.#e.keyboard)}async hover(){let xn=await this.#r();await hoverElement(this.#e,xn)}async dblclick(xn){let jn=await this.#r();await clickElement(this.#e,jn,{...xn,dblClick:true},this.#e.modifierState)}async focus(){let xn=await this.#r();await focusResolvedElement(this.#e,xn)}async blur(){let xn=await this.#r();await blurResolvedElement(this.#e,xn)}async tap(){let xn=await this.#r();await tapElement(this.#e,xn)}async clear(){await this.fill(``)}async type(xn,jn={}){await this.pressSequentially(xn,jn)}async uncheck(){let xn=await this.#r();await checkElement(this.#e,xn,false)}async setChecked(xn){if(xn){await this.check();return}await this.uncheck()}async setInputFiles(xn){let jn=await this.#r();if(xn===null){await setInputFilesElement(this.#e,jn,[]);return}if(typeof xn==`string`){let Vn=await this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`);await setInputFilesElement(this.#e,jn,[Vn]);return}if(xn.length===0){await setInputFilesElement(this.#e,jn,[]);return}if(startsWithFilePath(xn)){let Vn=await Promise.all(xn.map((xn)=>this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`)));await setInputFilesElement(this.#e,jn,Vn);return}await setInputFilesElement(this.#e,jn,xn.map((xn)=>({name:xn.name,mimeType:xn.mimeType,base64:Buffer.from(xn.buffer).toString(`base64`)})))}async dragTo(xn,jn={}){let Vn=await this.#r(),qn=await xn.#r();await dragToElement(this.#e,Vn,qn,jn)}async evaluate(xn,jn){let Vn=await this.#r(),qn=typeof xn==`function`?xn.toString():xn;return await evaluateOnElement(this.#e,Vn,qn,jn)}async evaluateAll(xn,jn){if(!this.#composition&&isRoleSelector(this.#t))throw Error(`locator.evaluateAll() does not support role selectors yet; use a CSS selector.`);let Vn=this.#composition?[]:isRef2(this.#t)||parseBackendNodeSelector(this.#t)?[this]:await this.all(),qn=this.#composition?await this.#collect():await Promise.all(Vn.map((xn)=>xn.#r())),Jn=qn[0]??await this.#s();if(qn.some((xn)=>xn.contextId!==Jn.contextId))throw Error(`locator.evaluateAll() cannot pass elements from multiple frames to one page function.`);let Yn=typeof xn==`function`?xn.toString():xn,Zn=[{value:jn},...qn.map((xn)=>({objectId:xn.objectId}))],{result:Qn,exceptionDetails:ei}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`async function(arg, ...elements) {
|
|
674
714
|
var __name = (target) => target;
|
|
675
715
|
const pageFunction = (${Yn});
|
|
676
716
|
if (typeof pageFunction !== 'function') {
|
|
@@ -699,8 +739,8 @@ ${qn.join(`
|
|
|
699
739
|
width,
|
|
700
740
|
height,
|
|
701
741
|
};
|
|
702
|
-
}`,jn);if(!qn)throw Error(`locator.screenshot: element is not visible in the viewport`);let{path:Jn,quality:Yn,timeout:Zn,type:Qn=`webp`}=xn;return await this.#e.screenshot({path:Jn,quality:Yn,timeout:Zn,type:Qn,clip:qn})}async isChecked(){let xn=await this.#r();return await isCheckedElement(this.#e,xn)}async inputValue(){let xn=await this.#r();return await inputValueElement(this.#e,xn)}async innerHTML(){let xn=await this.#r();return await innerHTMLElement(this.#e,xn)}async innerText(){let xn=await this.#r();return await innerTextElement(this.#e,xn)}async textContent(){let xn=await this.#r();return await textContentElement(this.#e,xn)}async elementHandle(){return new ElementHandle(this.#e,await this.#r())}async count(){if(isRef2(this.#t))try{return await this.#a(this.#t),1}catch(xn){if(xn instanceof RefStaleError)return 0;throw xn}if(isRoleSelector(this.#t)){let xn=NTH_SELECTOR_PATTERN.test(this.#t),{nth:jn,...Vn}=this.#p(this.#t),qn=await this.#d(),Jn=0;for(let{frameId:xn}of qn){let jn=this.#e.frameManager.getFrame(xn);jn?.isolatedContextId&&(Jn+=await this.#m(await this.#e.resolveSessionId(jn.sessionId),jn.isolatedContextId,Vn))}return xn?+(Jn>0&&(jn===`last`||jn<Jn)):Jn}let xn=NTH_SELECTOR_PATTERN.test(this.#t),jn=this.#f(this.#t),Vn=await this.#u();return await this.#e.evaluateInFrame(Vn,`function(query) {
|
|
703
|
-
const
|
|
742
|
+
}`,jn);if(!qn)throw Error(`locator.screenshot: element is not visible in the viewport`);let{path:Jn,quality:Yn,timeout:Zn,type:Qn=`webp`}=xn;return await this.#e.screenshot({path:Jn,quality:Yn,timeout:Zn,type:Qn,clip:qn})}async isChecked(){let xn=await this.#r();return await isCheckedElement(this.#e,xn)}async inputValue(){let xn=await this.#r();return await inputValueElement(this.#e,xn)}async innerHTML(){let xn=await this.#r();return await innerHTMLElement(this.#e,xn)}async innerText(){let xn=await this.#r();return await innerTextElement(this.#e,xn)}async textContent(){let xn=await this.#r();return await textContentElement(this.#e,xn)}async elementHandle(){return new ElementHandle(this.#e,await this.#r())}async count(){if(this.#composition)return(await this.#collect()).length;if(isRef2(this.#t))try{return await this.#a(this.#t),1}catch(xn){if(xn instanceof RefStaleError)return 0;throw xn}if(isRoleSelector(this.#t)){let xn=NTH_SELECTOR_PATTERN.test(this.#t),{nth:jn,...Vn}=this.#p(this.#t),qn=await this.#d(),Jn=0;for(let{frameId:xn}of qn){let jn=this.#e.frameManager.getFrame(xn);jn?.isolatedContextId&&(Jn+=await this.#m(await this.#e.resolveSessionId(jn.sessionId),jn.isolatedContextId,Vn))}return xn?+(Jn>0&&(jn===`last`||jn<Jn)):Jn}let xn=NTH_SELECTOR_PATTERN.test(this.#t),jn=this.#f(this.#t),Vn=await this.#u();return await this.#e.evaluateInFrame(Vn,`function(query) {
|
|
743
|
+
const textMatching = (${createTextMatching.toString()})();
|
|
704
744
|
const parseTextMatcher = (raw) => {
|
|
705
745
|
if (!raw) return null;
|
|
706
746
|
if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
|
|
@@ -719,11 +759,25 @@ ${qn.join(`
|
|
|
719
759
|
}
|
|
720
760
|
return { contains: parseLiteral(raw) };
|
|
721
761
|
};
|
|
722
|
-
const matchesText =
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
762
|
+
const matchesText = textMatching.matchesText;
|
|
763
|
+
// getByPlaceholder/AltText/Title/TestId match like Playwright: a RegExp tests the raw attribute value,
|
|
764
|
+
// "..."s is the whole case-sensitive value and "..."i a case-insensitive substring.
|
|
765
|
+
const parseAttributeMatcher = (raw) => {
|
|
766
|
+
if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
|
|
767
|
+
const lastSlash = raw.lastIndexOf('/');
|
|
768
|
+
return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
|
|
769
|
+
}
|
|
770
|
+
return { value: JSON.parse(raw.slice(0, -1)), exact: raw.endsWith('s') };
|
|
771
|
+
};
|
|
772
|
+
const matchesAttribute = (node, attribute) => {
|
|
773
|
+
const value = node.getAttribute(attribute.name);
|
|
774
|
+
if (value === null) return false;
|
|
775
|
+
const matcher = attribute.matcher;
|
|
776
|
+
if (matcher instanceof RegExp) {
|
|
777
|
+
matcher.lastIndex = 0;
|
|
778
|
+
return matcher.test(value);
|
|
779
|
+
}
|
|
780
|
+
return matcher.exact ? value === matcher.value : value.toLowerCase().includes(matcher.value.toLowerCase());
|
|
727
781
|
};
|
|
728
782
|
const splitSteps = (value) => value.split(/\\s*>>\\s*/).map((step) => step.trim()).filter(Boolean);
|
|
729
783
|
const parseStep = (rawStep) => {
|
|
@@ -749,6 +803,16 @@ ${qn.join(`
|
|
|
749
803
|
nth,
|
|
750
804
|
};
|
|
751
805
|
}
|
|
806
|
+
const attributeMatch = base.match(/^internal:attr=\\[([^=\\]]+)=(.*)\\]$/s);
|
|
807
|
+
if (attributeMatch) {
|
|
808
|
+
return {
|
|
809
|
+
kind: 'attribute',
|
|
810
|
+
selector: '[' + CSS.escape(attributeMatch[1]) + ']',
|
|
811
|
+
attribute: { name: attributeMatch[1], matcher: parseAttributeMatcher(attributeMatch[2]) },
|
|
812
|
+
hasText,
|
|
813
|
+
nth,
|
|
814
|
+
};
|
|
815
|
+
}
|
|
752
816
|
return {
|
|
753
817
|
kind: 'css',
|
|
754
818
|
selector: base,
|
|
@@ -756,30 +820,17 @@ ${qn.join(`
|
|
|
756
820
|
nth,
|
|
757
821
|
};
|
|
758
822
|
};
|
|
759
|
-
const
|
|
823
|
+
const queryOpenShadowAll = (${queryOpenShadowAll.toString()});
|
|
824
|
+
const descendants = (root) => queryOpenShadowAll(root, '*');
|
|
760
825
|
const textMatches = (root, matcher) => {
|
|
761
826
|
const matches = descendants(root).filter((node) => matcher && matchesText(node, matcher));
|
|
762
|
-
return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)));
|
|
827
|
+
return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)) && !(node.shadowRoot && matchesText(node.shadowRoot, matcher)));
|
|
763
828
|
};
|
|
764
829
|
// Some sites duplicate the same visible label onto hidden or zero-sized inputs.
|
|
765
830
|
// Prefer the actionable associated control so getByLabel() doesn't latch onto
|
|
766
831
|
// an inert duplicate and fail later in the actionability pipeline.
|
|
767
832
|
const labelMatches = (root, matcher) => {
|
|
768
|
-
const
|
|
769
|
-
.filter((label) => matcher && matchesText(label, matcher));
|
|
770
|
-
const controlSelector = 'input:not([type="hidden"]), textarea, select';
|
|
771
|
-
const seen = new Set();
|
|
772
|
-
const controls = [];
|
|
773
|
-
for (const label of labels) {
|
|
774
|
-
const explicitControl = label.control || (label.htmlFor ? document.getElementById(label.htmlFor) : null);
|
|
775
|
-
// Virginia DMV's Bootstrap form uses a label with no htmlFor, followed
|
|
776
|
-
// immediately by its input in the same row.
|
|
777
|
-
const siblingControl = label.nextElementSibling?.matches?.(controlSelector) ? label.nextElementSibling : null;
|
|
778
|
-
const control = explicitControl || siblingControl;
|
|
779
|
-
if (!control || seen.has(control)) continue;
|
|
780
|
-
seen.add(control);
|
|
781
|
-
controls.push(control);
|
|
782
|
-
}
|
|
833
|
+
const controls = descendants(root).filter((node) => matcher && textMatching.labels(node).some((label) => textMatching.matches(label, matcher)));
|
|
783
834
|
controls.sort((a, b) => {
|
|
784
835
|
const rank = (node) => {
|
|
785
836
|
let score = 0;
|
|
@@ -806,11 +857,13 @@ ${qn.join(`
|
|
|
806
857
|
const next = [];
|
|
807
858
|
const seen = new Set();
|
|
808
859
|
for (const root of roots) {
|
|
809
|
-
let matches = step.kind === '
|
|
860
|
+
let matches = step.kind === 'attribute'
|
|
861
|
+
? queryOpenShadowAll(root, step.selector).filter((node) => matchesAttribute(node, step.attribute))
|
|
862
|
+
: step.kind === 'text'
|
|
810
863
|
? textMatches(root, step.matcher)
|
|
811
864
|
: step.kind === 'label'
|
|
812
865
|
? labelMatches(root, step.matcher)
|
|
813
|
-
:
|
|
866
|
+
: queryOpenShadowAll(root, step.selector);
|
|
814
867
|
if (step.hasText) {
|
|
815
868
|
matches = matches.filter((node) => matchesText(node, step.hasText));
|
|
816
869
|
}
|
|
@@ -831,8 +884,23 @@ ${qn.join(`
|
|
|
831
884
|
const nodes = queryAll(query.selector);
|
|
832
885
|
const index = query.nth === 'last' ? nodes.length - 1 : query.nth;
|
|
833
886
|
return query.hasNth ? (nodes[index] ? 1 : 0) : nodes.length;
|
|
834
|
-
}`,{selector:jn.selector,nth:jn.nth,hasNth:xn})}async getAttribute(xn){let jn=await this.#r();return await getAttributeElement(this.#e,jn,xn)}async isDisabled(){let xn=await this.#r();return await isDisabledElement(this.#e,xn)}async isEditable(){let xn=await this.#r();return await isEditableElement(this.#e,xn)}async isEnabled(){let xn=await this.#r();return await isEnabledElement(this.#e,xn)}async isHidden(){let xn=await this.#r();return await isHiddenElement(this.#e,xn)}async isVisible(){let xn=await this.#r();return await isVisibleElement(this.#e,xn)}async dispatchEvent(xn,jn){let Vn=await this.#r();await dispatchEventElement(this.#e,Vn,xn,jn)}async waitFor(xn={}){let jn=xn.state??`visible`;if(!LOCATOR_WAIT_STATES.includes(jn))throw Error(`locator.waitFor: invalid state "${jn}"`);let Vn=xn.timeout??DEFAULT_LOCATOR_WAIT_TIMEOUT_MS;if(!Number.isFinite(Vn)||Vn<0)throw Error(`locator.waitFor: timeout must be a non-negative number`);let qn=Date.now(),Jn=0;for(;;){if(await this.#i(jn))return;if(Date.now()-qn>=Vn)throw Error(`locator.waitFor: timed out after ${Vn}ms waiting for ${this} to be ${jn}`);await sleep$12(LOCATOR_WAIT_POLL_INTERVALS[Math.min(Jn++,LOCATOR_WAIT_POLL_INTERVALS.length-1)])}}first(){return new xn(this.#e
|
|
835
|
-
const
|
|
887
|
+
}`,{selector:jn.selector,nth:jn.nth,hasNth:xn})}async getAttribute(xn){let jn=await this.#r();return await getAttributeElement(this.#e,jn,xn)}async isDisabled(){let xn=await this.#r();return await isDisabledElement(this.#e,xn)}async isEditable(){let xn=await this.#r();return await isEditableElement(this.#e,xn)}async isEnabled(){let xn=await this.#r();return await isEnabledElement(this.#e,xn)}async isHidden(){let xn=await this.#r();return await isHiddenElement(this.#e,xn)}async isVisible(){let xn=await this.#r();return await isVisibleElement(this.#e,xn)}async dispatchEvent(xn,jn){let Vn=await this.#r();await dispatchEventElement(this.#e,Vn,xn,jn)}async waitFor(xn={}){let jn=xn.state??`visible`;if(!LOCATOR_WAIT_STATES.includes(jn))throw Error(`locator.waitFor: invalid state "${jn}"`);let Vn=xn.timeout??DEFAULT_LOCATOR_WAIT_TIMEOUT_MS;if(!Number.isFinite(Vn)||Vn<0)throw Error(`locator.waitFor: timeout must be a non-negative number`);let qn=Date.now(),Jn=0;for(;;){if(await this.#i(jn))return;if(Date.now()-qn>=Vn)throw Error(`locator.waitFor: timed out after ${Vn}ms waiting for ${this} to be ${jn}`);await sleep$12(LOCATOR_WAIT_POLL_INTERVALS[Math.min(Jn++,LOCATOR_WAIT_POLL_INTERVALS.length-1)])}}first(){return this.nth(0)}nth(index){return this.#composition?new xn(this.#e,this.#t,this.#n,{source:this,index}):new xn(this.#e,`${this.#t}:nth(${index})`,this.#n)}last(){return this.#composition?new xn(this.#e,this.#t,this.#n,{source:this,index:-1}):new xn(this.#e,isRef2(this.#t)||parseBackendNodeSelector(this.#t)?this.#t:`${this.#t}:nth(last)`,this.#n)}locator(selector,options={}){const child=new xn(this.#e,selector,this.#n);return new xn(this.#e,selector,this.#n,{source:this,child}).filter(options)}filter(options={}){for(const key of Object.keys(options))if(!["has","hasNot","hasText","hasNotText","visible"].includes(key))throw Error(`Unknown locator.filter option: ${key}`);for(const key of["has","hasNot"]){const value=options[key];if(value!==undefined&&(!(value instanceof xn)||value.#e!==this.#e||value.#n!==this.#n))throw Error(`locator.filter ${key} must be a locator in the same frame`)}return Object.keys(options).length?new xn(this.#e,this.#t,this.#n,{source:this,filters:{...options}}):this}and(locator){return this.#combine("and",locator)}or(locator){return this.#combine("or",locator)}#combine(mode,locator){if(!(locator instanceof xn)||locator.#e!==this.#e||locator.#n!==this.#n)throw Error(`locator.${mode}: argument must be a locator in the same frame`);return new xn(this.#e,this.#t,this.#n,{source:this,[mode]:locator})}async allTextContents(){return await Promise.all((await this.#collect()).map(async(node)=>await textContentElement(this.#e,node)??""))}async allInnerTexts(){return await Promise.all((await this.#collect()).map((node)=>innerTextElement(this.#e,node)))}async#collect(scope){let nodes;const plan=this.#composition;if(!plan&&scope!==undefined&&NTH_SELECTOR_PATTERN.test(this.#t)){const{selector,nth}=this.#f(this.#t);const matches=await new xn(this.#e,selector,this.#n).#collect(scope);const node=matches.at(nth==="last"?-1:nth);return node?[node]:[]}if(plan){nodes=await plan.source.#collect(scope);if(plan.child)return plan.child.#collect(nodes);if(plan.and||plan.or)return await this.#merge(nodes,await definedOrThrow(plan.and??plan.or).#collect(scope),plan.and?"and":"or");if(plan.index!==undefined){const node=nodes.at(plan.index);return node?[node]:[]}const options=definedOrThrow(plan.filters);const filtered=[];for(const node of nodes){const textOptions={};for(const key of["hasText","hasNotText"])if(options[key]!==undefined){const value=options[key];textOptions[key]=isRegExpValue(value)?{source:value.source,flags:value.flags}:String(value)}const matches=await evaluateOnElement(this.#e,node,`function(_, options){
|
|
888
|
+
const text=this.textContent||'';
|
|
889
|
+
const matchesText=(matcher)=>typeof matcher==='string'
|
|
890
|
+
?text.replace(/\\s+/g,' ').trim().toLowerCase().includes(matcher.toLowerCase())
|
|
891
|
+
:new RegExp(matcher.source,matcher.flags).test(text);
|
|
892
|
+
if(options.hasText!==undefined&&!matchesText(options.hasText))return false;
|
|
893
|
+
if(options.hasNotText!==undefined&&matchesText(options.hasNotText))return false;
|
|
894
|
+
return true;
|
|
895
|
+
}`,textOptions);if(!matches)continue;if(options.visible!==undefined&&await isVisibleElement(this.#e,node)!==options.visible)continue;if(options.has&&(await options.has.#collect([node])).length===0)continue;if(options.hasNot&&(await options.hasNot.#collect([node])).length!==0)continue;filtered.push(node)}return filtered}if(scope!==undefined&&!isRef2(this.#t)&&!parseBackendNodeSelector(this.#t)&&!isRoleSelector(this.#t)){const count=await this.#c(this.#t,scope,true);nodes=[];for(let index=0;index<count;index++)nodes.push(await this.#c(`${this.#t}:nth(${index})`,scope));return nodes}if(isRef2(this.#t)||parseBackendNodeSelector(this.#t)){try{nodes=[await this.#r()]}catch(error){if(!isLocatorResolutionMiss(error))throw error;nodes=[]}}else{const count=await this.count();nodes=[];for(let index=0;index<count;index++){const locator=NTH_SELECTOR_PATTERN.test(this.#t)?this:new xn(this.#e,`${this.#t}:nth(${index})`,this.#n);nodes.push(await locator.#r())}}if(scope===undefined)return nodes;const scoped=[];for(const node of nodes){for(const root of scope){if(root.contextId!==node.contextId||root.frameSessionId!==node.frameSessionId)continue;const{result,exceptionDetails}=await this.#e.cdp.send("Runtime.callFunctionOn",{objectId:root.objectId,functionDeclaration:`function(node){
|
|
896
|
+
if(node===this)return false;
|
|
897
|
+
for(let parent=node.parentNode||node.host;parent;parent=parent.parentNode||parent.host)if(parent===this)return true;
|
|
898
|
+
return false;
|
|
899
|
+
}`,arguments:[{objectId:node.objectId}],returnByValue:true},await this.#e.resolveSessionId(root.frameSessionId));if(exceptionDetails)throw Error(formatRuntimeException(exceptionDetails,"Locator scope evaluation failed"));if(result.value){scoped.push(node);break}}}return scoped}async#merge(left,right,mode){const nodes=[...left,...right],groups=new Map;nodes.forEach((node,index)=>{const key=`${node.frameSessionId} ${node.contextId}`;groups.has(key)?definedOrThrow(groups.get(key)).push(index):groups.set(key,[index])});const merged=[];for(const indexes of groups.values()){const group=indexes.map((index)=>definedOrThrow(nodes[index]));const{result,exceptionDetails}=await this.#e.cdp.send("Runtime.callFunctionOn",{objectId:definedOrThrow(group[0]).objectId,functionDeclaration:`function(query,...nodes){
|
|
900
|
+
if(query.mode==='and'){const right=new Set(nodes.slice(query.left));return nodes.slice(0,query.left).flatMap((node,index)=>right.has(node)?[index]:[])}
|
|
901
|
+
return [...new Set(nodes)].sort((a,b)=>a.compareDocumentPosition(b)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1).map(node=>nodes.indexOf(node));
|
|
902
|
+
}`,arguments:[{value:{mode,left:indexes.filter((index)=>index<left.length).length}},...group.map((node)=>({objectId:node.objectId}))],returnByValue:true},await this.#e.resolveSessionId(definedOrThrow(group[0]).frameSessionId));if(exceptionDetails)throw Error(formatRuntimeException(exceptionDetails,`locator.${mode} evaluation failed`));merged.push(...indexListOf(result.value).map((index)=>definedOrThrow(group[index])))}return merged}async all(){return Array.from({length:await this.count()},(_,index)=>this.nth(index))}toString(){return`Locator@${this.#t}`}async#a(xn){if(this.#n)throw Error(`Snapshot refs already include frame identity; use page.locator(ref) instead of frame.locator(ref).`);let jn=xn.match(REF_PATTERN);if(!jn)throw Error(`Invalid ref format: ${xn}`);let Vn=jn[1]??``,qn=this.#e.frameManager.resolveFrameIdForSnapshotPrefix(Vn);if(!qn)throw new RefStaleError(xn);let Jn=Vn?3:1;for(let jn=0;jn<Jn;jn++){jn>0&&await new Promise((xn)=>setTimeout(xn,50*jn));let Vn=this.#e.frameManager.getFrame(qn);if(!Vn||!Vn.isolatedContextId&&(await this.#e.frameManager.ensureInjected(qn),!Vn.isolatedContextId))throw new RefStaleError(xn);try{let{result:jn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(refId) { return globalThis.__omowright?.deref(refId) ?? null; }`,arguments:[{value:xn}],executionContextId:Vn.isolatedContextId,returnByValue:false,awaitPromise:false,userGesture:false},await this.#e.resolveSessionId(Vn.sessionId));if(jn.objectId)return{objectId:jn.objectId,frameId:qn,frameSessionId:Vn.sessionId,contextId:Vn.isolatedContextId}}catch{this.#e.frameManager.invalidateContext(qn)}}throw new RefStaleError(xn)}async#o(xn){let jn=this.#e.frameManager.getFrame(xn.frameId),Vn=await this.#e.frameManager.ensureInjected(xn.frameId);if(!jn||!Vn)throw Error(`File chooser element is no longer available`);let qn=await this.#e.resolveSessionId(jn.sessionId),{object:Jn}=await this.#e.cdp.send(`DOM.resolveNode`,{backendNodeId:xn.backendNodeId,executionContextId:Vn},qn);if(!Jn.objectId)throw Error(`File chooser element is no longer available`);return{objectId:Jn.objectId,frameId:xn.frameId,frameSessionId:jn.sessionId,contextId:Vn}}async#s(){let xn=await this.#u(),jn=this.#e.frameManager.getFrame(xn),Vn=await this.#e.frameManager.ensureInjected(xn);if(!jn||!Vn)throw Error(`${this.#n?.label()??`Main frame`} isolated world is not ready`);return{contextId:Vn,frameSessionId:jn.sessionId}}async#c(xn,scope,countOnly=false){let jn=await this.#u(),Vn=this.#e.frameManager.getFrame(jn),qn=await this.#e.frameManager.ensureInjected(jn);if(!Vn||!qn)throw Error(`${this.#n?.label()??`Main frame`} isolated world is not ready`);const scopeRoots=scope?.filter((root)=>root.contextId===qn&&root.frameSessionId===Vn.sessionId)??[];if(scope&&scopeRoots.length===0){if(countOnly)return 0;throw Error(`Selector "${xn}" not found`)}let Jn={...this.#f(xn),scoped:scope!==undefined,countOnly},{result:Yn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query, ...scopeRoots) {
|
|
903
|
+
const textMatching = (${createTextMatching.toString()})();
|
|
836
904
|
const parseTextMatcher = (raw) => {
|
|
837
905
|
if (!raw) return null;
|
|
838
906
|
if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
|
|
@@ -851,140 +919,25 @@ ${qn.join(`
|
|
|
851
919
|
}
|
|
852
920
|
return { contains: parseLiteral(raw) };
|
|
853
921
|
};
|
|
854
|
-
const matchesText =
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
return text.includes(matcher.contains);
|
|
859
|
-
};
|
|
860
|
-
const splitSteps = (value) => value.split(/\\s*>>\\s*/).map((step) => step.trim()).filter(Boolean);
|
|
861
|
-
const parseStep = (rawStep) => {
|
|
862
|
-
const nthMatch = rawStep.match(/^(.*):nth\\((\\d+|last)\\)$/s);
|
|
863
|
-
const rawBase = nthMatch ? (nthMatch[1] || '').trim() || '*' : rawStep;
|
|
864
|
-
const nth = nthMatch ? nthMatch[2] === 'last' ? 'last' : Number.parseInt(nthMatch[2], 10) : null;
|
|
865
|
-
const hasTextMatch = rawBase.match(/^(.*):has-text\\((.*)\\)$/s);
|
|
866
|
-
const base = hasTextMatch ? (hasTextMatch[1] || '').trim() || '*' : rawBase;
|
|
867
|
-
const hasText = hasTextMatch ? parseTextMatcher((hasTextMatch[2] || '').trim()) : null;
|
|
868
|
-
if (base.startsWith('text:')) {
|
|
869
|
-
return {
|
|
870
|
-
kind: 'text',
|
|
871
|
-
matcher: parseTextMatcher(base.slice(5)),
|
|
872
|
-
hasText,
|
|
873
|
-
nth,
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
if (base.startsWith('internal:label:')) {
|
|
877
|
-
return {
|
|
878
|
-
kind: 'label',
|
|
879
|
-
matcher: parseTextMatcher(base.slice(15)),
|
|
880
|
-
hasText,
|
|
881
|
-
nth,
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
return {
|
|
885
|
-
kind: 'css',
|
|
886
|
-
selector: base,
|
|
887
|
-
hasText,
|
|
888
|
-
nth,
|
|
889
|
-
};
|
|
890
|
-
};
|
|
891
|
-
const descendants = (root) => Array.from((root instanceof Document ? root : root).querySelectorAll('*'));
|
|
892
|
-
const textMatches = (root, matcher) => {
|
|
893
|
-
const matches = descendants(root).filter((node) => matcher && matchesText(node, matcher));
|
|
894
|
-
return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)));
|
|
895
|
-
};
|
|
896
|
-
// Keep label-based locators resilient when one label name points at both
|
|
897
|
-
// hidden template inputs and the visible live control.
|
|
898
|
-
const labelMatches = (root, matcher) => {
|
|
899
|
-
const labels = Array.from((root instanceof Document ? root : root).querySelectorAll('label'))
|
|
900
|
-
.filter((label) => matcher && matchesText(label, matcher));
|
|
901
|
-
const controlSelector = 'input:not([type="hidden"]), textarea, select';
|
|
902
|
-
const seen = new Set();
|
|
903
|
-
const controls = [];
|
|
904
|
-
for (const label of labels) {
|
|
905
|
-
const explicitControl = label.control || (label.htmlFor ? document.getElementById(label.htmlFor) : null);
|
|
906
|
-
// Virginia DMV's Bootstrap form uses a label with no htmlFor, followed
|
|
907
|
-
// immediately by its input in the same row.
|
|
908
|
-
const siblingControl = label.nextElementSibling?.matches?.(controlSelector) ? label.nextElementSibling : null;
|
|
909
|
-
const control = explicitControl || siblingControl;
|
|
910
|
-
if (!control || seen.has(control)) continue;
|
|
911
|
-
seen.add(control);
|
|
912
|
-
controls.push(control);
|
|
913
|
-
}
|
|
914
|
-
controls.sort((a, b) => {
|
|
915
|
-
const rank = (node) => {
|
|
916
|
-
let score = 0;
|
|
917
|
-
if (node.isConnected) score += 100;
|
|
918
|
-
const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
|
|
919
|
-
if (style && style.display !== 'none' && style.visibility !== 'hidden') {
|
|
920
|
-
score += 10;
|
|
921
|
-
}
|
|
922
|
-
const rect = typeof node.getBoundingClientRect === 'function' ? node.getBoundingClientRect() : null;
|
|
923
|
-
if (rect && rect.width > 0 && rect.height > 0) {
|
|
924
|
-
score += 1;
|
|
925
|
-
}
|
|
926
|
-
return score;
|
|
927
|
-
};
|
|
928
|
-
return rank(b) - rank(a);
|
|
929
|
-
});
|
|
930
|
-
return controls;
|
|
931
|
-
};
|
|
932
|
-
const queryAll = (value) => {
|
|
933
|
-
const steps = splitSteps(value);
|
|
934
|
-
let roots = [document];
|
|
935
|
-
for (const rawStep of steps) {
|
|
936
|
-
const step = parseStep(rawStep);
|
|
937
|
-
const next = [];
|
|
938
|
-
const seen = new Set();
|
|
939
|
-
for (const root of roots) {
|
|
940
|
-
let matches = step.kind === 'text'
|
|
941
|
-
? textMatches(root, step.matcher)
|
|
942
|
-
: step.kind === 'label'
|
|
943
|
-
? labelMatches(root, step.matcher)
|
|
944
|
-
: Array.from((root instanceof Document ? root : root).querySelectorAll(step.selector));
|
|
945
|
-
if (step.hasText) {
|
|
946
|
-
matches = matches.filter((node) => matchesText(node, step.hasText));
|
|
947
|
-
}
|
|
948
|
-
if (step.nth !== null) {
|
|
949
|
-
const index = step.nth === 'last' ? matches.length - 1 : step.nth;
|
|
950
|
-
matches = matches[index] ? [matches[index]] : [];
|
|
951
|
-
}
|
|
952
|
-
for (const node of matches) {
|
|
953
|
-
if (seen.has(node)) continue;
|
|
954
|
-
seen.add(node);
|
|
955
|
-
next.push(node);
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
roots = next;
|
|
959
|
-
}
|
|
960
|
-
return roots;
|
|
961
|
-
};
|
|
962
|
-
return queryAll(selector).length;
|
|
963
|
-
}`,this.#t);return Array.from({length:jn},(xn,jn)=>this.nth(jn))}toString(){return`Locator@${this.#t}`}async#a(xn){if(this.#n)throw Error(`Snapshot refs already include frame identity; use page.locator(ref) instead of frame.locator(ref).`);let jn=xn.match(REF_PATTERN);if(!jn)throw Error(`Invalid ref format: ${xn}`);let Vn=jn[1]??``,qn=this.#e.frameManager.resolveFrameIdForSnapshotPrefix(Vn);if(!qn)throw new RefStaleError(xn);let Jn=Vn?3:1;for(let jn=0;jn<Jn;jn++){jn>0&&await new Promise((xn)=>setTimeout(xn,50*jn));let Vn=this.#e.frameManager.getFrame(qn);if(!Vn||!Vn.isolatedContextId&&(await this.#e.frameManager.ensureInjected(qn),!Vn.isolatedContextId))throw new RefStaleError(xn);try{let{result:jn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(refId) { return globalThis.__omowright?.deref(refId) ?? null; }`,arguments:[{value:xn}],executionContextId:Vn.isolatedContextId,returnByValue:false,awaitPromise:false,userGesture:false},await this.#e.resolveSessionId(Vn.sessionId));if(jn.objectId)return{objectId:jn.objectId,frameId:qn,frameSessionId:Vn.sessionId,contextId:Vn.isolatedContextId}}catch{this.#e.frameManager.invalidateContext(qn)}}throw new RefStaleError(xn)}async#o(xn){let jn=this.#e.frameManager.getFrame(xn.frameId),Vn=await this.#e.frameManager.ensureInjected(xn.frameId);if(!jn||!Vn)throw Error(`File chooser element is no longer available`);let qn=await this.#e.resolveSessionId(jn.sessionId),{object:Jn}=await this.#e.cdp.send(`DOM.resolveNode`,{backendNodeId:xn.backendNodeId,executionContextId:Vn},qn);if(!Jn.objectId)throw Error(`File chooser element is no longer available`);return{objectId:Jn.objectId,frameId:xn.frameId,frameSessionId:jn.sessionId,contextId:Vn}}async#s(){let xn=await this.#u(),jn=this.#e.frameManager.getFrame(xn),Vn=await this.#e.frameManager.ensureInjected(xn);if(!jn||!Vn)throw Error(`${this.#n?.label()??`Main frame`} isolated world is not ready`);return{contextId:Vn,frameSessionId:jn.sessionId}}async#c(xn){let jn=await this.#u(),Vn=this.#e.frameManager.getFrame(jn),qn=await this.#e.frameManager.ensureInjected(jn);if(!Vn||!qn)throw Error(`${this.#n?.label()??`Main frame`} isolated world is not ready`);let Jn=this.#f(xn),{result:Yn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
|
|
964
|
-
const normalizeText = (value) => String(value ?? '').replace(/\\s+/g, ' ').trim();
|
|
965
|
-
const parseTextMatcher = (raw) => {
|
|
966
|
-
if (!raw) return null;
|
|
922
|
+
const matchesText = textMatching.matchesText;
|
|
923
|
+
// getByPlaceholder/AltText/Title/TestId match like Playwright: a RegExp tests the raw attribute value,
|
|
924
|
+
// "..."s is the whole case-sensitive value and "..."i a case-insensitive substring.
|
|
925
|
+
const parseAttributeMatcher = (raw) => {
|
|
967
926
|
if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
|
|
968
927
|
const lastSlash = raw.lastIndexOf('/');
|
|
969
928
|
return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
|
|
970
929
|
}
|
|
971
|
-
|
|
972
|
-
try {
|
|
973
|
-
return JSON.parse(value);
|
|
974
|
-
} catch {
|
|
975
|
-
return value;
|
|
976
|
-
}
|
|
977
|
-
};
|
|
978
|
-
if (raw.startsWith('exact:')) {
|
|
979
|
-
return { exact: parseLiteral(raw.slice(6)) };
|
|
980
|
-
}
|
|
981
|
-
return { contains: parseLiteral(raw) };
|
|
930
|
+
return { value: JSON.parse(raw.slice(0, -1)), exact: raw.endsWith('s') };
|
|
982
931
|
};
|
|
983
|
-
const
|
|
984
|
-
const
|
|
985
|
-
if (
|
|
986
|
-
|
|
987
|
-
|
|
932
|
+
const matchesAttribute = (node, attribute) => {
|
|
933
|
+
const value = node.getAttribute(attribute.name);
|
|
934
|
+
if (value === null) return false;
|
|
935
|
+
const matcher = attribute.matcher;
|
|
936
|
+
if (matcher instanceof RegExp) {
|
|
937
|
+
matcher.lastIndex = 0;
|
|
938
|
+
return matcher.test(value);
|
|
939
|
+
}
|
|
940
|
+
return matcher.exact ? value === matcher.value : value.toLowerCase().includes(matcher.value.toLowerCase());
|
|
988
941
|
};
|
|
989
942
|
const splitSteps = (selector) => selector.split(/\\s*>>\\s*/).map((step) => step.trim()).filter(Boolean);
|
|
990
943
|
const parseStep = (rawStep) => {
|
|
@@ -1010,6 +963,16 @@ ${qn.join(`
|
|
|
1010
963
|
nth,
|
|
1011
964
|
};
|
|
1012
965
|
}
|
|
966
|
+
const attributeMatch = base.match(/^internal:attr=\\[([^=\\]]+)=(.*)\\]$/s);
|
|
967
|
+
if (attributeMatch) {
|
|
968
|
+
return {
|
|
969
|
+
kind: 'attribute',
|
|
970
|
+
selector: '[' + CSS.escape(attributeMatch[1]) + ']',
|
|
971
|
+
attribute: { name: attributeMatch[1], matcher: parseAttributeMatcher(attributeMatch[2]) },
|
|
972
|
+
hasText,
|
|
973
|
+
nth,
|
|
974
|
+
};
|
|
975
|
+
}
|
|
1013
976
|
return {
|
|
1014
977
|
kind: 'css',
|
|
1015
978
|
selector: base,
|
|
@@ -1017,31 +980,18 @@ ${qn.join(`
|
|
|
1017
980
|
nth,
|
|
1018
981
|
};
|
|
1019
982
|
};
|
|
1020
|
-
const
|
|
983
|
+
const queryOpenShadowAll = (${queryOpenShadowAll.toString()});
|
|
984
|
+
const descendants = (root) => queryOpenShadowAll(root, '*');
|
|
1021
985
|
const textMatches = (root, matcher) => {
|
|
1022
986
|
const matches = descendants(root).filter((node) => matcher && matchesText(node, matcher));
|
|
1023
987
|
// Text selectors should resolve to the innermost visible text element,
|
|
1024
988
|
// not broad ancestors like <body>; click actionability depends on that.
|
|
1025
|
-
return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)));
|
|
989
|
+
return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)) && !(node.shadowRoot && matchesText(node.shadowRoot, matcher)));
|
|
1026
990
|
};
|
|
1027
991
|
// Keep label selectors aligned with what a human can actually click when
|
|
1028
992
|
// pages duplicate label text across hidden template controls.
|
|
1029
993
|
const labelMatches = (root, matcher) => {
|
|
1030
|
-
const
|
|
1031
|
-
.filter((label) => matcher && matchesText(label, matcher));
|
|
1032
|
-
const controlSelector = 'input:not([type="hidden"]), textarea, select';
|
|
1033
|
-
const seen = new Set();
|
|
1034
|
-
const controls = [];
|
|
1035
|
-
for (const label of labels) {
|
|
1036
|
-
const explicitControl = label.control || (label.htmlFor ? document.getElementById(label.htmlFor) : null);
|
|
1037
|
-
// Virginia DMV's Bootstrap form uses a label with no htmlFor, followed
|
|
1038
|
-
// immediately by its input in the same row.
|
|
1039
|
-
const siblingControl = label.nextElementSibling?.matches?.(controlSelector) ? label.nextElementSibling : null;
|
|
1040
|
-
const control = explicitControl || siblingControl;
|
|
1041
|
-
if (!control || seen.has(control)) continue;
|
|
1042
|
-
seen.add(control);
|
|
1043
|
-
controls.push(control);
|
|
1044
|
-
}
|
|
994
|
+
const controls = descendants(root).filter((node) => matcher && textMatching.labels(node).some((label) => textMatching.matches(label, matcher)));
|
|
1045
995
|
controls.sort((a, b) => {
|
|
1046
996
|
const rank = (node) => {
|
|
1047
997
|
let score = 0;
|
|
@@ -1060,19 +1010,21 @@ ${qn.join(`
|
|
|
1060
1010
|
});
|
|
1061
1011
|
return controls;
|
|
1062
1012
|
};
|
|
1063
|
-
const queryAll = (selector) => {
|
|
1013
|
+
const queryAll = (selector, start) => {
|
|
1064
1014
|
const steps = splitSteps(selector);
|
|
1065
|
-
let roots =
|
|
1015
|
+
let roots = start;
|
|
1066
1016
|
for (const rawStep of steps) {
|
|
1067
1017
|
const step = parseStep(rawStep);
|
|
1068
1018
|
const next = [];
|
|
1069
1019
|
const seen = new Set();
|
|
1070
1020
|
for (const root of roots) {
|
|
1071
|
-
let matches = step.kind === '
|
|
1021
|
+
let matches = step.kind === 'attribute'
|
|
1022
|
+
? queryOpenShadowAll(root, step.selector).filter((node) => matchesAttribute(node, step.attribute))
|
|
1023
|
+
: step.kind === 'text'
|
|
1072
1024
|
? textMatches(root, step.matcher)
|
|
1073
1025
|
: step.kind === 'label'
|
|
1074
1026
|
? labelMatches(root, step.matcher)
|
|
1075
|
-
:
|
|
1027
|
+
: queryOpenShadowAll(root, step.selector);
|
|
1076
1028
|
if (step.hasText) {
|
|
1077
1029
|
matches = matches.filter((node) => matchesText(node, step.hasText));
|
|
1078
1030
|
}
|
|
@@ -1090,10 +1042,11 @@ ${qn.join(`
|
|
|
1090
1042
|
}
|
|
1091
1043
|
return roots;
|
|
1092
1044
|
};
|
|
1093
|
-
const nodes = queryAll(query.selector);
|
|
1045
|
+
const nodes = queryAll(query.selector, query.scoped ? scopeRoots : [document]);
|
|
1046
|
+
if (query.countOnly) return nodes.length;
|
|
1094
1047
|
const index = query.nth === 'last' ? nodes.length - 1 : query.nth;
|
|
1095
1048
|
return nodes[index] ?? null;
|
|
1096
|
-
}`,arguments:[{value:Jn}],executionContextId:qn,returnByValue:false,awaitPromise:false,userGesture:false},await this.#e.resolveSessionId(Vn.sessionId));if(!Yn.objectId)throw Error(`Selector "${xn}" not found`);return{objectId:Yn.objectId,frameId:jn,frameSessionId:Vn.sessionId,contextId:qn}}async#l(xn){let jn=this.#p(xn),Vn=await this.#d(),{nth:qn,...Jn}=jn,Yn;if(qn===`last`){Yn=0;for(let{frameId:xn}of Vn){let jn=this.#e.frameManager.getFrame(xn);jn?.isolatedContextId&&(Yn+=await this.#m(await this.#e.resolveSessionId(jn.sessionId),jn.isolatedContextId,Jn))}--Yn}else Yn=qn;if(Yn<0)throw Error(`Role selector not found: ${xn}`);for(let{frameId:xn}of Vn){let Vn=this.#e.frameManager.getFrame(xn);if(!Vn?.isolatedContextId)continue;let qn=await this.#e.resolveSessionId(Vn.sessionId),Zn=await this.#m(qn,Vn.isolatedContextId,Jn);if(Zn<=0)continue;if(Yn>=Zn){Yn-=Zn;continue}let{result:Qn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
|
|
1049
|
+
}`,arguments:[{value:Jn},...scopeRoots.map((root)=>({objectId:root.objectId}))],executionContextId:qn,returnByValue:false,awaitPromise:false,userGesture:false},await this.#e.resolveSessionId(Vn.sessionId));if(countOnly)return Yn.value;if(!Yn.objectId)throw Error(`Selector "${xn}" not found`);return{objectId:Yn.objectId,frameId:jn,frameSessionId:Vn.sessionId,contextId:qn}}async#l(xn){let jn=this.#p(xn),Vn=await this.#d(),{nth:qn,...Jn}=jn,Yn;if(qn===`last`){Yn=0;for(let{frameId:xn}of Vn){let jn=this.#e.frameManager.getFrame(xn);jn?.isolatedContextId&&(Yn+=await this.#m(await this.#e.resolveSessionId(jn.sessionId),jn.isolatedContextId,Jn))}--Yn}else Yn=qn;if(Yn<0)throw Error(`Role selector not found: ${xn}`);for(let{frameId:xn}of Vn){let Vn=this.#e.frameManager.getFrame(xn);if(!Vn?.isolatedContextId)continue;let qn=await this.#e.resolveSessionId(Vn.sessionId),Zn=await this.#m(qn,Vn.isolatedContextId,Jn);if(Zn<=0)continue;if(Yn>=Zn){Yn-=Zn;continue}let{result:Qn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
|
|
1097
1050
|
const normalizeText = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
|
|
1098
1051
|
const getRole = (node) => {
|
|
1099
1052
|
const explicit = node.getAttribute?.('role');
|
|
@@ -1120,51 +1073,11 @@ ${qn.join(`
|
|
|
1120
1073
|
return 'generic';
|
|
1121
1074
|
};
|
|
1122
1075
|
|
|
1123
|
-
const
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
if (labelledBy) {
|
|
1129
|
-
const labelText = labelledBy
|
|
1130
|
-
.split(/\\s+/)
|
|
1131
|
-
.map((id) => normalizeText(node.ownerDocument?.getElementById(id)?.textContent))
|
|
1132
|
-
.filter(Boolean)
|
|
1133
|
-
.join(' ');
|
|
1134
|
-
if (labelText) return labelText;
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
if (typeof node.labels?.length === 'number' && node.labels.length > 0) {
|
|
1138
|
-
const labelText = Array.from(node.labels)
|
|
1139
|
-
.map((label) => normalizeText(label.textContent))
|
|
1140
|
-
.filter(Boolean)
|
|
1141
|
-
.join(' ');
|
|
1142
|
-
if (labelText) return labelText;
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
const title = normalizeText(node.getAttribute?.('title'));
|
|
1146
|
-
if (title) return title;
|
|
1147
|
-
|
|
1148
|
-
const alt = normalizeText(node.getAttribute?.('alt'));
|
|
1149
|
-
if (alt) return alt;
|
|
1150
|
-
|
|
1151
|
-
const placeholder = normalizeText(node.getAttribute?.('placeholder'));
|
|
1152
|
-
if (placeholder) return placeholder;
|
|
1153
|
-
|
|
1154
|
-
const value = normalizeText(node.value);
|
|
1155
|
-
if (value) return value;
|
|
1156
|
-
|
|
1157
|
-
return normalizeText(node.textContent).slice(0, 100);
|
|
1158
|
-
};
|
|
1159
|
-
|
|
1160
|
-
const isHidden = (node) => {
|
|
1161
|
-
if (!node.isConnected) return true;
|
|
1162
|
-
if (node.getAttribute?.('hidden') !== null) return true;
|
|
1163
|
-
if (node.getAttribute?.('aria-hidden') === 'true') return true;
|
|
1164
|
-
const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
|
|
1165
|
-
if (!style) return false;
|
|
1166
|
-
return style.display === 'none' || style.visibility === 'hidden';
|
|
1167
|
-
};
|
|
1076
|
+
const isElementHiddenForAria = (${isElementHiddenForAria.toString()});
|
|
1077
|
+
const ariaHiddenCache = new Map();
|
|
1078
|
+
const isHidden = (node) => isElementHiddenForAria(node, ariaHiddenCache);
|
|
1079
|
+
const textMatching = (${createTextMatching.toString()})(isHidden, getRole, query.includeHidden === true);
|
|
1080
|
+
const getAccessibleName = textMatching.accessibleName;
|
|
1168
1081
|
|
|
1169
1082
|
const getAriaBoolean = (value) => {
|
|
1170
1083
|
if (value === 'true') return true;
|
|
@@ -1225,7 +1138,7 @@ ${qn.join(`
|
|
|
1225
1138
|
if (query.name === undefined) {
|
|
1226
1139
|
return true;
|
|
1227
1140
|
}
|
|
1228
|
-
return query.exact ?
|
|
1141
|
+
return textMatching.matches(name, query.exact ? { exact: query.name } : { contains: query.name });
|
|
1229
1142
|
};
|
|
1230
1143
|
|
|
1231
1144
|
const matchesState = (node) => {
|
|
@@ -1253,26 +1166,18 @@ ${qn.join(`
|
|
|
1253
1166
|
return true;
|
|
1254
1167
|
};
|
|
1255
1168
|
|
|
1256
|
-
const root = document.documentElement || document.body;
|
|
1257
|
-
if (!root) {
|
|
1258
|
-
return null;
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
1169
|
const matches = [];
|
|
1262
|
-
const
|
|
1263
|
-
let current = root;
|
|
1264
|
-
while (current) {
|
|
1170
|
+
for (const current of (${queryOpenShadowAll.toString()})(document, '*')) {
|
|
1265
1171
|
if (matchesState(current) && getRole(current) === query.role) {
|
|
1266
1172
|
const name = getAccessibleName(current);
|
|
1267
1173
|
if (nameMatches(name)) {
|
|
1268
1174
|
matches.push(current);
|
|
1269
1175
|
}
|
|
1270
1176
|
}
|
|
1271
|
-
current = walker.nextNode();
|
|
1272
1177
|
}
|
|
1273
1178
|
|
|
1274
1179
|
return matches[query.nth] ?? null;
|
|
1275
|
-
}`,arguments:[{value:{...jn,nth:Yn}}],executionContextId:Vn.isolatedContextId,returnByValue:false,awaitPromise:false,userGesture:false},qn);if(Qn.objectId)return{objectId:Qn.objectId,frameId:xn,frameSessionId:Vn.sessionId,contextId:Vn.isolatedContextId}}throw Error(`Role selector not found: ${xn}`)}async#u(){return this.#n?await this.#n.resolveFrameId():this.#e.frameManager.mainFrameId}async#d(){if(this.#n){let xn=await this.#n.resolveFrameId(),jn=this.#e.frameManager.getFrame(xn);return jn?[{frameId:xn,parentFrameId:jn.parentFrameId,depth:0}]:[]}return this.#e.frameManager.collectDescendantFrames(this.#e.frameManager.mainFrameId)}#f(xn){let jn=xn.match(/^(.*):nth\((\d+|last)\)$/);if(!jn)return{selector:xn,nth:0};let Vn=jn[2];return{selector:jn[1].trim(),nth:Vn===`last`?`last`:Number.parseInt(Vn,10)}}#p(xn){let jn=xn.match(NTH_SELECTOR_PATTERN),Vn=jn?.[1],qn=Vn===`last`?`last`:Vn?Number.parseInt(Vn,10):0,Jn=jn?xn.slice(0,jn.index):xn,Yn=Jn.match(/^role:([^[]+)/);if(!Yn)throw Error(`Invalid role selector: ${xn}`);let Zn={role:Yn[1].trim(),nth:qn},Qn=Jn.slice(Yn[0].length),ei=/\[([a-z-]+)(\*?)=(.*?)\]/g,ti;for(;ti=ei.exec(Qn);){let[,xn,jn,Vn]=ti,qn=xn,Jn=Vn.trim();if(qn===`name-regex`){Zn.regexSource=decodeURIComponent(Jn);continue}if(qn===`name-regex-flags`){Zn.regexFlags=decodeURIComponent(Jn);continue}if(qn===`name`){Zn.name=decodeURIComponent(Jn),Zn.exact=jn!==`*`;continue}qn===`checked`&&(Zn.checked=Jn===`true`),qn===`disabled`&&(Zn.disabled=Jn===`true`),qn===`expanded`&&(Zn.expanded=Jn===`true`),qn===`include-hidden`&&(Zn.includeHidden=Jn===`true`),qn===`level`&&(Zn.level=Number.parseInt(Jn,10)),qn===`pressed`&&(Zn.pressed=Jn===`true`),qn===`selected`&&(Zn.selected=Jn===`true`)}return Zn}async#m(xn,jn,Vn){let{result:qn,exceptionDetails:Jn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
|
|
1180
|
+
}`,arguments:[{value:{...jn,nth:Yn}}],executionContextId:Vn.isolatedContextId,returnByValue:false,awaitPromise:false,userGesture:false},qn);if(Qn.objectId)return{objectId:Qn.objectId,frameId:xn,frameSessionId:Vn.sessionId,contextId:Vn.isolatedContextId}}throw Error(`Role selector not found: ${xn}`)}async#u(){return this.#n?await this.#n.resolveFrameId():this.#e.frameManager.mainFrameId}async#d(){if(this.#n){let xn=await this.#n.resolveFrameId(),jn=this.#e.frameManager.getFrame(xn);return jn?[{frameId:xn,parentFrameId:jn.parentFrameId,depth:0}]:[]}return this.#e.frameManager.collectDescendantFrames(this.#e.frameManager.mainFrameId)}#f(xn){let jn=xn.match(/^(.*):nth\((\d+|last)\)$/);if(!jn)return{selector:xn,nth:0};let Vn=definedOrThrow(jn[2]);return{selector:definedOrThrow(jn[1]).trim(),nth:Vn===`last`?`last`:Number.parseInt(Vn,10)}}#p(xn){let jn=xn.match(NTH_SELECTOR_PATTERN),Vn=jn?.[1],qn=Vn===`last`?`last`:Vn?Number.parseInt(Vn,10):0,Jn=jn?xn.slice(0,jn.index):xn,Yn=Jn.match(/^role:([^[]+)/);if(!Yn)throw Error(`Invalid role selector: ${xn}`);let Zn={role:definedOrThrow(Yn[1]).trim(),nth:qn},Qn=Jn.slice(Yn[0].length),ei=/\[([a-z-]+)(\*?)=(.*?)\]/g,ti;for(;ti=ei.exec(Qn);){let[,xn,jn,Vn]=ti,qn=xn,Jn=definedOrThrow(Vn).trim();if(qn===`name-regex`){Zn.regexSource=decodeURIComponent(Jn);continue}if(qn===`name-regex-flags`){Zn.regexFlags=decodeURIComponent(Jn);continue}if(qn===`name`){Zn.name=decodeURIComponent(Jn),Zn.exact=jn!==`*`;continue}qn===`checked`&&(Zn.checked=Jn===`true`),qn===`disabled`&&(Zn.disabled=Jn===`true`),qn===`expanded`&&(Zn.expanded=Jn===`true`),qn===`include-hidden`&&(Zn.includeHidden=Jn===`true`),qn===`level`&&(Zn.level=Number.parseInt(Jn,10)),qn===`pressed`&&(Zn.pressed=Jn===`true`),qn===`selected`&&(Zn.selected=Jn===`true`)}return Zn}async#m(xn,jn,Vn){let{result:qn,exceptionDetails:Jn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
|
|
1276
1181
|
const normalizeText = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
|
|
1277
1182
|
const getRole = (node) => {
|
|
1278
1183
|
const explicit = node.getAttribute?.('role');
|
|
@@ -1299,51 +1204,11 @@ ${qn.join(`
|
|
|
1299
1204
|
return 'generic';
|
|
1300
1205
|
};
|
|
1301
1206
|
|
|
1302
|
-
const
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
if (labelledBy) {
|
|
1308
|
-
const labelText = labelledBy
|
|
1309
|
-
.split(/\\s+/)
|
|
1310
|
-
.map((id) => normalizeText(node.ownerDocument?.getElementById(id)?.textContent))
|
|
1311
|
-
.filter(Boolean)
|
|
1312
|
-
.join(' ');
|
|
1313
|
-
if (labelText) return labelText;
|
|
1314
|
-
}
|
|
1315
|
-
|
|
1316
|
-
if (typeof node.labels?.length === 'number' && node.labels.length > 0) {
|
|
1317
|
-
const labelText = Array.from(node.labels)
|
|
1318
|
-
.map((label) => normalizeText(label.textContent))
|
|
1319
|
-
.filter(Boolean)
|
|
1320
|
-
.join(' ');
|
|
1321
|
-
if (labelText) return labelText;
|
|
1322
|
-
}
|
|
1323
|
-
|
|
1324
|
-
const title = normalizeText(node.getAttribute?.('title'));
|
|
1325
|
-
if (title) return title;
|
|
1326
|
-
|
|
1327
|
-
const alt = normalizeText(node.getAttribute?.('alt'));
|
|
1328
|
-
if (alt) return alt;
|
|
1329
|
-
|
|
1330
|
-
const placeholder = normalizeText(node.getAttribute?.('placeholder'));
|
|
1331
|
-
if (placeholder) return placeholder;
|
|
1332
|
-
|
|
1333
|
-
const value = normalizeText(node.value);
|
|
1334
|
-
if (value) return value;
|
|
1335
|
-
|
|
1336
|
-
return normalizeText(node.textContent).slice(0, 100);
|
|
1337
|
-
};
|
|
1338
|
-
|
|
1339
|
-
const isHidden = (node) => {
|
|
1340
|
-
if (!node.isConnected) return true;
|
|
1341
|
-
if (node.getAttribute?.('hidden') !== null) return true;
|
|
1342
|
-
if (node.getAttribute?.('aria-hidden') === 'true') return true;
|
|
1343
|
-
const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
|
|
1344
|
-
if (!style) return false;
|
|
1345
|
-
return style.display === 'none' || style.visibility === 'hidden';
|
|
1346
|
-
};
|
|
1207
|
+
const isElementHiddenForAria = (${isElementHiddenForAria.toString()});
|
|
1208
|
+
const ariaHiddenCache = new Map();
|
|
1209
|
+
const isHidden = (node) => isElementHiddenForAria(node, ariaHiddenCache);
|
|
1210
|
+
const textMatching = (${createTextMatching.toString()})(isHidden, getRole, query.includeHidden === true);
|
|
1211
|
+
const getAccessibleName = textMatching.accessibleName;
|
|
1347
1212
|
|
|
1348
1213
|
const getAriaBoolean = (value) => {
|
|
1349
1214
|
if (value === 'true') return true;
|
|
@@ -1404,7 +1269,7 @@ ${qn.join(`
|
|
|
1404
1269
|
if (query.name === undefined) {
|
|
1405
1270
|
return true;
|
|
1406
1271
|
}
|
|
1407
|
-
return query.exact ?
|
|
1272
|
+
return textMatching.matches(name, query.exact ? { exact: query.name } : { contains: query.name });
|
|
1408
1273
|
};
|
|
1409
1274
|
|
|
1410
1275
|
const matchesState = (node) => {
|
|
@@ -1432,48 +1297,47 @@ ${qn.join(`
|
|
|
1432
1297
|
return true;
|
|
1433
1298
|
};
|
|
1434
1299
|
|
|
1435
|
-
const root = document.documentElement || document.body;
|
|
1436
|
-
if (!root) {
|
|
1437
|
-
return 0;
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
1300
|
let count = 0;
|
|
1441
|
-
const
|
|
1442
|
-
let current = root;
|
|
1443
|
-
while (current) {
|
|
1301
|
+
for (const current of (${queryOpenShadowAll.toString()})(document, '*')) {
|
|
1444
1302
|
if (matchesState(current) && getRole(current) === query.role) {
|
|
1445
1303
|
const name = getAccessibleName(current);
|
|
1446
1304
|
if (nameMatches(name)) {
|
|
1447
1305
|
count += 1;
|
|
1448
1306
|
}
|
|
1449
1307
|
}
|
|
1450
|
-
current = walker.nextNode();
|
|
1451
1308
|
}
|
|
1452
1309
|
|
|
1453
1310
|
return count;
|
|
1454
|
-
}`,arguments:[{value:Vn}],executionContextId:jn,returnByValue:true,awaitPromise:false,userGesture:false},xn);if(Jn)throw Error(Jn.text??`Role selector count failed`);return Number(qn.value??0)}}
|
|
1311
|
+
}`,arguments:[{value:Vn}],executionContextId:jn,returnByValue:true,awaitPromise:false,userGesture:false},xn);if(Jn)throw Error(Jn.text??`Role selector count failed`);return Number(qn.value??0)}}}function createElementHandleClass(){return class ElementHandle{#e;#t;constructor(xn,jn){this.#e=xn,this.#t=jn}async contentFrame(){let{node:xn}=await this.#e.cdp.send(`DOM.describeNode`,{objectId:this.#t.objectId,depth:0},await this.#e.resolveSessionId(this.#t.frameSessionId));if(!xn.frameId||!this.#e.frameManager.getFrame(xn.frameId))return null;let{OmOFrame:jn}=await Promise.resolve().then(()=>(init_frame(),frame_exports));return new jn(this.#e,xn.frameId)}}}function createFileChooserClass(){return class FileChooser{page;#e;#t;#n;#r=null;constructor(xn,jn,Vn,qn){this.page=xn,this.#e=jn,this.#t=Vn,this.#n=qn}element(){return this.#r??=new Locator(this.page,createBackendNodeLocatorSelector(this.#e,this.#t)),this.#r}isMultiple(){return this.#n}async setFiles(xn){await this.element().setInputFiles(Array.isArray(xn)||typeof xn==`string`?xn:[xn])}}}function createOmOMouseClass(){return class OmOMouse{context;modifierState;#e=0;#t=0;#n=`none`;constructor(xn,jn){this.context=xn,this.modifierState=jn}async move(xn,jn,Vn={}){let qn=this.#e,Jn=this.#t,Yn=Math.max(Vn.steps??1,1),Zn=this.modifierState.toButtonsMask(),Qn=await shouldUseDomInputFallback(this.context);for(let Vn=1;Vn<=Yn;Vn+=1){let ei=qn+(xn-qn)*(Vn/Yn),ti=Jn+(jn-Jn)*(Vn/Yn);if(Qn){await this.#i(`move`,{x:ei,y:ti,button:this.#n,buttons:Zn});continue}await this.#r(`mouseMoved`,{x:ei,y:ti,button:this.#n,buttons:Zn,modifiers:this.modifierState.toModifiersMask(),force:Zn>0?0.5:0})}this.#e=xn,this.#t=jn}async down(xn={}){let jn=xn.button??`left`,Vn=xn.clickCount??1;if(this.#n=jn,this.modifierState.mouseDown(jn),await shouldUseDomInputFallback(this.context)){await this.#i(`down`,{x:this.#e,y:this.#t,button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn});return}await this.#r(`mousePressed`,{button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn,modifiers:this.modifierState.toModifiersMask(),force:this.modifierState.toButtonsMask()>0?0.5:0})}async up(xn={}){let jn=xn.button??`left`,Vn=xn.clickCount??1;if(this.#n=`none`,this.modifierState.mouseUp(jn),await shouldUseDomInputFallback(this.context)){await this.#i(`up`,{x:this.#e,y:this.#t,button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn});return}await this.#r(`mouseReleased`,{button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn,modifiers:this.modifierState.toModifiersMask()})}async click(xn,jn,Vn={}){let qn=Vn.button??`left`,Jn=Vn.clickCount??1,Yn=Vn.delay??0;await this.move(xn,jn,{steps:Vn.steps}),await this.context.prepareForPotentialFileChooser?.();for(let xn=1;xn<=Jn;xn+=1)await this.down({button:qn,clickCount:xn}),Yn>0&&await sleep$12(Yn),await this.up({button:qn,clickCount:xn}),Yn>0&&xn<Jn&&await sleep$12(Yn)}async dblclick(xn,jn,Vn={}){await this.click(xn,jn,{button:Vn.button??`left`,clickCount:2,delay:Vn.delay??0,steps:Vn.steps})}async wheel(xn,jn){if(await shouldUseDomInputFallback(this.context)){await this.#i(`wheel`,{x:this.#e,y:this.#t,deltaX:xn,deltaY:jn});return}await this.#r(`mouseWheel`,{deltaX:xn,deltaY:jn,modifiers:this.modifierState.toModifiersMask()})}async#r(xn,jn){await this.context._sendToTarget(`Input.dispatchMouseEvent`,{type:xn,x:Math.floor(jn.x??this.#e),y:Math.floor(jn.y??this.#t),button:jn.button,buttons:jn.buttons,clickCount:jn.clickCount,deltaX:jn.deltaX,deltaY:jn.deltaY,force:jn.force,modifiers:jn.modifiers??this.modifierState.toModifiersMask()})}async#i(xn,jn){await this.context.evaluate((xn)=>{let{eventType:jn,x:Vn,y:qn,button:Jn,buttons:Yn,clickCount:Zn,deltaX:Qn,deltaY:ei}=xn,ti=document.elementFromPoint(Vn,qn)??document.scrollingElement??document.documentElement??document.body,ni=Jn===`right`?2:+(Jn===`middle`);if(jn===`wheel`){ti.dispatchEvent(new WheelEvent(`wheel`,{clientX:Vn,clientY:qn,deltaX:Qn??0,deltaY:ei??0,bubbles:true,cancelable:true,composed:true})),window.scrollBy(Qn??0,ei??0);return}let ri=jn===`move`?`mousemove`:jn===`down`?`mousedown`:`mouseup`;ti.dispatchEvent(new MouseEvent(ri,{clientX:Vn,clientY:qn,button:ni,buttons:Yn??0,detail:Zn??0,bubbles:true,cancelable:true,composed:true,view:window})),jn===`up`&&(ti.dispatchEvent(new MouseEvent(`click`,{clientX:Vn,clientY:qn,button:ni,buttons:Yn??0,detail:Zn??1,bubbles:true,cancelable:true,composed:true,view:window})),(Zn??0)===2&&ti.dispatchEvent(new MouseEvent(`dblclick`,{clientX:Vn,clientY:qn,button:ni,buttons:Yn??0,detail:2,bubbles:true,cancelable:true,composed:true,view:window})))},{eventType:xn,...jn})}}}var REF_PATTERN;var REF_SELECTOR_ALIAS_PATTERN;var BACKEND_NODE_SELECTOR_PREFIX;var DEFAULT_SCREENSHOT_MARGIN;var DEFAULT_LOCATOR_WAIT_TIMEOUT_MS;var LOCATOR_WAIT_POLL_INTERVALS;var LOCATOR_WAIT_STATES;var NTH_SELECTOR_PATTERN;var isRef2;var isRoleSelector;var Locator;var ElementHandle;var init_locator=__esmMin(()=>{init_utils$13(),init_errors$3(),init_types$4(),init_actions(),REF_PATTERN=/^(f\d+)?e\d+$/,REF_SELECTOR_ALIAS_PATTERN=/^\[ref=((?:f\d+)?e\d+)\]$/,BACKEND_NODE_SELECTOR_PREFIX=`internal:backend-node-id:`,DEFAULT_SCREENSHOT_MARGIN=8,DEFAULT_LOCATOR_WAIT_TIMEOUT_MS=3000,LOCATOR_WAIT_POLL_INTERVALS=[0,20,50,100,100,500],LOCATOR_WAIT_STATES=[`attached`,`detached`,`visible`,`hidden`],NTH_SELECTOR_PATTERN=/:nth\((\d+|last)\)$/,isRef2=(xn)=>/^(f\d+)?e\d+$/.test(xn),isRoleSelector=(xn)=>xn.startsWith(`role:`),Locator=createLocatorClass(),ElementHandle=createElementHandleClass()});var FileChooser;var init_file_chooser=__esmMin(()=>{init_locator(),FileChooser=createFileChooserClass()});var OmOMouse;var init_mouse=__esmMin(()=>{init_utils$13(),init_keyboard(),OmOMouse=createOmOMouseClass()});var PASSWORD_MANAGER_EXTENSION_ID;var PASSWORD_MANAGER_EXTENSION_ORIGIN;var init_extension_ids=__esmMin(()=>{PASSWORD_MANAGER_EXTENSION_ID=`clcdgiameigmljcbkkcbjiljinmfkncl`,PASSWORD_MANAGER_EXTENSION_ORIGIN=`chrome-extension://${PASSWORD_MANAGER_EXTENSION_ID}`});function getKnownIframeOriginLabel(xn){return KNOWN_IFRAME_ORIGINS.find(({urlPrefix:jn})=>xn.startsWith(jn))?.label??null}function formatIframeOriginLabel(xn){return xn?` [origin="${xn.replace(/"/g,`\\"`)}"]`:``}function tagIframeLine(xn,jn,Vn){return xn.split(`
|
|
1455
1312
|
`).map((xn)=>{let qn=xn.match(/^(\s*)- iframe(?:.*? )?\[ref=([^\]]*)\]/);return!qn||qn[2]!==jn||xn.includes(` [origin=`)?xn:xn.replace(/^(\s*)- iframe/,`$1- iframe${formatIframeOriginLabel(Vn)}`)}).join(`
|
|
1456
1313
|
`)}function getCdpNodeAttribute(xn,jn){if(!xn)return null;for(let Vn=0;Vn<xn.length;Vn+=2)if(xn[Vn]===jn)return xn[Vn+1]??``;return null}function inlineChildTree(xn,jn,Vn){return xn.split(`
|
|
1457
1314
|
`).flatMap((xn)=>{let qn=xn.match(/^(\s*)- iframe(?:.*? )?\[ref=([^\]]*)\]/);if(!qn||qn[2]!==jn)return[xn];let Jn=qn[1]??``,Yn=Vn.split(`
|
|
1458
|
-
`).map((xn)=>`${Jn} ${xn}`);
|
|
1315
|
+
`).map((xn)=>`${Jn} ${xn}`);Yn.unshift(Vn.length>0?`${xn}:`:xn);return Yn}).join(`
|
|
1459
1316
|
`)}function appendOrphanChildTree(xn,jn,Vn){if(!jn)return xn;let qn=jn.split(`
|
|
1460
1317
|
`).map((xn)=>` ${xn}`);return`${xn}
|
|
1461
1318
|
- iframe${formatIframeOriginLabel(Vn)}:
|
|
1462
1319
|
${qn.join(`
|
|
1463
|
-
`)}`}function getRefPrefix(xn){return xn.match(/^(f\d+)?e\d+$/)?.[1]??``}async function takeSnapshot(xn,jn,Vn={}){let qn=jn.mainFrameId,Jn=jn.collectDescendantFrames(qn),Yn=new Map,Zn=new Map,Qn=1;for(let xn of Jn){let jn=xn.frameId===qn?``:`f${Qn++}`;Yn.set(xn.frameId,jn),Zn.set(jn,xn.frameId)}jn.setSnapshotFramePrefixMap(Zn);let ei=(()=>{if(!Vn.ref)return qn;let xn=getRefPrefix(Vn.ref);return Jn.find(({frameId:jn})=>(Yn.get(jn)??``)===xn)?.frameId??null})();if(!ei)throw Error(`Ref "${Vn.ref}" points to a frame that is no longer available. Take a new snapshot.`);let ti=jn.collectDescendantFrames(ei),ni=new Map,ri;await Promise.all(ti.map(async({frameId:qn})=>{let Jn=qn===ei,Zn=Jn?SNAPSHOT_MAX_RETRIES:1,Qn;for(let ti=0;ti<Zn;ti++){ti>0&&await sleep$12(SNAPSHOT_RETRY_DELAY_MS);let ii=await jn.ensureInjected(qn).catch((xn)=>(Qn=xn,null));if(!ii){if(Jn&&ti<Zn-1)continue;Jn&&(ri=Qn);return}let ai={interactive:Vn.interactive,maxDepth:Vn.maxDepth,maxChars:Vn.maxChars,refId:qn===ei?Vn.ref:undefined,selector:qn===ei?Vn.selector:undefined,showHidden:Vn.showHidden,refPrefix:Yn.get(qn)??``};try{let{result:Vn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(opts) {
|
|
1320
|
+
`)}`}function getRefPrefix(xn){return xn.match(/^(f\d+)?e\d+$/)?.[1]??``}async function takeSnapshot(xn,jn,Vn={}){validateSnapshotOptions(Vn);let qn=jn.mainFrameId,Jn=jn.collectDescendantFrames(qn),Yn=new Map,Zn=new Map,Qn=1;for(let xn of Jn){let jn=xn.frameId===qn?``:`f${Qn++}`;Yn.set(xn.frameId,jn),Zn.set(jn,xn.frameId)}jn.setSnapshotFramePrefixMap(Zn);let ei=(()=>{if(!Vn.ref)return qn;let xn=getRefPrefix(Vn.ref);return Jn.find(({frameId:jn})=>(Yn.get(jn)??``)===xn)?.frameId??null})();if(!ei)throw Error(`Ref "${Vn.ref}" points to a frame that is no longer available. Take a new snapshot.`);let ti=jn.collectDescendantFrames(ei),ni=new Map,ri;await Promise.all(ti.map(async({frameId:qn})=>{let Jn=qn===ei,Zn=Jn?SNAPSHOT_MAX_RETRIES:1,Qn;for(let ti=0;ti<Zn;ti++){ti>0&&await sleep$12(SNAPSHOT_RETRY_DELAY_MS);let ii=await jn.ensureInjected(qn).catch((xn)=>(Qn=xn,null));if(!ii){if(Jn&&ti<Zn-1)continue;Jn&&(ri=Qn);return}let ai={interactive:Vn.interactive,maxDepth:Vn.maxDepth,maxChars:Vn.maxChars,refId:qn===ei?Vn.ref:undefined,selector:qn===ei?Vn.selector:undefined,showHidden:Vn.showHidden,refPrefix:Yn.get(qn)??``};try{let{result:Vn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(opts) {
|
|
1464
1321
|
return globalThis.__omowright.takeSnapshot(opts);
|
|
1465
|
-
}`,arguments:[{value:ai}],executionContextId:ii,returnByValue:true,awaitPromise:false,userGesture:false},jn.getFrame(qn)?.sessionId),Yn=Vn.value;if(Yn){if(Yn.error){Jn&&(ri=Yn.error);return}ni.set(qn,Yn);return}}catch(xn){Qn=xn,isContextDestroyedError(xn)&&jn.invalidateContext(qn)}Jn&&Zn-1}Jn&&(ri=Qn)}));let ii=ni.get(ei);if(!ii){let xn=ri;throw xn instanceof Error?xn:typeof xn==`string`&&xn.length>0?Error(xn):Error(ei===qn?`Main frame snapshot failed`:`Ref subtree snapshot failed`)}let ai=new Map,oi=new Map;await Promise.all(ti.map(async({frameId:Vn})=>{let qn=ni.get(Vn),Jn=jn.getFrame(Vn);if(!qn||!Jn?.isolatedContextId)return;let Yn=Object.entries(qn.refs).filter(([,xn])=>xn.tagName.toLowerCase()===`iframe`).map(([xn])=>xn);if(Yn.length===0)return;let Zn=await Promise.all(Yn.map(async(qn)=>{let{result:Yn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(ref) {
|
|
1322
|
+
}`,arguments:[{value:ai}],executionContextId:ii,returnByValue:true,awaitPromise:false,userGesture:false},jn.getFrame(qn)?.sessionId),Yn=pageResult(Vn.value);if(Yn){if(Yn.error){Jn&&(ri=Yn.error);return}ni.set(qn,Yn);return}}catch(xn){Qn=xn,isContextDestroyedError(xn)&&jn.invalidateContext(qn)}Jn&&Zn-1}Jn&&(ri=Qn)}));let ii=ni.get(ei);if(!ii){let xn=ri;throw xn instanceof Error?xn:typeof xn==`string`&&xn.length>0?Error(xn):Error(ei===qn?`Main frame snapshot failed`:`Ref subtree snapshot failed`)}let ai=new Map,oi=new Map;await Promise.all(ti.map(async({frameId:Vn})=>{let qn=ni.get(Vn),Jn=jn.getFrame(Vn);if(!qn||!Jn?.isolatedContextId)return;let Yn=Object.entries(qn.refs).filter(([,xn])=>xn.tagName.toLowerCase()===`iframe`).map(([xn])=>xn);if(Yn.length===0)return;let Zn=await Promise.all(Yn.map(async(qn)=>{let{result:Yn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(ref) {
|
|
1466
1323
|
return globalThis.__omowright.elementRegistry.get(ref);
|
|
1467
|
-
}`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].sort((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return{tree:ii.tree,refs:ci}}var KNOWN_IFRAME_ORIGINS;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var init_snapshot=__esmMin(()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3});var formatRange;var init_diff=__esmMin(()=>{formatRange=(xn,jn)=>jn===1?String(xn):`${xn},${jn}`});var init_session_tab_queries=__esmMin(()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()});var ANNOTATION_OVERLAY_ID;var init_annotate_screenshot=__esmMin(()=>{ANNOTATION_OVERLAY_ID=`__omowright_annotations__`});var AI_TAB_STABLE_VIEWPORT;var MIN_STABLE_AI_TAB_VIEWPORT;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_diff(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),AI_TAB_STABLE_VIEWPORT={width:1440,height:900},MIN_STABLE_AI_TAB_VIEWPORT={width:960,height:540}});function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return await readProcessStream(xn.stderr).catch(()=>``)}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var init_video=__esmMin(()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=class{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}writeFrame(xn,jn){if(this.#r)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c())}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){if(this.#r)return;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}},OmOVideo=class{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn),{promise:ti,resolve:ni,reject:ri}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1000;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:ri,resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,ri(xn),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion(qn)}catch(xn){throw jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn),await this.#t.completion;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:undefined,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==undefined){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===undefined?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==undefined)return typeof xn==`number`?`${xn}px`:xn}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var init_page=__esmMin(()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=class{cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){let xn=new Set,jn=(xn)=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,(xn)=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#u(`Page.javascriptDialogOpening`,(xn)=>{this.events.emit(`dialog`,{type:xn.type,message:xn.message,defaultPrompt:xn.defaultPrompt??``,url:xn.url}).catch(jn)}),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,(xn)=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,(xn)=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,(xn)=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=(Vn)=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,(xn)=>Vn(xn))),this.#u(`Page.downloadWillBegin`,(xn)=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||this.events.emit(`popup`,{url:xn.url,windowName:xn.windowName}).catch(jn)})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn));return Vn.set(jn,qn),this.#e.set(xn,Vn),xn===`filechooser`&&this.#m(),()=>{qn(),Vn.delete(jn),xn===`filechooser`&&this.#h()}}off(xn,jn){let Vn=this.#e.get(xn),qn=Vn?.get(jn);qn?.(),Vn?.delete(jn),qn&&xn===`filechooser`&&this.#h()}async waitForEvent(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,Qn(),xn())},ti=(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,Qn=()=>{ni(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then((xn)=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()})})}#d(){for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map((jn)=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return}try{await Yn}catch(xn){if(await this.#_())return;throw xn}return}Yn&&await Yn}async goBack(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex-1;if(jn<0)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async goForward(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex+1;if(jn>=xn.entries.length)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async reload(){let xn=this.#C();await this._sendToTarget(`Page.reload`),await xn}async waitForLoadState(xn=`interactive`,jn=DEFAULT_WAIT_TIMEOUT_MS){if(xn===`interactive`||xn===`stable`){await waitForNavigationReadiness(this,xn,jn);return}if(xn===`networkidle`||xn===`load`){replPrint(`[system] this is redundant wait; openTab() already waits for the page to become usable. Falling back to 'stable' with 5s timeout.`),await waitForNavigationReadiness(this,`stable`,5000).catch(()=>{});return}if(await this.#_())return;let Vn=`Page.domContentEventFired`,qn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let Jn=setTimeout(()=>{Yn(),Vn(Error(`Timed out waiting for load state "${xn}"`))},DEFAULT_WAIT_TIMEOUT_MS),Yn=this.cdp.on(`Page.domContentEventFired`,(xn,Vn)=>{Vn.sessionId===qn&&(clearTimeout(Jn),Yn(),jn())})})}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS,qn=Date.now();for(;Date.now()-qn<Vn;){let jn=this.url();if(typeof xn==`string`?jn===xn:xn.test(jn))return;await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(xn)}`)}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate((xn)=>{let jn=document.querySelector(xn);if(!jn)return{attached:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===undefined){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute);let xn=new URL(this.#r).origin,jn=this.browser.daemonSession;upsertNotificationGrant({accountId:jn.accountId,origin:xn,grantedBySessionId:jn.id})}url({truncate:xn=false}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:undefined,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}
|
|
1468
|
-
Viewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path.join(jn,path.basename(xn.path));await mkdir(path.dirname(Vn),{recursive:true}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path.dirname(jn),{recursive:true}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):undefined,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,undefined,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){await this._sendToTarget(`Network.enable`).catch(()=>{});let jn=await this.resolveSessionId(this.#n);await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=(xn)=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#C(){let xn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let qn=setTimeout(()=>{Jn(),Vn(Error(`Timed out waiting for navigation`))},DEFAULT_WAIT_TIMEOUT_MS),Jn=this.cdp.on(`Page.frameNavigated`,(Vn,Yn)=>{Yn.sessionId===xn&&(Vn.frame.parentId||(clearTimeout(qn),Jn(),jn()))})})}async _sendToTarget(xn,jn,Vn={}){if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==undefined){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}});init_client$6();init_session_manager();init_frame_manager();init_page();import{isDeepStrictEqual}from"node:util";var shared=new Map;function withinTimeout(pending,timeoutMs,message){let timer;return Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeoutMs)})]).finally(()=>clearTimeout(timer))}function release(key,entry){entry.refs-=1;if(entry.refs>0)return Promise.resolve();if(shared.get(key)===entry)shared.delete(key);return entry.ready.then((connection)=>connection.close(),()=>{})}function bindTo(target,value){return typeof value==="function"?value.bind(target):value}class SharedConnectionError extends Error{constructor(){super("this browser connection is shared; pass dialogPolicy to connect()/connectNamed() so this holder gets its own connection");this.name="SharedConnectionError";this.code="shared_connection"}}var RESERVED=new Set(["cdp","close","setDialogPolicy"]);function refuse(what){return(_target,property)=>{throw new TypeError(`cannot change ${String(property)} on ${what} through a handle: every holder of this connection uses it`)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=[];const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){for(const unsubscribe of subscriptions.splice(0))unsubscribe();closed=release(key,entry)}return closed};const setDialogPolicy=(policy)=>{ensureOpen("setDialogPolicy");if(entry.refs>1)throw new SharedConnectionError;if(shared.get(key)===entry)shared.delete(key);return connection.setDialogPolicy(policy)};const tracked=(subscribe)=>(...args)=>{const unsubscribe=subscribe(...args);subscriptions.push(unsubscribe);return unsubscribe};const readOnly=(what,get)=>({get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)});const client=connection.cdp;const transportSubscriptions=[];const transportEvents=new Proxy(client.transportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){return(...args)=>{const unsubscribe=tracked(target.on.bind(target))(...args);transportSubscriptions.push(unsubscribe);return unsubscribe}}if(property==="clearListeners"){return()=>{for(const unsubscribe of transportSubscriptions.splice(0))unsubscribe()}}if(property==="emit"){return()=>{throw new TypeError("cannot emit transport events through a handle: every holder of this connection hears them")}}return bindTo(target,Reflect.get(target,property,target))}));const clientView=new Proxy(client,readOnly("the shared CDP client",(target,property)=>{ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="close")return close;if(property==="on")return tracked(target.on.bind(target));if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close")return close;ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="cdp")return clientView;if(Object.hasOwn(overlay,property))return overlay[property];return bindTo(target,Reflect.get(target,property,target))},set(target,property,value){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);return Reflect.set(overlay,property,value)},defineProperty(target,property,descriptor){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);if(descriptor.configurable!==true)return false;return Reflect.defineProperty(overlay,property,descriptor)},deleteProperty(target,property){ensureOpen(property);if(Object.hasOwn(overlay,property))return Reflect.deleteProperty(overlay,property);return refuse("the shared connection")(target,property)},has(target,property){return Object.hasOwn(overlay,property)||Reflect.has(target,property)},ownKeys(target){return[...new Set([...Reflect.ownKeys(target),...Reflect.ownKeys(overlay)])]},getOwnPropertyDescriptor(target,property){return Object.hasOwn(overlay,property)?Reflect.getOwnPropertyDescriptor(overlay,property):Reflect.getOwnPropertyDescriptor(target,property)}})}function isPlainData(value,path=new Set){if(typeof value==="function"||value===null||typeof value!=="object")return true;if(path.has(value))return false;const prototype=Object.getPrototypeOf(value);const isArray=Array.isArray(value);if(isArray?prototype!==Array.prototype:prototype!==Object.prototype&&prototype!==null){return false}path.add(value);try{for(const key of Reflect.ownKeys(value)){if(isArray&&key==="length")continue;if(typeof key==="symbol")return false;const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,options))return open(options);if(!entry){entry={options,refs:0,ready:open(options)};shared.set(webSocketDebuggerUrl,entry)}entry.refs+=1;try{const connection=await entry.ready;const reconnected=connection.cdp.ensureConnected();await(timeoutMs===undefined?reconnected:withinTimeout(reconnected,timeoutMs,`timed out after ${timeoutMs}ms reconnecting the CDP session on ${webSocketDebuggerUrl}`));return lease(webSocketDebuggerUrl,entry,connection)}catch(error){if(shared.get(webSocketDebuggerUrl)===entry)shared.delete(webSocketDebuggerUrl);await release(webSocketDebuggerUrl,entry);throw error}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#storageRoot;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path2.resolve(options.storageRoot??process.cwd())}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async newTab(url="about:blank"){await Promise.resolve().then(() => init_agent_tabs());return(await createAgentTabs(this).create(url)).page}async attachPage(targetId){if(this.#pages.has(targetId))return this.#pages.get(targetId).page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);entry.page=page;this.#pages.set(targetId,entry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),resolvePath:(value)=>path2.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path2.resolve(this.#storageRoot,value);await mkdir2(path2.dirname(resolved),{recursive:true});return resolved},registerReadableDownload:(value)=>value,isReadableDownload:()=>false,openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}}async function browserKey(client,cdpUrl){if(/^wss?:\/\//.test(cdpUrl))return cdpUrl;return(await client.discoverVersion()).webSocketDebuggerUrl}function createClient(cdpHttpUrl,options){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}return new CdpClient({cdpUrl:cdpHttpUrl,...options.client,dialogPolicy:options.dialogPolicy??options.client?.dialogPolicy})}async function openConnection(cdpHttpUrl,options={}){return new BrowserConnection(createClient(cdpHttpUrl,options),options).initialize()}async function connect(cdpHttpUrl,options={}){const client=createClient(cdpHttpUrl,options);if(!canShareConnection(options))return new BrowserConnection(client,options).initialize();const key=await browserKey(client,cdpHttpUrl);return acquireSharedConnection(key,options,{open:()=>openConnection(key,options)})}var OMOWRIGHT_PAGE_CDP_METHODS=Object.freeze(["Browser.getVersion","DOM.describeNode","DOM.enable","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelectorAll","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.setDeviceMetricsOverride","Emulation.setFocusEmulationEnabled","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.enable","Page.addScriptToEvaluateOnNewDocument","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.enable","Page.getFrameTree","Page.getLayoutMetrics","Page.getNavigationHistory","Page.handleJavaScriptDialog","Page.navigate","Page.navigateToHistoryEntry","Page.printToPDF","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.screencastFrameAck","Page.setInterceptFileChooserDialog","Page.setWebLifecycleState","Page.startScreencast","Page.stopScreencast","Runtime.callFunctionOn","Runtime.evaluate","Runtime.releaseObject","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);import{spawn}from"node:child_process";import{mkdirSync,readFileSync as readFileSync2,rmSync,writeFileSync}from"node:fs";import path4 from"node:path";import{setTimeout as sleep2}from"node:timers/promises";import{randomUUID as randomUUID2}from"node:crypto";import{watch}from"node:fs";import{link as link2,readdir,rename,stat,unlink as unlink2}from"node:fs/promises";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{execFile}from"node:child_process";import{randomUUID}from"node:crypto";import{chmod,link,open as open2,readFile,unlink}from"node:fs/promises";import{promisify}from"node:util";var execFileAsync=promisify(execFile);var ownStartTime;async function processStartTime(pid){if(process.platform==="win32")return null;if(process.platform==="linux"){try{const text=await readFile(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}try{const{stdout}=await execFileAsync("ps",["-o","lstart=","-p",String(pid)],{env:{...process.env,LC_ALL:"C",TZ:"UTC"}});return stdout.trim()||null}catch{return null}}async function createLock(lockPath){ownStartTime??=processStartTime(process.pid);const token=randomUUID();const tempPath=`${lockPath}.${process.pid}.${randomUUID()}.tmp`;let handle;try{handle=await open2(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify({pid:process.pid,start:await ownStartTime,token,acquiredAt:new Date().toISOString()})}
|
|
1469
|
-
`,
|
|
1470
|
-
|
|
1324
|
+
}`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].toSorted((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return snapshotResult(jn,Vn,{tree:ii.tree,refs:ci})}var KNOWN_IFRAME_ORIGINS;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var init_snapshot=__esmMin(()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3});var init_session_tab_queries=__esmMin(()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()});var init_annotate_screenshot=__esmMin(()=>{});var AI_TAB_STABLE_VIEWPORT;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),AI_TAB_STABLE_VIEWPORT={width:1440,height:900}});function errorMessageOf(error){const message=readProperty(error,`message`);return message===undefined?undefined:String(message)}function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path2.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return xn.stderr}function createFfmpegVideoRecorderClass(){return class FfmpegVideoRecorder{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];#failure=null;constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}async ready(){await this.#t.ready;if(this.#t.error){await this.dispose();throw new VideoRecordingError(this.#t.error.message,{cause:this.#t.error})}}async dispose(){await disposeProcess(this.#t)}writeFrame(xn,jn){if(this.#r||this.#failure)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c()).catch(async(error)=>{this.#failure??=error;await this.dispose()})}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){try{if(this.#r)return;if(this.#failure)throw this.#failure;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),this.#failure)throw this.#failure;if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t,ENCODER_EXIT_TIMEOUT_MS));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}catch(error){throw new VideoRecordingError(errorMessageOf(error),{cause:error})}finally{await this.dispose()}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}}}function createOmOVideoClass(){return class OmOVideo{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn);await ei.ready();let{promise:ti,resolve:ni}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1000;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:(error)=>ni({error}),resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,await ei.dispose(),ni({error:xn}),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion({path:qn})}catch(xn){throw this.#n=null,jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn);let result=await this.#t.completion;if(result.error)throw result.error;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var init_video=__esmMin(()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=createFfmpegVideoRecorderClass(),OmOVideo=createOmOVideoClass()});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:undefined,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==undefined){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===undefined?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==undefined)return typeof xn==`number`?`${xn}px`:xn}function createOmOPageClass(){return class OmOPage{#networkCount=0;#networkOff=null;#closeRequested=false;cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;#runtimeListeners=0;#runtimeEpoch=0;#runtimeReady=Promise.resolve();constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){this.#networkCount>0&&(this.#networkOff=subscribePageNetworkEvents(this));this.#a.push(subscribeConsoleEvents(this),subscribePageErrors(this));let xn=new Set,jn=(xn)=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,(xn)=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#a.push(this.cdp.on(`Page.javascriptDialogOpening`,(xn,Vn)=>{if(Vn.sessionId===this.#n)return this.events.emit(`dialog`,Vn.dialog??new Dialog(xn,(dialogAction)=>this.cdp.send(`Page.handleJavaScriptDialog`,dialogAction,this.#n))).catch(jn)})),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,(xn)=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,(xn)=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,(xn)=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=(Vn)=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,(xn)=>Vn(xn))),this.#u(`Page.downloadWillBegin`,(xn)=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||!this.events.listenerCount(`popup`)||this.browser.resolvePopup(xn).then((xn)=>xn&&this.events.emit(`popup`,xn)).catch((xn)=>this.events.emit(`popupError`,xn).catch(jn))})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.#a.push(this.cdp.on(`Target.targetDestroyed`,(xn)=>{xn.targetId===this.targetId&&this.dispose().catch(jn)}),this.cdp.on(`Target.detachedFromTarget`,(xn)=>{xn.targetId===this.targetId&&this.cdp.send(`Target.getTargetInfo`,{targetId:this.targetId}).then(()=>{},()=>this.dispose()).catch(jn)})),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn]),this.#runtimeListeners>0&&this.#setRuntimeCapture(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){assertPageEvent(xn);let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn)),active=true,isNetwork=xn===`request`||xn===`response`;if(isNetwork&&this.#networkCount++===0)this.#networkOff=subscribePageNetworkEvents(this);xn===`filechooser`&&this.#m();RUNTIME_PAGE_EVENTS.has(xn)&&this.#addRuntimeListener();const off=()=>{if(!active)return;active=false;qn();Vn.get(jn)===off&&Vn.delete(jn);if(isNetwork&&--this.#networkCount===0){this.#networkOff?.();this.#networkOff=null}xn===`filechooser`&&this.#h();RUNTIME_PAGE_EVENTS.has(xn)&&this.#removeRuntimeListener()};Vn.set(jn,off);this.#e.set(xn,Vn);return off}off(xn,jn){assertPageEvent(xn);this.#e.get(xn)?.get(jn)?.()}waitForResponse(match,options={}){return this.waitForEvent(`response`,{...options,predicate:networkPredicate(match)})}waitForRequest(match,options={}){return this.waitForEvent(`request`,{...options,predicate:networkPredicate(match)})}async waitForEvent(xn,jn={}){if(typeof jn===`function`)jn={predicate:jn};assertPageEvent(xn);let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,Qn(),xn())},ti=(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path2.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,ri=()=>{},Qn=()=>{ni(),ri(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then((xn)=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()});xn===`popup`&&(ri=this.events.on(`popupError`,({data:xn})=>ei(()=>Jn(xn))))})}#d(){this.#networkOff?.();this.#networkOff=null;disposeNetwork(this);for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),++this.#runtimeEpoch,this.#runtimeListeners>0&&await this.#setRuntimeCapture(false),this.#runtimeListeners=0,this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,++this.#runtimeEpoch,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true),this.#runtimeListeners>0&&this.#setRuntimeCapture(true,undefined,true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map((jn)=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}#setRuntimeCapture(enabled,sessions=this.#f(),clearEntries=false){const epoch=this.#runtimeEpoch;return this.#runtimeReady=this.#runtimeReady.then(()=>withoutReplContext(async()=>{await Promise.allSettled(sessions.map(async(session)=>{if(enabled){if(clearEntries)await this.cdp.send(`Runtime.discardConsoleEntries`,undefined,session).catch(()=>{});if(epoch!==this.#runtimeEpoch||this.#runtimeListeners===0)return}await this.cdp.send(enabled||hasPageBindings(this)?`Runtime.enable`:`Runtime.disable`,undefined,session)}))}))}#addRuntimeListener(){this.#runtimeListeners+=1,this.#runtimeListeners===1&&(++this.#runtimeEpoch,this.#setRuntimeCapture(true,undefined,true))}#removeRuntimeListener(){this.#runtimeListeners!==0&&(--this.#runtimeListeners,this.#runtimeListeners===0&&(++this.#runtimeEpoch,this.#setRuntimeCapture(false)))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(this.#runtimeListeners>0)await this.#runtimeReady;if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){await networkReady(this);const releaseNetwork=[`interactive`,`stable`,`networkidle`].includes(jn.waitUntil??`interactive`)?acquireNetwork(this.cdp,await this.resolveSessionId()):null;const documents=trackDocumentResponses(this,this.frameManager.mainFrameId);try{await releaseNetwork?.ready;await documents.ready;let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return null}try{await Yn}catch(xn){if(!await this.#_())throw xn}return documents.response(Zn.loaderId)}Yn&&await Yn;return documents.response(Zn.loaderId)}finally{documents.dispose(),releaseNetwork?.()}}async goBack(){return await this.#historyStep(-1)}async goForward(){return await this.#historyStep(1)}async#historyStep(delta){let history=await this._sendToTarget(`Page.getNavigationHistory`),entry=history.entries[history.currentIndex+delta];if(!entry)return null;return await this.#navigationResponse(()=>this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:entry.id}))}async reload(){return await this.#navigationResponse(()=>this._sendToTarget(`Page.reload`))}async waitForTimeout(timeout){await sleep$12(timeout)}async setContent(html,options={}){const waitUntil=options.waitUntil??`load`,timeout=options.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(![`load`,`domcontentloaded`,`networkidle`,`commit`].includes(waitUntil))throw Error(`page.setContent: waitUntil must be one of load, domcontentloaded, networkidle, commit; got "${waitUntil}"`);let timer;const deadline=new Promise((_,reject)=>{if(timeout>0)timer=setTimeout(()=>reject(Error(`page.setContent: Timeout ${timeout}ms exceeded waiting for "${waitUntil}"`)),timeout)});const idle=waitUntil===`networkidle`?this.#S(timeout>0?timeout:2147483647):null;idle?.catch(()=>{});try{await Promise.race([deadline,(async()=>{await this.evaluate(({html,waitUntil})=>{document.open();const ready=waitUntil===`commit`?null:new Promise((resolve)=>waitUntil===`domcontentloaded`?document.addEventListener(`DOMContentLoaded`,()=>resolve(),{once:true}):window.addEventListener(`load`,()=>resolve(),{once:true}));document.write(html);document.close();return ready},{html,waitUntil});await idle})()])}finally{clearTimeout(timer)}}async waitForLoadState(state=`interactive`,options=DEFAULT_WAIT_TIMEOUT_MS){let timeout=typeof options==`number`?options:options?.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(state===`interactive`||state===`stable`){await waitForNavigationReadiness(this,state,timeout);return}if(state===`commit`)return;if(state===`networkidle`){await this.#S(timeout);return}if(state!==`load`&&state!==`domcontentloaded`)throw Error(`waitForLoadState: unsupported state "${state}"; expected load, domcontentloaded, networkidle, commit, interactive or stable`);let sessionId=await this.resolveSessionId(this.#n),reached=state===`load`?(xn)=>xn===`complete`:(xn)=>xn!==`loading`,unsubscribe=()=>{},timer;try{await new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for load state "${state}"`)),timeout),unsubscribe=this.cdp.on(state===`load`?`Page.loadEventFired`:`Page.domContentEventFired`,(xn,meta)=>{meta.sessionId===sessionId&&resolve()}),this.evaluate(`document.readyState`).then((xn)=>{reached(xn)&&resolve()},()=>{})})}finally{clearTimeout(timer),unsubscribe()}}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(match,options={}){let timeout=options.timeout??DEFAULT_WAIT_TIMEOUT_MS,start=Date.now();for(;Date.now()-start<timeout;){if(await urlMatches(this.url(),match)){options.waitUntil&&await this.waitForLoadState(options.waitUntil,{timeout:Math.max(0,timeout-(Date.now()-start))});return}await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(match)}`)}async waitForFunction(xn,jn,Vn){let qn=Vn?.polling??`raf`,Jn=Vn?.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(qn!==`raf`&&!(typeof qn==`number`&&Number.isFinite(qn)&&qn>0))throw Error(`page.waitForFunction: polling must be "raf" or a positive number of milliseconds`);if(!(typeof Jn==`number`&&Number.isFinite(Jn)&&Jn>=0))throw Error(`page.waitForFunction: timeout must be a non-negative number of milliseconds (0 waits forever)`);let Yn=typeof xn==`function`?xn.toString():String(xn),Zn=Jn>0?Date.now()+Jn:1/0,Qn=`async function(arg, polling, remainingMs) { var __name = (t) => t; const predicate = (a) => { const value = (${Yn}); return typeof value === 'function' ? value(a) : value; }; const start = performance.now(); const next = () => new Promise((resolve) => { if (polling !== 'raf') { setTimeout(resolve, polling); return; } let frame; const fallback = setTimeout(() => { resolve(); cancelAnimationFrame(frame); }, ${WAIT_FOR_FUNCTION_RAF_FALLBACK_MS}); frame = requestAnimationFrame(() => { clearTimeout(fallback); resolve(); }); }); for (;;) { const value = await predicate(arg); if (value) return { done: true, value }; if (remainingMs > 0 && performance.now() - start >= remainingMs) return { done: false }; await next(); } }`,Cn,$n=new Promise((jn,qn)=>{Cn=this.events.on(`close`,()=>qn(Error(`page.waitForFunction: the page closed while waiting`)))});$n.catch(()=>{});try{for(;;){let xn=Zn-Date.now();if(xn<=0)throw new WaitForFunctionTimeoutError(Yn,Jn);let Vn,Xn=new Promise((jn,qn)=>{Number.isFinite(xn)&&(Vn=setTimeout(()=>qn(new WaitForFunctionTimeoutError(Yn,Jn)),xn))}),ei=(async()=>{let Vn=await this.#x(),{result:Jn,exceptionDetails:Zn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Vn,functionDeclaration:Qn,arguments:[{value:jn},{value:qn},{value:Number.isFinite(xn)?xn:0}],returnByValue:true,awaitPromise:true},{timeoutMs:Number.isFinite(xn)?xn+WAIT_FOR_FUNCTION_CALL_MARGIN_MS:0});if(Zn)throw Error(formatRuntimeException(Zn,`page.waitForFunction: the page function threw`));return Jn.value})();ei.catch(()=>{});try{let xn=await Promise.race([ei,Xn,$n]);if(readOptionalProperty(xn,`done`))return readProperty(xn,`value`)}catch(xn){if(isUnserializableResultError(xn))return true;if(this.#s||this.#closeRequested&&isSessionDetachedError(xn))throw Error(`page.waitForFunction: the page closed while waiting`);if(!isNavigationInterruptedError(xn))throw xn;await Promise.race([sleep$12(20),$n])}finally{clearTimeout(Vn)}}}finally{definedOrThrow(Cn)()}}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate((xn)=>{let jn=document.querySelector(xn);if(!jn)return{attached:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===undefined){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute)}url({truncate:xn=false}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:undefined,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}
|
|
1325
|
+
Viewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path2.join(jn,path2.basename(xn.path));await mkdir(path2.dirname(Vn),{recursive:true}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path2.dirname(jn),{recursive:true}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):undefined,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path2.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){this.#closeRequested=true;for(const sessionId of this.#f())this.cdp.closeSession?.(sessionId);if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,undefined,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){let jn=await this.resolveSessionId(this.#n),releaseNetwork=acquireNetwork(this.cdp,jn);await releaseNetwork.ready;await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),releaseNetwork(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=(xn)=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#navigationResponse(trigger){let frameId=this.frameManager.mainFrameId,documents=trackDocumentResponses(this,frameId),offs=[],timer;try{await documents.ready;let sessionId=await this.resolveSessionId(this.#n),deadline=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for navigation`)),DEFAULT_WAIT_TIMEOUT_MS)}),committed=new Promise((resolve)=>{offs.push(this.cdp.on(`Page.frameNavigated`,(params,meta)=>{meta.sessionId===sessionId&&!params.frame.parentId&&resolve(params.frame.loaderId)}),this.cdp.on(`Page.navigatedWithinDocument`,(params,meta)=>{meta.sessionId===sessionId&¶ms.frameId===frameId&&resolve(null)}))});deadline.catch(()=>{});let[,loaderId]=await Promise.race([Promise.all([trigger(),committed]),deadline]);if(!loaderId)return null;await Promise.race([this.cdp.send(`Page.getFrameTree`,undefined,sessionId),deadline]);return documents.response(loaderId)}finally{clearTimeout(timer);for(let off of offs)off();documents.dispose()}}async _sendToTarget(xn,jn,Vn={}){await networkReady(this);if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==undefined){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var init_page=__esmMin(()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=createOmOPageClass()});init_client$6();init_session_manager();init_frame_manager();init_page();Object.assign(initialized(()=>OmOPage).prototype,{addInitScript,exposeFunction,exposeBinding,setExtraHTTPHeaders,setViewportSize,emulateMedia});var testIdAttributeName="data-testid";var selectors={setTestIdAttribute(attributeName){if(typeof attributeName!=="string"||!/^[^\s"'>/=[\]]+$/.test(attributeName)){throw new TypeError(`selectors.setTestIdAttribute: invalid attribute name ${JSON.stringify(attributeName)}`)}testIdAttributeName=attributeName}};function isRegExpValue(value){return Object.prototype.toString.call(value)==="[object RegExp]"}function attributeSelector(name,value,exact){if(isRegExpValue(value))return`internal:attr=[${name}=/${value.source.replaceAll(">>",">\\x3e")}/${value.flags}]`;return`internal:attr=[${name}=${JSON.stringify(String(value)).replaceAll(">","\\u003e")}${exact?"s":"i"}]`}class AttributeLocatorGetters{getByAltText(text,options={}){return this.locator(attributeSelector("alt",text,options.exact))}getByPlaceholder(text,options={}){return this.locator(attributeSelector("placeholder",text,options.exact))}getByTestId(testId){return this.locator(attributeSelector(testIdAttributeName,testId,true))}getByTitle(text,options={}){return this.locator(attributeSelector("title",text,options.exact))}}for(const Container of[initialized(()=>OmOPage),initialized(()=>OmOFrame),initialized(()=>FrameLocator)]){for(const name of Object.getOwnPropertyNames(AttributeLocatorGetters.prototype)){if(name!=="constructor")Object.defineProperty(Container.prototype,name,definedOrThrow(Object.getOwnPropertyDescriptor(AttributeLocatorGetters.prototype,name)))}}initialized(()=>OmOPage).prototype.route=function(url,handler,options){return pageRoute(this,url,handler,options)};initialized(()=>OmOPage).prototype.unroute=function(url,handler){return pageUnroute(this,url,handler)};initialized(()=>OmOPage).prototype.unrouteAll=function(){return pageUnrouteAll(this)};var shared=new Map;function withinTimeout(pending,timeoutMs,message){let timer;return Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeoutMs)})]).finally(()=>clearTimeout(timer))}function release(key,entry){entry.refs-=1;if(entry.refs>0)return Promise.resolve();if(shared.get(key)===entry)shared.delete(key);return entry.ready.then((connection)=>connection.close(),()=>{})}function bindTo(target,value){return typeof value==="function"?value.bind(target):value}class SharedConnectionError extends Error{constructor(){super("this browser connection is shared; pass dialogPolicy to connect()/connectNamed() so this holder gets its own connection");this.name="SharedConnectionError";this.code="shared_connection"}}var RESERVED=new Set(["cdp","close","setDialogPolicy"]);function refuse(what){return(_target,property)=>{throw new TypeError(`cannot change ${String(property)} on ${what} through a handle: every holder of this connection uses it`)}}function readOnly(what,get){return{get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=new Set;const transportSubscriptions=new Set;const unsubscribeAll=(set)=>{for(const unsubscribe of[...set])unsubscribe()};const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){unsubscribeAll(subscriptions);closed=release(key,entry)}return closed};const setDialogPolicy=(policy)=>{ensureOpen("setDialogPolicy");if(entry.refs>1)throw new SharedConnectionError;if(shared.get(key)===entry)shared.delete(key);return connection.setDialogPolicy(policy)};const tracked=(subscribe,...sets)=>(...args)=>{const remove=subscribe(...args);let removed=false;const unsubscribe=()=>{if(removed)return;removed=true;for(const set of sets)set.delete(unsubscribe);remove()};for(const set of sets)set.add(unsubscribe);return unsubscribe};const client=connection.cdp;const sharedTransportEvents=client.transportEvents;if(sharedTransportEvents===undefined)throw new TypeError("Cannot create proxy with a non-object as target or handler");const transportEvents=new Proxy(sharedTransportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){const on=(name,listener)=>target.on(name,(event)=>listener(event));return tracked(on,subscriptions,transportSubscriptions)}if(property==="clearListeners")return()=>unsubscribeAll(transportSubscriptions);if(property==="emit"){return()=>{throw new TypeError("cannot emit transport events through a handle: every holder of this connection hears them")}}return bindTo(target,Reflect.get(target,property,target))}));const clientView=new Proxy(client,readOnly("the shared CDP client",(target,property)=>{ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="close")return close;if(property==="on")return tracked(target.on.bind(target),subscriptions);if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close"||property===Symbol.asyncDispose)return close;ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="cdp")return clientView;if(Object.hasOwn(overlay,property))return overlay[property];return bindTo(target,Reflect.get(target,property,target))},set(target,property,value){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);return Reflect.set(overlay,property,value)},defineProperty(target,property,descriptor){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);if(descriptor.configurable!==true)return false;return Reflect.defineProperty(overlay,property,descriptor)},deleteProperty(target,property){ensureOpen(property);if(Object.hasOwn(overlay,property))return Reflect.deleteProperty(overlay,property);return refuse("the shared connection")(target,property)},has(target,property){return Object.hasOwn(overlay,property)||Reflect.has(target,property)},ownKeys(target){return[...new Set([...Reflect.ownKeys(target),...Reflect.ownKeys(overlay)])]},getOwnPropertyDescriptor(target,property){return Object.hasOwn(overlay,property)?Reflect.getOwnPropertyDescriptor(overlay,property):Reflect.getOwnPropertyDescriptor(target,property)}})}function isPlainData(value,path=new Set){if(typeof value==="function"||value===null||typeof value!=="object")return true;if(path.has(value))return false;const prototype=Object.getPrototypeOf(value);const isArray=Array.isArray(value);if(isArray?prototype!==Array.prototype:prototype!==Object.prototype&&prototype!==null){return false}path.add(value);try{for(const key of Reflect.ownKeys(value)){if(isArray&&key==="length")continue;if(typeof key==="symbol")return false;const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!readProperty(descriptor,"enumerable")||descriptor===undefined||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function frozenCopy(value){if(value===null||typeof value!=="object")return value;let copy;if(Array.isArray(value)){const sparse=[];sparse.length=value.length;copy=sparse}else copy=Object.create(Object.getPrototypeOf(value));for(const key of Object.keys(value)){Object.defineProperty(copy,key,{value:frozenCopy(readProperty(value,key)),enumerable:true})}return Object.freeze(copy)}function openingOptions(snapshot){if(snapshot?.dialogPolicy!=null||snapshot?.client?.dialogPolicy!=null)return snapshot;return Object.freeze({...snapshot,dialogPolicy:Object.freeze({accept:true})})}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);const snapshot=frozenCopy(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,snapshot))return open(openingOptions(snapshot));if(!entry){entry={options:snapshot,refs:0,ready:open(openingOptions(snapshot))};shared.set(webSocketDebuggerUrl,entry)}entry.refs+=1;try{const connection=await entry.ready;const reconnected=connection.cdp.ensureConnected();await(timeoutMs===undefined?reconnected:withinTimeout(reconnected,timeoutMs,`timed out after ${timeoutMs}ms reconnecting the CDP session on ${webSocketDebuggerUrl}`));return lease(webSocketDebuggerUrl,entry,connection)}catch(error){if(shared.get(webSocketDebuggerUrl)===entry)shared.delete(webSocketDebuggerUrl);await release(webSocketDebuggerUrl,entry);throw error}}var managers=new WeakMap;var CAPABILITY=targetCreationCapability;function optionsKey(options={}){return JSON.stringify({viewport:{...DEFAULT_AGENT_VIEWPORT,...options.viewport},closeTimeoutMs:options.closeTimeoutMs??5000})}class AgentTabManager{#connection;#owned=new Map;#unsubscribers=[];#disposed=false;#closing=new Map;viewport;closeTimeoutMs;ready;constructor(connection,options={}){if(!connection?.cdp)throw new TypeError("createAgentTabs requires a browser connection");this.#connection=connection;this.viewport=Object.freeze({...DEFAULT_AGENT_VIEWPORT,...options.viewport});this.closeTimeoutMs=options.closeTimeoutMs??5000;this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected",()=>{for(const id of[...this.#owned.keys()])this.#destroyed(id,Error("Browser transport disconnected"))}));this.ready=Promise.resolve(connection.cdp.ensureConnected?.())}async create(url="about:blank",options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");await this.ready;const viewport={...this.viewport,...options.viewport};const result=await this.#connection.cdp.send("Target.createTarget",{url:"about:blank",background:true,newWindow:true,...options.browserContextId?{browserContextId:options.browserContextId}:{}},undefined,{capability:CAPABILITY});const targetId=result.targetId;if(await this.#isHeadless())await this.#connection.cdp.send("Target.activateTarget",{targetId});const tab=await this.adopt(targetId,{viewport});if(url!=="about:blank")await tab.page.goto(url);return tab}async adopt(targetId,options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");const existing=this.#owned.get(targetId);if(existing){if(existing.page===null)throw new TypeError(`Target ${targetId} is still being adopted`);return this.#public(existing,existing.page)}const viewport={...this.viewport,...options.viewport};const record={targetId,page:null,viewport:Object.freeze({...viewport}),repinQueue:Promise.resolve()};this.#owned.set(targetId,record);try{const page=await this.#connection.attachPage(targetId);record.page=page;await repinViewport(page,record.viewport);record.navigationOff=page.on?.("framenavigated",(event)=>{if(!event.parentFrameId)this.#repin(record)});return this.#public(record,page)}catch(error){await this.#connection.cdp.send("Target.closeTarget",{targetId}).catch(()=>{});throw error}}#public(record,page=record.page){return Object.freeze({targetId:record.targetId,page,viewport:{...record.viewport},close:(options)=>this.close(record.targetId,options)})}get(targetId){const record=targetId===undefined?undefined:this.#owned.get(targetId);return record?this.#public(record):null}list(){return[...this.#owned.values()].map((record)=>this.#public(record))}async#isHeadless(){if(typeof this.#connection.cdp.isHeadless==="boolean")return this.#connection.cdp.isHeadless;const version=await this.#connection.cdp.send("Browser.getVersion").catch(()=>null);return/Headless/i.test(version?.product??"")}#queueRepin(record,viewport,reportErrors=false){const size={...viewport};const operation=record.repinQueue.then(async()=>{try{if(record.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(record.page,size)}catch(error){if(reportErrors)console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`,error);else throw error}record.viewport=Object.freeze(size);return{...size}});record.repinQueue=operation.catch(()=>{});return operation}async#repin(record){await this.#queueRepin(record,record.viewport,true)}async repin(tabOrTargetId,viewport=this.viewport){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record)throw Error(`Target ${id} is not owned by this manager`);return this.#queueRepin(record,viewport)}async close(tabOrTargetId,options={}){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record||id===undefined)throw Error(`Target ${id} is not owned by this manager`);const existing=this.#closing.get(id);if(existing)return existing.promise;const{promise,resolve:resolveOperation,reject:rejectOperation}=Promise.withResolvers();const entry={promise,reject:rejectOperation};this.#closing.set(id,entry);this.#close(record,options).then(resolveOperation,rejectOperation).finally(()=>{if(this.#closing.get(id)===entry)this.#closing.delete(id)});return promise}async#close(record,options){const{promise:destroyed,resolve:resolveDestroy,reject:rejectDestroy}=Promise.withResolvers();const timeout=setTimeout(()=>rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)),options.timeoutMs??this.closeTimeoutMs);const off=this.#connection.cdp.on("Target.targetDestroyed",(info)=>{if(info?.targetId===record.targetId)resolveDestroy()});const offDisconnect=this.#connection.cdp.transportEvents?.on?.("disconnected",()=>rejectDestroy(Error("Browser transport disconnected")));try{if(options.runBeforeUnload&&record.page)await record.page.cdp.send("Page.close",undefined,await record.page.resolveSessionId()).catch(()=>this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId}));else await this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId});if(this.#owned.has(record.targetId))await destroyed}finally{clearTimeout(timeout);off();offDisconnect?.();if(!this.#owned.has(record.targetId))record.navigationOff?.()}}#destroyed(id,error){if(id===undefined)return;const record=this.#owned.get(id);if(!record)return;record.navigationOff?.();this.#owned.delete(id);if(error)this.#closing.get(id)?.reject(error)}async closeAll(options={}){const results=await Promise.allSettled([...this.#owned.keys()].map((id)=>this.close(id,options)));const failures=results.filter((result)=>result.status==="rejected").map((result)=>result.reason);if(failures.length)throw new AggregateError(failures,"Failed to close one or more agent tabs")}async dispose(options={closeOwned:true}){if(this.#disposed)return;let failure;if(options.closeOwned!==false)try{await this.closeAll(options)}catch(error){failure=error}this.#disposed=true;for(const off of this.#unsubscribers){if(off===undefined)throw new TypeError("off is not a function");off()}this.#unsubscribers=[];if(failure)throw failure}}function getAgentTabs(connection){return managers.get(connection)}function createAgentTabs(connection,options={}){const current=managers.get(connection);if(current){if(current._optionsKey!==optionsKey(options))throw new TypeError("Conflicting AgentTabManager options");return current}const manager=new AgentTabManager(connection,options);Object.defineProperty(manager,"_optionsKey",{value:optionsKey(options)});managers.set(connection,manager);return manager}function cookieToCdp(cookie){const{name,value,url,domain,path,httpOnly,secure,sameSite}=cookie;const out={name,value,url,domain,path,httpOnly,secure,sameSite};if(cookie.expires!==undefined&&cookie.expires!==-1)out.expires=cookie.expires;if(cookie.partitionKey!==undefined){out.partitionKey={topLevelSite:cookie.partitionKey,hasCrossSiteAncestor:true}}return out}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies).map(cookieToCdp)})}var isCookieFilterKey=(key)=>["name","domain","path"].includes(key);class BrowserContext{#connection;#scope;#origins=new Set;constructor(connection,browserContextId){this.#connection=connection;this.#scope=browserContextId?{browserContextId}:{}}trackOrigin(url){if(!/^https?:\/\//.test(url??""))return;this.#origins.add(new URL(url).origin)}async cookies(urls=[]){const{cookies}=await this.#connection.cdp.send("Storage.getCookies",this.#scope);const parsed=(typeof urls==="string"?[urls]:urls).map((url)=>new URL(url));return cookies.filter((cookie)=>!parsed.length||parsed.some((url)=>{const domain=cookie.domain.startsWith(".")?cookie.domain.slice(1):cookie.domain;if(url.hostname!==domain&&!(cookie.domain.startsWith(".")&&url.hostname.endsWith(`.${domain}`)))return false;if(cookie.secure&&url.protocol!=="https:"&&url.hostname!=="localhost")return false;const pathname=cookie.path.endsWith("/")?cookie.path:`${cookie.path}/`;return url.pathname===cookie.path||`${url.pathname}/`.startsWith(pathname)})).map((cookie)=>{const{name,value,domain,path:cookiePath,expires,httpOnly,secure}=cookie;const out={name,value,domain,path:cookiePath,expires,httpOnly,secure,sameSite:cookie.sameSite??"Lax"};if(cookie.partitionKey)out.partitionKey=cookie.partitionKey.topLevelSite;return out})}async addCookies(cookies){const normalized=cookies.map((cookie)=>{if(typeof cookie.name!=="string"||typeof cookie.value!=="string"){throw new TypeError("Cookie name and value must be strings")}if(cookie.url!==undefined){if(cookie.domain!==undefined||cookie.path!==undefined)throw new Error("Cookie must have either url or domain and path");const url=new URL(cookie.url);if(!/^https?:$/.test(url.protocol))throw new Error("Cookie url must be HTTP or HTTPS");return cookieToCdp({...cookie,domain:url.hostname,path:url.pathname.slice(0,url.pathname.lastIndexOf("/")+1),secure:cookie.secure??url.protocol==="https:"})}if(!cookie.domain||!cookie.path)throw new Error("Cookie must have either url or domain and path");return cookieToCdp(cookie)});await this.#connection.cdp.send("Storage.setCookies",{...this.#scope,cookies:normalized})}async clearCookies(options={}){const filters=Object.entries(options).filter((entry)=>isCookieFilterKey(entry[0]));if(!filters.length){await this.#connection.cdp.send("Storage.clearCookies",this.#scope);return}const survivors=(await this.cookies()).filter((cookie)=>!filters.every(([key,filter])=>filter instanceof RegExp?new RegExp(filter.source,filter.flags.replace(/[gy]/g,"")).test(cookie[key]):cookie[key]===filter));await this.#connection.cdp.send("Storage.clearCookies",this.#scope);await this.addCookies(survivors)}async newPage(){return(await(getAgentTabs(this.#connection)??createAgentTabs(this.#connection)).create("about:blank",this.#scope)).page}async storageState(options={}){const state={cookies:await this.cookies(),origins:[]};if(this.#origins.size){const page=await this.newPage();try{await page.route("**/*",(route)=>route.fulfill({contentType:"text/html",body:"<html></html>"}));for(const origin of this.#origins){await page.goto(origin,{waitUntil:"domcontentloaded"});const{entries}=await page._sendToTarget("DOMStorage.getDOMStorageItems",{storageId:{securityOrigin:origin,isLocalStorage:true}});if(entries.length)state.origins.push({origin,localStorage:entries.map(([name,value])=>({name,value}))})}}finally{await page.close()}}if(options.path!==undefined){await mkdir3(path22.dirname(path22.resolve(options.path)),{recursive:true});await writeFile2(options.path,JSON.stringify(state,null,2))}return state}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#contexts=new Map;#storageRoot;#popups=new Map;#popupTargets=new Map;#attachingPopups=new Map;#ownedPopups=new Set;#popupOff=[];tabs;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path3.resolve(options.storageRoot??process.cwd());this.#popupOff.push(client.on("Target.targetCreated",({targetInfo})=>{const openerId=targetInfo?.openerId;if(targetInfo?.type!=="page"||!this.#acceptsPopup(openerId))return;const targets=this.#popupTargets.get(openerId)??[];targets.push({targetId:targetInfo.targetId});this.#popupTargets.set(openerId,targets);this.#matchPopups(openerId)}));this.#popupOff.push(client.on("Target.targetDestroyed",({targetId})=>{this.#ownedPopups.delete(targetId);const error=Error("Popup closed before attachment completed");this.#attachingPopups.get(targetId)?.reject(error);for(const targets of this.#popupTargets.values()){const target=targets.find((candidate)=>candidate.targetId===targetId);if(target)target.error=error}}))}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async newTab(url="about:blank"){return(await(getAgentTabs(this)??createAgentTabs(this)).create(url)).page}#acceptsPopup(openerId){return openerId!==undefined&&!!getAgentTabs(this)?.get(openerId)&&(this.#pages.get(openerId)?.page.events.listenerCount("popup")??0)>0}#matchPopups(openerId){const targets=this.#popupTargets.get(openerId);const queue=this.#popups.get(openerId);while(targets?.length&&queue?.length){const target=targets.shift();const pending=queue.shift();if(target===undefined||pending===undefined)break;if(target.error)pending.reject(target.error);else{this.#attachingPopups.set(target.targetId,pending);this.#ownedPopups.add(target.targetId);pending.operation=this.#attachPopup(target.targetId,pending).catch(pending.reject).finally(()=>{this.#attachingPopups.delete(target.targetId)})}}if(!targets?.length)this.#popupTargets.delete(openerId);if(!queue?.length)this.#popups.delete(openerId)}async#attachPopup(targetId,pending){const tabs=getAgentTabs(this)??createAgentTabs(this);const{page}=await tabs.adopt(targetId);Object.assign(page,{popupMetadata:Object.freeze(pending.metadata)});await page.waitForLoadState("interactive");pending.resolve(page)}async attachPage(targetId){const attached=this.#pages.get(targetId);if(attached)return attached.page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);const{targetInfo}=await this.#client.send("Target.getTargetInfo",{targetId});const contextId=targetInfo.browserContextId;let context=this.#contexts.get(contextId);if(!context){context=new BrowserContext(this,contextId);this.#contexts.set(contextId,context)}const pageContext=context;Object.assign(page,{context:()=>pageContext});for(const frame of frames.frames.values())pageContext.trackOrigin(frame.url);page.on("framenavigated",(frame)=>pageContext.trackOrigin(frame.url));const attachedEntry=Object.assign(entry,{page});this.#pages.set(targetId,attachedEntry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),setViewportSize:async(size)=>{const tabs=getAgentTabs(this);if(tabs?.get(targetId))await tabs.repin(targetId,size);else{if(entry.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(entry.page,size)}},resolvePath:(value)=>path3.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path3.resolve(this.#storageRoot,value);await mkdir4(path3.dirname(resolved),{recursive:true});return resolved},registerReadableDownloadPath:(value)=>value,isReadableDownload:()=>false,resolvePopup:async(metadata)=>{if(!this.#acceptsPopup(targetId))return;const queue=this.#popups.get(targetId)??[];const promise=new Promise((resolve,reject)=>queue.push({resolve,reject,metadata:{url:metadata.url,windowName:metadata.windowName}}));this.#popups.set(targetId,queue);this.#matchPopups(targetId);return promise},openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const off of this.#popupOff)off();for(const queue of this.#popups.values()){for(const pending of queue)pending.reject(Error("Browser connection closed"))}this.#popups.clear();this.#popupTargets.clear();for(const pending of this.#attachingPopups.values())pending.reject(Error("Browser connection closed"));await Promise.all([...this.#attachingPopups.values()].map((pending)=>pending.operation));const tabs=getAgentTabs(this);if(tabs){await Promise.all([...this.#ownedPopups].filter((id)=>tabs.get(id)).map((id)=>tabs.close(id)));await tabs.dispose({closeOwned:false})}for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}async[Symbol.asyncDispose](){await this.close()}}async function browserKey(client,cdpUrl){if(/^wss?:\/\//.test(cdpUrl))return cdpUrl;return(await client.discoverVersion()).webSocketDebuggerUrl}function createClient(cdpHttpUrl,options){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}return new CdpClient({cdpUrl:cdpHttpUrl,...options.client,dialogPolicy:options.dialogPolicy??options.client?.dialogPolicy})}async function openConnection(cdpHttpUrl,options={}){return new BrowserConnection(createClient(cdpHttpUrl,options),options).initialize()}async function connect(cdpHttpUrl,options={}){const client=createClient(cdpHttpUrl,options);if(!canShareConnection(options))return new BrowserConnection(client,options).initialize();const key=await browserKey(client,cdpHttpUrl);return acquireSharedConnection(key,options,{open:(snapshot)=>openConnection(key,snapshot)})}var OMOWRIGHT_PAGE_CDP_METHODS=Object.freeze(["Browser.getVersion","DOM.describeNode","DOM.enable","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelectorAll","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.setDeviceMetricsOverride","Emulation.setFocusEmulationEnabled","Emulation.setEmulatedMedia","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.disable","Network.enable","Network.getResponseBody","Network.setExtraHTTPHeaders","Page.addScriptToEvaluateOnNewDocument","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.enable","Page.getFrameTree","Page.getLayoutMetrics","Page.getNavigationHistory","Page.handleJavaScriptDialog","Page.navigate","Page.navigateToHistoryEntry","Page.printToPDF","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.screencastFrameAck","Page.setInterceptFileChooserDialog","Page.setWebLifecycleState","Page.startScreencast","Page.stopScreencast","Runtime.callFunctionOn","Runtime.addBinding","Runtime.disable","Runtime.discardConsoleEntries","Runtime.enable","Runtime.evaluate","Runtime.releaseObject","Runtime.removeBinding","Runtime.runIfWaitingForDebugger","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);var DARWIN_EXCLUSIVE_NONBLOCK=32|4;var WINDOWS_EXCLUSIVE=268435456;var probedPaths=new Set;var DARWIN_BUSY_CODES=new Set(["EAGAIN","EWOULDBLOCK"]);async function lockLinux(fd){return new Promise((resolve,reject)=>{const child=spawn2("flock",["-n","3"],{stdio:["ignore","ignore","pipe",fd]});let stderr="";const stderrStream=child.stderr;if(stderrStream===null)throw new TypeError("flock child has no stderr pipe");stderrStream.setEncoding("utf8");stderrStream.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error)=>{reject(error.code==="ENOENT"?new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`,{cause:error}):error)});child.once("close",(code,signal)=>{if(code===0)resolve(true);else if(code===1&&stderr.trim()==="")resolve(false);else reject(Object.assign(new Error(`instance lock flock failed (${signal??code}): ${stderr.trim()}`),{code:"ERR_INSTANCE_LOCK"}))})})}async function tryAcquire(lockPath){const platform=process.platform;if(platform==="win32"&&process.versions.bun){await Promise.resolve().then(() => init_lock_backend_win32_xbcm60vz());return tryAcquireWindows(lockPath)}let flags=constants.O_RDWR|constants.O_CREAT;if(platform==="darwin")flags|=DARWIN_EXCLUSIVE_NONBLOCK;else if(platform==="win32")flags|=WINDOWS_EXCLUSIVE;else if(platform!=="linux")throw new Error(`instance lock is unsupported on ${platform}`);let handle;try{handle=await open2(lockPath,flags,384)}catch(error){if(platform==="darwin"&&DARWIN_BUSY_CODES.has(readProperty(error,"code")))return null;if(platform==="win32"&&readProperty(error,"code")==="EBUSY")return null;throw error}try{if(platform==="linux"&&!await lockLinux(handle.fd)){await handle.close();return null}}catch(error){await handle.close();throw error}return{release:()=>handle.close()}}async function probeOnce(lockPath){if(probedPaths.has(lockPath))return;const second=await tryAcquire(lockPath);if(second!==null){await second.release();throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`)}probedPaths.add(lockPath)}var localLocks=new Map;function errorCode(error){return error===null||error===undefined?undefined:readProperty(error,"code")}function isPidAlive(pid){try{process.kill(pid,0);return true}catch(error){if(errorCode(error)==="EPERM")return true;if(errorCode(error)==="ESRCH")return false;throw error}}async function unlinkIfPresent(target){await unlink2(target).catch((error)=>{if(errorCode(error)!=="ENOENT")throw error})}async function acquireLock(lockPath,timeoutMs){const deadline=performance.now()+timeoutMs;let delay=10;for(;;){const held=await tryAcquire(lockPath);if(held){try{await probeOnce(lockPath);return held}catch(error){await held.release();throw error}}const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`timed out waiting for instance lock ${lockPath}`);await sleep(Math.min(remaining,delay*(0.75+Math.random()*0.5)));delay=Math.min(delay*2,250)}}async function acquireLocalLock(key){const previous=localLocks.get(key)??Promise.resolve();let releaseCurrent;const current=new Promise((resolve)=>{releaseCurrent=resolve});const tail=previous.then(()=>current);localLocks.set(key,tail);await previous;return()=>{releaseCurrent();if(localLocks.get(key)===tail)localLocks.delete(key)}}async function withLock(lockPath,{timeoutMs},run){const releaseLocal=await acquireLocalLock(lockPath);try{const held=await acquireLock(lockPath,timeoutMs);try{return await run()}finally{await held.release()}}finally{releaseLocal()}}var execFileAsync=promisify(execFile);var WINDOWS_START_TIME_TIMEOUT_MS=15000;var ownStartTime;async function processStartTime(pid){if(process.platform==="win32"){if(!Number.isInteger(pid)||pid<=0)return null;const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";try{const{stdout}=await execFileAsync(path4.win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`],{timeout:WINDOWS_START_TIME_TIMEOUT_MS,windowsHide:true});const ticks=String(stdout).trim();return/^\d+$/.test(ticks)?ticks:null}catch{return null}}if(process.platform==="linux"){try{const text=await readFile3(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}try{const{stdout}=await execFileAsync("ps",["-o","lstart=","-p",String(pid)],{env:{...process.env,LC_ALL:"C",TZ:"UTC"}});return stdout.trim()||null}catch{return null}}function ownProcessStartTime(){ownStartTime??=processStartTime(process.pid);return ownStartTime}var TERM_GRACE_MS=5000;var PID_FILE_NAME="omowright-browser.pid";var REAP_POLL_MS=50;var browserSpawnDetached=process.platform!=="win32";function profileDirFromArgs(browserArgs){for(const[index,argument]of browserArgs.entries()){const next=browserArgs[index+1];if(argument==="--user-data-dir"&&next)return path5.resolve(next);if(argument.startsWith("--user-data-dir="))return path5.resolve(argument.slice("--user-data-dir=".length))}return null}var signalsCanAskToQuit=process.platform!=="win32";async function terminateChild(child,{quitRequested=false}={}){if(child.pid===undefined)return;if(child.exitCode!==null||child.signalCode!==null)return;const exited=new Promise((resolve)=>child.once("exit",resolve));if(signalsCanAskToQuit){try{child.kill("SIGTERM")}catch{}}if(signalsCanAskToQuit||quitRequested){let timer;const graceOver=new Promise((resolve)=>{timer=setTimeout(resolve,TERM_GRACE_MS)});await Promise.race([exited,graceOver]);clearTimeout(timer)}if(child.exitCode===null&&child.signalCode===null){try{child.kill("SIGKILL")}catch{}await exited}}function pidFilePath(profileDir){return path5.join(profileDir,PID_FILE_NAME)}async function writeBrowserPidFile(profileDir,pid){if(!profileDir||!pid)return;const[start,ownerStart]=await Promise.all([processStartTime(pid),ownProcessStartTime()]);mkdirSync(profileDir,{recursive:true});const record={pid,start,profileDir,owner:{pid:process.pid,start:ownerStart}};writeFileSync(pidFilePath(profileDir),`${JSON.stringify(record)}
|
|
1326
|
+
`,{mode:384})}function removeBrowserPidFile(profileDir,pid){if(!profileDir)return;try{const recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"));if(readProperty(recorded,"pid")!==pid)return}catch{return}rmSync(pidFilePath(profileDir),{force:true})}async function sameProcessAlive(pid,start){if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return null;if(!isPidAlive(pid))return false;if(start===null||start===undefined)return null;const now=await processStartTime(pid);if(now===null)return null;return now===start}async function reapOrphanedBrowser(profileDir){if(!profileDir)return;let recorded;try{recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"))}catch{return}const pid=readProperty(recorded,"pid");const start=readProperty(recorded,"start");const owner=readProperty(recorded,"owner");if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0){rmSync(pidFilePath(profileDir),{force:true});return}const browserAlive=await sameProcessAlive(pid,start);if(browserAlive===false){rmSync(pidFilePath(profileDir),{force:true});return}if(browserAlive===null||pid===process.pid)return;const ownerAlive=owner===null||owner===undefined?await sameProcessAlive(undefined,undefined):await sameProcessAlive(readProperty(owner,"pid"),readProperty(owner,"start"));if(ownerAlive!==false)return;try{process.kill(pid,"SIGTERM")}catch{}const deadline=Date.now()+TERM_GRACE_MS;while(isPidAlive(pid)&&Date.now()<deadline)await sleep2(REAP_POLL_MS);if(isPidAlive(pid)){try{process.kill(pid,"SIGKILL")}catch{}}rmSync(pidFilePath(profileDir),{force:true})}class NulFrameReader{#parts=[];push(chunk){const frames=[];let start=0;let end;while((end=chunk.indexOf(0,start))!==-1){const tail=chunk.subarray(start,end);let frame=tail;if(this.#parts.length>0){this.#parts.push(tail);frame=Buffer.concat(this.#parts);this.#parts=[]}frames.push(frame.toString("utf8"));start=end+1}if(start<chunk.length)this.#parts.push(chunk.subarray(start));return frames}}class SerialEmitter{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;var EXIT_STDERR_DRAIN_MS=1000;class PipeCdpClient{#child;#writeStream;#readStream;#frames=new NulFrameReader;#seq=1;#pending=new Map;#closedSessions=new Set;#sessionTargets=new Map;#launch;#launchId;#launchedAt=0;#receivedBytes=0;#malformedFrameCount=0;#events=new SerialEmitter;#connected=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#stderrHead="";#dialogPolicy;transportEvents=new SerialEmitter;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];const profileDir=profileDirFromArgs(this.#browserArgs);await reapOrphanedBrowser(profileDir);const child=spawn3(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{detached:browserSpawnDetached,...this.#spawnOptions,stdio});this.#child=child;const spawnFailed=new Promise((resolve)=>child.once("error",resolve));if(child.pid===undefined){const error=await spawnFailed;this.#child=undefined;throw error}const browserPid=child.pid;const launch={};this.#launch=launch;const owned=(listener)=>(...args)=>{if(this.#launch===launch)listener(...args)};this.#launchId=`${this.logId}:${browserPid}`;this.#launchedAt=performance.now();this.#receivedBytes=0;this.#malformedFrameCount=0;this.#frames=new NulFrameReader;this.#sessionTargets.clear();this.#closedSessions.clear();child.once("exit",()=>removeBrowserPidFile(profileDir,browserPid));this.#stdioTail="";this.#stderrHead="";const stderr=child.stderr;for(const stream of[child.stdout,stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT);if(stream===stderr&&this.#stderrHead.length<STDIO_TAIL_LIMIT&&!this.#stderrHead.trimStart().includes(`
|
|
1327
|
+
`)){this.#stderrHead=(this.#stderrHead+chunk).slice(0,STDIO_TAIL_LIMIT)}});stream.on("error",()=>{})}const writeStream=child.stdio[3];const readStream=child.stdio[4];if(!writeStream||!("write"in writeStream))throw new TypeError("CDP pipe write stream (fd 3) is missing");if(!readStream||!("read"in readStream))throw new TypeError("CDP pipe read stream (fd 4) is missing");this.#writeStream=writeStream;this.#readStream=readStream;readStream.on("data",owned((chunk)=>this.#onData(chunk)));for(const event of["end","close"]){readStream.on(event,owned(()=>this.#failCommands(CdpPipeClosedError,`CDP pipe read stream ${event}`)))}for(const stream of[writeStream,readStream]){stream.on("error",owned((error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`))))}child.on("exit",owned(()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})}));try{await writeBrowserPidFile(profileDir,browserPid)}catch(error){await this.#quitFailedLaunch();throw error}this.#connected=true;try{await this.#awaitReady();await this.#dispatch("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}catch(error){await this.#quitFailedLaunch();throw error}}async#quitFailedLaunch(){const child=this.#child;this.#child=undefined;this.#connected=false;this.#failAll(Error("CDP pipe launch failed"));if(child===undefined)throw new TypeError("Cannot read properties of undefined (reading 'pid')");await terminateChild(child)}async#awaitReady(){const child=this.#child;if(child===undefined)throw new TypeError("Cannot read properties of undefined (reading 'exitCode')");const deadline=Date.now()+this.#readinessTimeoutMs;const exited=child.exitCode!==null||child.signalCode!==null?Promise.resolve("exited"):new Promise((resolve)=>child.once("exit",()=>resolve("exited")));let lastError;while(Date.now()<deadline){try{const outcome=await Promise.race([this.#dispatch("Browser.getVersion",undefined,undefined,{timeoutMs:1000}),exited]);if(outcome!=="exited")return}catch(error){lastError=error}if(child.exitCode!==null||child.signalCode!==null)throw await this.#exitedBeforeReady(child,deadline);let timer;try{await Promise.race([new Promise((resolve)=>{timer=setTimeout(resolve,100)}),exited])}finally{clearTimeout(timer)}}const reason=lastError?String(readProperty(lastError,"message")??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`
|
|
1471
1328
|
Browser stdio tail:
|
|
1472
|
-
${tail}`:""))}async
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
`,"utf8")}finally{await handle.close()}await chmod3(metadataPath,384)}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path7.resolve(profileDir);const metadataPath=path7.join(resolvedProfile,METADATA_FILE);await mkdir4(resolvedProfile,{recursive:true,mode:448});await chmod3(resolvedProfile,448);const requested=fingerprintSeed===undefined?null:normalizeFingerprintSeed(fingerprintSeed);let stored=await readMetadata(metadataPath);if(stored===null){const candidate=requested??normalizeFingerprintSeed(randomSeed());try{await writeMetadata(metadataPath,candidate);stored=candidate}catch(error){if(error?.code!=="EEXIST")throw error;stored=await readMetadata(metadataPath);if(stored===null){throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`)}}}if(requested!==null&&requested!==stored){throw new Error(`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`)}await chmod3(metadataPath,384);return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path7.join(os2.homedir(),".cloakbrowser")}={}){const candidates=globSync(path7.join(path7.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).sort();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path7.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function assertCloakLaunchClear({browserPath,profileDir,registryRoot,legacyProbeUrl=LEGACY_CLOAK_PROBE_URL,probeTimeoutMs}){const records=await listInstances({registryRoot,probeTimeoutMs});for(const record of records){if(!record.alive||!record.responsive)continue;if(!record.profileDir)continue;if(path7.resolve(record.profileDir)===path7.resolve(profileDir))continue;if(path7.resolve(record.browserPath)!==path7.resolve(browserPath))continue;throw new Error(`CloakBrowser allows one instance: "${record.name}" (pid ${record.pid}, profile ${record.profileDir}) is live — connectNamed("${record.name}") to reuse it or close it first`)}const legacyHost=new URL(legacyProbeUrl).host;const explainedByRecord=records.some((record)=>record.alive&&record.responsive&&new URL(record.endpoint).host===legacyHost);if(explainedByRecord)return;try{const response=await fetch(new URL("/json/version",legacyProbeUrl),{signal:AbortSignal.timeout(probeTimeoutMs??LEGACY_PROBE_TIMEOUT_MS)});if(response.ok){throw new Error(`an unregistered CloakBrowser is answering on ${legacyProbeUrl} — attach with connect("${legacyProbeUrl}") or close it before launching`)}}catch(error){const unreachable=error instanceof TypeError||error?.name==="TimeoutError"||error?.name==="AbortError";if(!unreachable)throw error}}async function connectCloakProfile({browserPath=process.env.CLOAKBROWSER_BIN??findCloakBrowserPath(),profileDir=process.env.CLOAK_PROFILE_DIR??DEFAULT_PROFILE_DIR,fingerprintSeed=process.env.CLOAK_FINGERPRINT_SEED,browserArgs=[],storageRoot,name,...options}={}){const profile=await resolveCloakProfile({profileDir,fingerprintSeed});const resolvedBrowserArgs=buildCloakBrowserArgs({profileDir:profile.profileDir,fingerprintSeed:profile.fingerprintSeed,extraArgs:browserArgs});if(name===undefined){return connectPipe({browserPath,browserArgs:resolvedBrowserArgs,storageRoot:storageRoot??profile.profileDir,...options})}const{legacyProbeUrl,...connectOptions}=options;return withEngineLock(connectOptions.registryRoot,browserPath,async()=>{await assertCloakLaunchClear({browserPath,profileDir:profile.profileDir,registryRoot:connectOptions.registryRoot,legacyProbeUrl,probeTimeoutMs:connectOptions.probeTimeoutMs});return connectNamed(name,{browserPath,browserArgs:resolvedBrowserArgs,profileDir:profile.profileDir,storageRoot:storageRoot??profile.profileDir,...connectOptions})})}var SNAPSHOT_PARSE_ERROR="compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";function compactSnapshot(snapshot){const obj=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);return obj.tree}function snapshotTokens(snapshot){const text=typeof snapshot==="string"?snapshot:JSON.stringify(snapshot);return{bytes:Buffer.byteLength(text,"utf8"),estTokens:Math.ceil(Buffer.byteLength(text,"utf8")/4)}}var toolSchemas=[{name:"newTab",description:"Open a tab and return its page. Waits for interactivity.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"attachPage",description:"Attach to an existing tab by targetId from listTargets().",parameters:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"]}},{name:"page.goto",description:"Navigate the page; resolves when the page looks interactive.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"page.snapshot",description:"PRIMARY page read. Returns a compact a11y tree; interactive elements carry [ref=eN] ids for page.locator. Options: maxDepth, maxChars, interactive, showHidden, selector, ref.",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.locator",description:"Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",parameters:{type:"object",properties:{selectorOrRef:{type:"string"}},required:["selectorOrRef"]}},{name:"page.evaluate",description:"Run JS in the page and return the result.",parameters:{type:"object",properties:{expression:{type:"string"}},required:["expression"]}},{name:"page.screenshot",description:"Capture page image bytes (path, fullPage, clip, type, quality).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.pdf",description:"Print the page to PDF bytes (path, format, margin, printBackground).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"compactSnapshot",description:"Pass page.snapshot() output through this before reading: returns the raw tree without the refs map (refs resolve in-page; the map is ~54% of bytes on real pages).",parameters:{type:"object",properties:{snapshot:{}},required:["snapshot"]}},{name:"createCua",description:"Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"createCaptcha",description:"Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"createChromeApi",description:"Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",parameters:{type:"object",properties:{connection:{},options:{type:"object"}},required:["connection"]}},{name:"injectCookies",description:"Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",parameters:{type:"object",properties:{page:{},cookies:{type:"array"}},required:["page","cookies"]}},{name:"createNetworkSnoop",description:"Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",parameters:{type:"object",properties:{page:{},match:{},bodies:{type:"boolean"},maxEntries:{type:"number"},maxBodyBytes:{type:"number"}},required:["page"]}},{name:"snoop.waitFor",description:"Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",parameters:{type:"object",properties:{match:{},timeoutMs:{type:"number"}}}},{name:"snoop.popJson",description:"Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",parameters:{type:"object",properties:{}}},{name:"snoop.summary",description:"Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",parameters:{type:"object",properties:{max:{type:"number"}}}},{name:"collectWhileScrolling",description:"Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",parameters:{type:"object",properties:{page:{},snoop:{},minItems:{type:"number"},maxScrolls:{type:"number"},extract:{},scroll:{type:"string",enum:["wheel","end"]},settleMs:{type:"number"}},required:["page","snoop"]}},{name:"createTrace",description:"Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",parameters:{type:"object",properties:{page:{},dir:{type:"string"},screenshots:{type:"boolean"},network:{type:"boolean"},console:{type:"boolean"},maxBodyBytes:{type:"number"},events:{}},required:["page","dir"]}},{name:"trace.step",description:"Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",parameters:{type:"object",properties:{name:{type:"string"},fn:{}},required:["name","fn"]}},{name:"trace.stop",description:"Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",parameters:{type:"object",properties:{}}},{name:"reconcileFrames",description:"Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"snapshotWithFrames",description:"Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"connectPipe.dialogPolicy",description:"Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",parameters:{type:"object",properties:{accept:{type:"boolean"},promptText:{type:"string"}}}},{name:"requestHuman",description:"Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",parameters:{type:"object",properties:{page:{},prompt:{type:"string"},until:{},timeoutMs:{type:"number"},pollMs:{type:"number"},signal:{}},required:["page"]}},{name:"describeLayers",description:"Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",parameters:{type:"object",properties:{page:{},grid:{type:"number"}},required:["page"]}},{name:"snapshotWithLayers",description:"Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"emulate",description:"Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",parameters:{type:"object",properties:{page:{},preset:{}},required:["page","preset"]}},{name:"createRoutes",description:"Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"route.continue",description:"Continue an intercepted request, optionally overriding url, method, headers, or postData.",parameters:{type:"object",properties:{url:{type:"string"},method:{type:"string"},headers:{type:"object"},postData:{}}}},{name:"route.fulfill",description:"Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",parameters:{type:"object",properties:{status:{type:"number"},headers:{type:"object"},contentType:{type:"string"},body:{}}}},{name:"route.abort",description:"Abort an intercepted request with a CDP errorReason (defaults to Failed).",parameters:{type:"object",properties:{reason:{type:"string"}}}}];var MODIFIER_KEYS2=new Set(["Alt","Control","Meta","Shift"]);function splitModifiers(keys=[]){const modifiers=keys.filter((key)=>MODIFIER_KEYS2.has(key)||/^(cmd|command|ctrl|option|controlormeta)$/i.test(key));const rest=keys.filter((key)=>!modifiers.includes(key));return{modifiers,rest}}function createCua(page){async function holdModifiers(keys,fn){const{modifiers}=splitModifiers(keys);for(const key of modifiers)await page.keyboard.down(key);try{return await fn()}finally{for(const key of[...modifiers].reverse())await page.keyboard.up(key)}}return{page,async click({x,y,button="left",keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{button}))},async doubleClick({x,y,keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{clickCount:2}))},async drag({path,keys}){if(!Array.isArray(path)||path.length<2){throw new TypeError("cua.drag requires path with at least two points")}await holdModifiers(keys,async()=>{const[first,...rest]=path;await page.mouse.move(first.x,first.y);await page.mouse.down();try{for(const point of rest)await page.mouse.move(point.x,point.y)}finally{await page.mouse.up()}})},async getVisibleScreenshot(){const buffer=await page.screenshot({type:"png"});return buffer.toString("base64")},async keypress({keys}){if(!Array.isArray(keys)||keys.length===0){throw new TypeError("cua.keypress requires a non-empty keys array")}await page.keyboard.press(keys.join("+"))},async move({x,y,keys}){await holdModifiers(keys,()=>page.mouse.move(x,y))},async scroll({x,y,scrollX,scrollY,keypress}){await holdModifiers(keypress,async()=>{await page.mouse.move(x,y);await page.mouse.wheel(scrollX,scrollY)})},async type({text}){await page.keyboard.type(text)}}}import{spawn as spawn3}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path8 from"node:path";var MAX_TIMER_MS=2147483647;var STOP=Symbol("wait stopped");async function waitForCaptcha(page,{until,timeoutMs=1e4,pollMs=100,signal}={}){if(typeof until!=="function")throw new TypeError("until must be a function");if(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>MAX_TIMER_MS){throw new RangeError("timeoutMs must be between 0 and 2147483647")}if(!Number.isFinite(pollMs)||pollMs<=0||pollMs>MAX_TIMER_MS){throw new RangeError("pollMs must be greater than 0 and at most 2147483647")}if(signal!==undefined&&(typeof signal?.aborted!=="boolean"||typeof signal.addEventListener!=="function"||typeof signal.removeEventListener!=="function")){throw new TypeError("signal must be AbortSignal-compatible")}const started=performance.now();const deadline=started+timeoutMs;const operation=new AbortController;let deadlineTimer;let pollTimer;let stop;const stopped=new Promise((resolve)=>{stop=()=>resolve(STOP)});const terminal=()=>signal?.aborted?"cancelled":performance.now()>=deadline?"timed_out":null;const result=(outcome)=>({outcome,elapsedMs:performance.now()-started});const scheduleDeadline=()=>{const remaining=deadline-performance.now();if(remaining<=0)stop();else deadlineTimer=setTimeout(scheduleDeadline,Math.ceil(remaining))};try{const initial=terminal();if(initial)return result(initial);signal?.addEventListener("abort",stop,{once:true});scheduleDeadline();for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>terminal()?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}const outcome=terminal();if(outcome)return result(outcome);if(accepted===true)return result("matched");await Promise.race([new Promise((resolve)=>{pollTimer=setTimeout(resolve,Math.ceil(Math.min(pollMs,deadline-performance.now())))}),stopped]);clearTimeout(pollTimer);const afterDelay=terminal();if(afterDelay)return result(afterDelay)}}finally{clearTimeout(deadlineTimer);clearTimeout(pollTimer);signal?.removeEventListener("abort",stop);operation.abort();stop()}}var DEFAULT_DRAG_STEPS=20;var POST_ACTION_SETTLE_MS=3000;function validatePoint(point){if(!Number.isFinite(point?.x)||!Number.isFinite(point?.y)){throw new TypeError("point coordinates must be finite numbers")}}function validateSteps(steps){if(!Number.isSafeInteger(steps)||steps<=0){throw new RangeError("steps must be a positive safe integer")}}function validateSettleMs(value){if(!Number.isFinite(value)||value<0||value>2147483647){throw new RangeError("settleMs must be between 0 and 2147483647")}}var MACOS_VISION_OCR_SWIFT=`
|
|
1329
|
+
${tail}`:""))}async#exitedBeforeReady(child,deadline){if(child.stderr){let timer;await Promise.race([finished(child.stderr).catch(()=>{}),new Promise((resolve)=>{timer=setTimeout(resolve,Math.max(0,Math.min(EXIT_STDERR_DRAIN_MS,deadline-Date.now())))})]);clearTimeout(timer)}const how=child.signalCode?`signal ${child.signalCode}`:`exit code ${child.exitCode}`;const firstLine=this.#stderrHead.split(`
|
|
1330
|
+
`).map((line)=>line.trim()).find(Boolean);const tailLines=this.#stdioTail.trim().split(`
|
|
1331
|
+
`);const repeat=tailLines.findIndex((line)=>line.trim()===firstLine);if(repeat!==-1)tailLines.splice(repeat,1);const tail=tailLines.join(`
|
|
1332
|
+
`).trim();return Error(`Browser exited before it became ready over the CDP pipe (${how})`+(firstLine?`: ${firstLine}`:"")+(tail?`
|
|
1333
|
+
Browser stdio tail:
|
|
1334
|
+
${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}async#dispatch(method,params,sessionId,opts={}){const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const entry={method,sessionId,targetId:(params===undefined||params===null?undefined:readProperty(params,"targetId"))??this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes};if(this.#closedSessions.has(sessionId)&&method!=="Page.close"){throw this.#commandError(CdpSessionDetachedError,"Page closed",entry)}const readStream=this.#readStream;if(readStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'readableEnded')");if(readStream.readableEnded||readStream.destroyed){throw this.#commandError(CdpPipeClosedError,"CDP pipe read stream closed",entry)}const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(this.#commandError(CdpCommandTimeoutError,"CDP command timeout",entry))},timeoutMs):undefined;this.#pending.set(id,{...entry,resolve,reject,timeout});if(this.#writeStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'write')");this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failCommands(CdpSessionDetachedError,"Page closed",sessionId)}async close(){const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));let quitRequested=false;if(this.#connected){await Promise.race([this.send("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).then(()=>{quitRequested=true},()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){let timer;try{await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS)})])}finally{clearTimeout(timer)}}await terminateChild(child,{quitRequested});return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#receivedBytes+=chunk.length;for(const raw of this.#frames.push(chunk)){if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{this.#malformedFrameCount++;continue}this._handleTransportMessage(msg)}}_handleTransportMessage(msg){if(typeof msg.id==="number"){const entry=this.#pending.get(msg.id);if(!entry)return;this.#pending.delete(msg.id);if(entry.timeout)clearTimeout(entry.timeout);if(msg.error){const err=Error(msg.error.message??`CDP command failed: ${entry.method}`);err.code=msg.error.code;err.data=msg.error.data;entry.reject(err)}else{if(entry.method==="Target.attachToTarget"&&msg.result?.sessionId){this.#sessionTargets.set(msg.result.sessionId,entry.targetId)}entry.resolve(msg.result)}return}if(typeof msg.method==="string"){if(msg.method==="Target.attachedToTarget"&&msg.params?.sessionId&&msg.params.targetInfo?.targetId){this.#sessionTargets.set(msg.params.sessionId,msg.params.targetInfo.targetId)}else if(msg.method==="Target.detachedFromTarget"&&msg.params?.sessionId){this.#failCommands(CdpSessionDetachedError,"CDP session detached",msg.params.sessionId);this.#sessionTargets.delete(msg.params.sessionId)}else if(msg.method==="Inspector.targetCrashed"&&msg.sessionId){this.#failCommands(CdpSessionCrashedError,"CDP session crashed",msg.sessionId,"Page.reload")}const meta={sessionId:msg.sessionId};const dialogSessionId=msg.sessionId;if(msg.method==="Page.javascriptDialogOpening"&&dialogSessionId){meta.dialog=new Dialog(msg.params,(action)=>this.send("Page.handleJavaScriptDialog",action,dialogSessionId))}const emitted=this.#events.emit(msg.method,{data:{payload:msg.params,meta}}).catch(()=>{});const{dialog}=meta;return dialog?emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,msg.params)).catch(()=>{}):undefined}}#commandError(ErrorType,reason,entry){const now=performance.now();const receivedBytesSinceSend=this.#receivedBytes-entry.receivedBytes;const details={method:entry.method,launchId:this.#launchId,sessionId:entry.sessionId??null,targetId:entry.targetId??this.#sessionTargets.get(entry.sessionId)??null,elapsedSinceLaunchMs:Math.round(now-this.#launchedAt),commandElapsedMs:Math.round(now-entry.sentAt),receivedReplyBytes:receivedBytesSinceSend>0,receivedBytesSinceSend,malformedFrameCount:this.#malformedFrameCount};const context=Object.entries(details).map(([key,value])=>`${key}=${value}`).join(", ");return new ErrorType(`${reason}: ${entry.method} (${context})`,details)}#failCommands(ErrorType,reason,sessionId,sparedMethod){for(const[id,entry]of this.#pending){if(sessionId!==undefined&&entry.sessionId!==sessionId)continue;if(entry.method===sparedMethod)continue;if(entry.timeout)clearTimeout(entry.timeout);this.#pending.delete(id);entry.reject(this.#commandError(ErrorType,reason,entry))}}#failAll(err){for(const entry of this.#pending.values()){if(entry.timeout)clearTimeout(entry.timeout);entry.reject(err)}this.#pending.clear()}}async function connectPipe({browserPath,browserArgs=[],spawnOptions,storageRoot,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}={}){const client=new PipeCdpClient({browserPath,browserArgs,spawnOptions,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();connection.browserProcess=client.childProcess;return connection}function errorCode2(error){return error===null||error===undefined?undefined:readProperty(error,"code")}var ACTIVE_PORT_POLL_MS=100;function httpEndpointFromWebSocket(webSocketUrl){const endpoint=new URL(webSocketUrl);endpoint.protocol=endpoint.protocol==="wss:"?"https:":"http:";endpoint.pathname="/";endpoint.search="";endpoint.hash="";return endpoint.toString().replace(/\/$/,"")}function parseActivePort(text){const[portLine,browserPath]=text.trim().split(/\r?\n/);const port=Number(portLine);if(!Number.isInteger(port)||port<1||port>65535)return null;return{endpoint:`http://127.0.0.1:${port}`,browserPath:browserPath?.trim()||null}}function activePortIdentity(info){return{ino:info.ino,mtimeMs:info.mtimeMs,size:info.size}}async function snapshotActivePort(profileDir){if(!profileDir)return null;const activePortPath=path6.join(profileDir,"DevToolsActivePort");try{const identity=activePortIdentity(await stat(activePortPath));return{...identity,text:await readFile4(activePortPath,"utf8")}}catch(error){if(errorCode2(error)==="ENOENT")return null;throw error}}function isSameFile(info,previous){return previous!==null&&info.ino===previous.ino&&info.mtimeMs===previous.mtimeMs&&info.size===previous.size}function assertLaunchedBrowser(child,report,webSocketDebuggerUrl){if(child.exitCode!==null||child.signalCode!==null){throw new Error(`browser exited before its DevTools endpoint ${report.endpoint} could be verified`)}const answered=new URL(webSocketDebuggerUrl).pathname;if(report.browserPath===null||answered!==report.browserPath){throw new Error(`DevTools endpoint ${report.endpoint} answers as ${answered}, not as the launched browser (${report.browserPath??"no browser id reported"})`)}}async function discoverLaunchedEndpoint(child,{profileDir,timeoutMs,previousActivePort=null}={}){const activePortPath=profileDir?path6.join(profileDir,"DevToolsActivePort"):null;return new Promise((resolve,reject)=>{let settled=false;let stderr="";let activePortWatcher;let activePortReading=false;let activePortChangedWhileReading=false;const cleanups=[];const finish=(error,endpoint)=>{if(settled)return;settled=true;for(const cleanup of cleanups.splice(0))cleanup();activePortWatcher?.close();if(error)reject(error);else resolve(endpoint)};const readActivePort=async(portPath)=>{const info=await stat(portPath);if(isSameFile(activePortIdentity(info),previousActivePort))return;const text=await readFile4(portPath,"utf8");if(previousActivePort!==null&&text===previousActivePort.text)return;const report=parseActivePort(text);if(report)finish(null,report)};const tryActivePort=async()=>{if(!activePortPath||settled)return;if(activePortReading){activePortChangedWhileReading=true;return}activePortReading=true;try{do{activePortChangedWhileReading=false;await readActivePort(activePortPath)}while(activePortChangedWhileReading&&!settled)}catch(error){if(errorCode2(error)!=="ENOENT")finish(error)}finally{activePortReading=false}};const onStderr=(chunk)=>{stderr=`${stderr}${chunk}`.slice(-16384);const match=/DevTools listening on (ws:\/\/\S+)/.exec(stderr);const webSocketUrl=match?.[1];if(webSocketUrl!==undefined){finish(null,{endpoint:httpEndpointFromWebSocket(webSocketUrl),browserPath:new URL(webSocketUrl).pathname})}else tryActivePort()};const onError=(error)=>finish(error);const onExit=(code,signal)=>{finish(new Error(`browser exited before exposing DevTools (code ${code}, signal ${signal??"none"})${stderr?`
|
|
1335
|
+
${stderr}`:""}`))};child.stderr.setEncoding("utf8");child.stderr.on("data",onStderr);child.once("error",onError);child.once("exit",onExit);cleanups.push(()=>child.stderr.off("data",onStderr));cleanups.push(()=>child.off("error",onError));cleanups.push(()=>child.off("exit",onExit));if(activePortPath&&profileDir){try{activePortWatcher=watch(profileDir,(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path6.basename(activePortPath))){tryActivePort()}})}catch(error){if(errorCode2(error)!=="ENOENT")finish(error)}tryActivePort();const poll=setInterval(()=>void tryActivePort(),ACTIVE_PORT_POLL_MS);cleanups.push(()=>clearInterval(poll))}const timeout=setTimeout(()=>{finish(new Error(`browser did not expose a DevTools endpoint within ${timeoutMs}ms${stderr?`
|
|
1336
|
+
${stderr}`:""}`))},timeoutMs);cleanups.push(()=>clearTimeout(timeout))})}var execFileAsync2=promisify2(execFile2);var WINDOWS_COMMAND_TIMEOUT_MS=15000;var ownerOnlyDirectories=new Set;var TRUSTED_TRUSTEES=new Set(["SY","S-1-5-18","BA","S-1-5-32-544","S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464","OW","S-1-3-4","CO","S-1-3-0"]);var DENY_ACE_TYPES=new Set(["D","OD","XD"]);var currentUserSid;function windowsSystemTool(name,env=process.env){return path7.win32.join(env["SystemRoot"]||env["windir"]||"C:\\Windows","System32",name)}async function readCurrentUserSid(run){const{stdout}=await run(windowsSystemTool("whoami.exe"),["/user","/fo","csv","/nh"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const sid=/"(S-1-[\d-]+)"\s*$/.exec(String(stdout).trim())?.[1];if(!sid)throw new Error(`cannot read the current user's SID from whoami: ${String(stdout).trim()}`);return sid}function cachedCurrentUserSid(){currentUserSid??=readCurrentUserSid(execFileAsync2).catch((error)=>{currentUserSid=undefined;throw error});return currentUserSid}async function readDirectoryDacl(dir,run){const scratch=await mkdtemp(path7.join(tmpdir2(),"omowright-acl-"));try{const saved=path7.join(scratch,"acl");await run(windowsSystemTool("icacls.exe"),[dir,"/save",saved,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const bytes=await readFile5(saved);const text=bytes.length>1&&bytes[1]===0?bytes.toString("utf16le"):bytes.toString("utf8");return/D:[^\r\n]*/.exec(text)?.[0]??""}finally{await rm(scratch,{recursive:true,force:true})}}function parseDacl(dacl){const head=/^D:([A-Z]*)/.exec(dacl);if(!head)return null;const aces=[];let depth=0;let start=0;let i=head[0].length;for(;i<dacl.length;i++){const c=dacl[i];if(c==='"'&&depth>0){i=dacl.indexOf('"',i+1);if(i===-1)return null}else if(c==="("){if(depth++===0)start=i+1}else if(c===")"){if(depth===0)return null;if(--depth===0)aces.push(dacl.slice(start,i).split(";"))}else if(depth===0){break}}if(depth!==0||i<dacl.length&&!dacl.startsWith("S:",i))return null;return{flags:dacl.slice("D:".length,head[0].length),aces}}function inspectDirectoryDacl(text,sid){const dacl=parseDacl(text);if(!dacl)return{parsed:false,ownerOnly:false,foreign:[]};const isUser=(trustee)=>trustee===sid||trustee==="LA"&&sid.endsWith("-500")||trustee==="LG"&&sid.endsWith("-501");const own=dacl.aces.filter((fields)=>isUser(fields[5]));const others=dacl.aces.filter(([type,,,,,trustee])=>!isUser(trustee)&&!TRUSTED_TRUSTEES.has(trustee)&&!DENY_ACE_TYPES.has(type));return{parsed:true,ownerOnly:dacl.flags.includes("P")&&others.length===0&&own.length===1&&own[0]?.[0]==="A"&&own[0]?.[1]==="OICI"&&own[0]?.[2]==="FA",foreign:[...new Set(others.filter(([,flags])=>!String.prototype.includes.call(flags,"ID")).map(([,,,,,trustee])=>trustee))]}}async function directoryIdentity(dir){const{dev,ino,birthtimeNs}=await stat2(dir,{bigint:true});return ino===0n?null:`${dev}:${ino}:${birthtimeNs}`}async function rememberOwnerOnlyDirectory(dir){const identity=await directoryIdentity(dir).catch(()=>null);if(identity)ownerOnlyDirectories.add(identity)}async function restrictToOwner(target,kind,{platform=process.platform,run}={}){if(platform!=="win32"){await chmod(target,kind==="directory"?448:384);return}const command=run??execFileAsync2;const sid=run?await readCurrentUserSid(run):await cachedCurrentUserSid();const dacl=kind==="directory"?inspectDirectoryDacl(await readDirectoryDacl(target,command),sid):null;if(dacl?.ownerOnly){await rememberOwnerOnlyDirectory(target);return}const grant=kind==="directory"?`*${sid}:(OI)(CI)F`:`*${sid}:F`;await command(windowsSystemTool("icacls.exe"),[target,"/inheritance:r","/grant:r",grant,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});if(!dacl)return;if(dacl.foreign.length>0){await command(windowsSystemTool("icacls.exe"),[target,"/remove:g",...dacl.foreign.map((trustee)=>`*${trustee}`),"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true})}if(dacl.parsed)await rememberOwnerOnlyDirectory(target)}var RECORD_VERSION=2;var DEFAULT_REGISTRY_ROOT=path8.join(os.homedir(),".local","share","omowright","instances");var DEFAULT_PROBE_TIMEOUT_MS=1000;var DEFAULT_LAUNCH_TIMEOUT_MS=1e4;var DEFAULT_CONNECT_TIMEOUT_MS=1e4;var BROWSER_CLOSE_TIMEOUT_MS=2000;var LOCK_TIMEOUT_MARGIN_MS=5000;var DEFAULT_LOCK_TIMEOUT_MS=resolveLockTimeoutMs({});function errorCode3(error){return error===null||error===undefined?undefined:readProperty(error,"code")}function normalizeName(name){if(typeof name!=="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)){throw new TypeError("instance name must start with a letter or number and contain only letters, numbers, dots, dashes, or underscores")}return name}function registryPaths(registryRoot,name){const root=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);return{root,recordPath:path8.join(root,`${name}.json`),lockPath:path8.join(root,`${name}.flock`)}}async function ensureRegistryRoot(root){await mkdir5(root,{recursive:true,mode:448});await restrictToOwner(root,"directory")}function isRecord(value,expectedName){if(value===null||typeof value!=="object")return false;const pid=readProperty(value,"pid");const endpoint=readProperty(value,"endpoint");const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");const profileDir=readProperty(value,"profileDir");const browserPath=readProperty(value,"browserPath");const startedAt=readProperty(value,"startedAt");return readProperty(value,"version")===RECORD_VERSION&&readProperty(value,"name")===expectedName&&typeof pid==="number"&&Number.isInteger(pid)&&pid>0&&typeof endpoint==="string"&&endpoint.length>0&&typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0&&(typeof profileDir==="string"||profileDir===null)&&typeof browserPath==="string"&&browserPath.length>0&&typeof startedAt==="string"&&!Number.isNaN(Date.parse(startedAt))}async function readRecord(recordPath,expectedName){let text;try{text=await readFile6(recordPath,"utf8")}catch(error){if(errorCode3(error)==="ENOENT")return{exists:false,record:null};throw error}try{const record=JSON.parse(text);return{exists:true,record:isRecord(record,expectedName)?record:null}}catch{return{exists:true,record:null}}}async function writeRecordAtomic(root,recordPath,record){const tempPath=path8.join(root,`.${record.name}.${process.pid}.${randomUUID2()}.tmp`);let handle;try{handle=await open3(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify(record,null,2)}
|
|
1337
|
+
`,"utf8");await handle.close();handle=null;await restrictToOwner(tempPath,"file");await rename(tempPath,recordPath);await restrictToOwner(recordPath,"file")}catch(error){await handle?.close().catch(()=>{});await unlink3(tempPath).catch(()=>{});throw error}}function isConnectionRefused(error){for(let cause=error;cause;cause=readProperty(cause,"cause")){const code=readProperty(cause,"code");if(code==="ECONNREFUSED"||code==="ENOTFOUND"||code==="ConnectionRefused"){return true}}return false}function isBrowserVersion(value){if(value===null||value===undefined)return false;const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");return typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0}async function probeEndpoint(endpoint,timeoutMs){const versionUrl=new URL("/json/version",endpoint);const response=await fetch(versionUrl,{signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){throw new Error(`CDP discovery request failed (${response.status} ${response.statusText})`)}const version=await response.json();if(!isBrowserVersion(version)){throw new Error("CDP discovery response lacks webSocketDebuggerUrl")}return version}function resolveConnectTimeoutMs(options){return options.connectTimeoutMs??DEFAULT_CONNECT_TIMEOUT_MS}function resolveLockTimeoutMs(options){if(options.lockTimeoutMs!==undefined)return options.lockTimeoutMs;return(options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS)+(options.probeTimeoutMs??resolveConnectTimeoutMs(options))+resolveConnectTimeoutMs(options)+LOCK_TIMEOUT_MARGIN_MS}function nameLockOptions(options){return{timeoutMs:resolveLockTimeoutMs(options)}}async function connectWithin(endpoint,options,timeoutMs){const pending=openConnection(endpoint,options);let timer;try{return await Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`timed out after ${timeoutMs}ms opening a CDP session on ${endpoint}`)),timeoutMs)})])}catch(error){pending.then((connection)=>connection.close().catch(()=>{}),()=>{});throw error}finally{clearTimeout(timer)}}async function removeOwnedRecord(recordPath,name,pid){const loaded=await readRecord(recordPath,name);if(loaded.record?.pid!==pid)return;await unlinkIfPresent(recordPath)}function connectionOptions(options,profileDir){const result={...options.connectionOptions};if(options.storageRoot!==undefined)result.storageRoot=options.storageRoot;else if(result.storageRoot===undefined&&profileDir){result.storageRoot=profileDir}if(options.client!==undefined){result.client={...result.client,...options.client}}if(options.dialogPolicy!==undefined)result.dialogPolicy=options.dialogPolicy;return result}async function askBrowserToQuit(connection,child,disconnect){if(child.exitCode!==null||child.signalCode!==null||!readProperty(connection.cdp,"isConnected")){await disconnect();return false}const exited=new Promise((resolve)=>child.once("exit",resolve));const quitRequested=await Promise.race([connection.cdp.send("Browser.close",undefined,undefined,{timeoutMs:BROWSER_CLOSE_TIMEOUT_MS}).then(()=>true,()=>false),exited.then(()=>true)]);await disconnect();if(child.exitCode===null&&child.signalCode===null){let timer;await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,BROWSER_CLOSE_TIMEOUT_MS)})]);clearTimeout(timer)}return quitRequested}async function launchNamed(name,{root,recordPath,lockPath},options){if(typeof options.browserPath!=="string"||options.browserPath.length===0){throw new TypeError(`connectNamed("${name}") requires browserPath when no healthy instance is registered`)}const browserArgs=[...options.browserArgs??[]];const profileDir=options.profileDir?path8.resolve(options.profileDir):profileDirFromArgs(browserArgs);const previousActivePort=await snapshotActivePort(profileDir);const child=spawn4(options.browserPath,[...browserArgs,"--remote-debugging-address=127.0.0.1","--remote-debugging-port=0"],{...process.platform==="win32"?{detached:true}:{},...options.spawnOptions,stdio:["ignore","ignore","pipe"]});let connection;try{const launchTimeoutMs=options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS;const report=await discoverLaunchedEndpoint(child,{profileDir,timeoutMs:launchTimeoutMs,previousActivePort});if(report===undefined)throw new TypeError("launch endpoint discovery settled without a report");const{endpoint}=report;const{webSocketDebuggerUrl}=await probeEndpoint(endpoint,launchTimeoutMs);assertLaunchedBrowser(child,report,webSocketDebuggerUrl);const opened=await connectWithin(endpoint,connectionOptions(options,profileDir),resolveConnectTimeoutMs(options));connection=opened;const record={version:RECORD_VERSION,name,pid:child.pid,endpoint,webSocketDebuggerUrl,profileDir,browserPath:path8.resolve(options.browserPath),startedAt:new Date().toISOString()};await writeRecordAtomic(root,recordPath,record);opened.browserProcess=child;const disconnect=opened.close.bind(opened);opened.close=async()=>{let failure;const quitRequested=await askBrowserToQuit(opened,child,async()=>{try{await disconnect()}catch(error){failure=error}});await terminateChild(child,{quitRequested});try{await withLock(lockPath,nameLockOptions(options),()=>removeOwnedRecord(recordPath,name,child.pid))}catch(error){failure??=error}if(failure)throw failure};return opened}catch(error){await connection?.close().catch(()=>{});await terminateChild(child);throw error}}async function withEngineLock(registryRoot,engineKey,run){const root=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const digest=createHash("sha256").update(path8.resolve(engineKey)).digest("hex").slice(0,16);const lockPath=path8.join(root,`_engine-${digest}.flock`);return withLock(lockPath,{timeoutMs:DEFAULT_LOCK_TIMEOUT_MS},run)}async function connectNamed(name,options={}){const normalizedName=normalizeName(name);const paths=registryPaths(options.registryRoot,normalizedName);await ensureRegistryRoot(paths.root);return withLock(paths.lockPath,nameLockOptions(options),()=>attachOrLaunch(normalizedName,paths,options))}async function attachOrLaunch(normalizedName,paths,options){const loaded=await readRecord(paths.recordPath,normalizedName);if(loaded.record){await restrictToOwner(paths.recordPath,"file");if(isPidAlive(loaded.record.pid)){let version=null;try{version=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??resolveConnectTimeoutMs(options))}catch(error){if(!isConnectionRefused(error)){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${readProperty(error,"message")}`,{cause:error})}}if(version?.webSocketDebuggerUrl===loaded.record.webSocketDebuggerUrl){const{webSocketDebuggerUrl}=loaded.record;const timeoutMs=resolveConnectTimeoutMs(options);try{return await acquireSharedConnection(webSocketDebuggerUrl,connectionOptions(options,loaded.record.profileDir),{open:(shared)=>connectWithin(webSocketDebuggerUrl,shared,timeoutMs),timeoutMs})}catch(error){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${readProperty(error,"message")}`,{cause:error})}}}}if(loaded.exists){await unlink3(paths.recordPath).catch((error)=>{if(errorCode3(error)!=="ENOENT")throw error})}return await launchNamed(normalizedName,paths,options)}async function listInstances(options={}){const root=path8.resolve(options.registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const entries=await readdir(root,{withFileTypes:true});const records=await Promise.all(entries.filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map(async(entry)=>{const expectedName=entry.name.slice(0,-".json".length);const recordPath=path8.join(root,entry.name);const{record}=await readRecord(recordPath,expectedName);if(!record)return null;await restrictToOwner(recordPath,"file");const alive=isPidAlive(record.pid);let responsive=false;if(alive){responsive=await probeEndpoint(record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS).then((version)=>version.webSocketDebuggerUrl===record.webSocketDebuggerUrl,()=>false)}return Object.assign(record,{alive,responsive})}));return records.filter((record)=>record!==null).toSorted((left,right)=>left.name.localeCompare(right.name))}var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);var pathFor=(platform)=>platform==="win32"?path9.win32:path9.posix;function macRow(b,home,exists){const{join}=path9.posix;const apps=[join("/Applications",`${b.app}.app`),join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path9.posix.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const{join}=path9.win32;const localAppData=env["LOCALAPPDATA"]??join(home,"AppData","Local");const programFiles=[localAppData,env["PROGRAMFILES"],env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter((root)=>Boolean(root));const userDataDir=join(localAppData,b.userData);const binary=programFiles.map((root)=>join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir(),env=process.env,exists=existsSync}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var DEFAULT_PORT_CHECK_MS=1000;class RunningBrowserError extends Error{constructor(code,message,candidates=[]){super(message);this.name="RunningBrowserError";this.code=code;this.candidates=candidates}}async function readDevToolsActivePort(userDataDir){const text=await readFile7(path10.join(userDataDir,"DevToolsActivePort"),"utf8").catch(()=>null);if(text===null)return null;const[portLine="",wsPath=""]=text.split(/\r?\n/);const port=Number(portLine.trim());if(!Number.isInteger(port)||port<=0||port>65535)return null;const pathPart=wsPath.trim();return{port,wsPath:pathPart.startsWith("/devtools/browser")?pathPart:null}}function portIsListening(port,timeoutMs){return new Promise((resolve)=>{const socket=connectTcp({host:"127.0.0.1",port});const done=(live)=>{socket.destroy();resolve(live)};socket.setTimeout(timeoutMs,()=>done(false));socket.once("connect",()=>done(true));socket.once("error",()=>done(false))})}function candidateDirs({browser,userDataDirs,catalog}){if(userDataDirs)return userDataDirs.map((dir)=>({id:path10.basename(dir),label:dir,userDataDir:dir}));const rows=catalog().filter((row)=>row.hasProfile);return browser?rows.filter((row)=>row.id===browser):rows}async function findRunningBrowser({browser,userDataDirs,portCheckMs=DEFAULT_PORT_CHECK_MS,catalog=catalogBrowsers}={}){const live=[];for(const candidate of candidateDirs({browser,userDataDirs,catalog})){const active=await readDevToolsActivePort(candidate.userDataDir);if(!active||!active.wsPath)continue;if(!await portIsListening(active.port,portCheckMs))continue;live.push({...candidate,port:active.port,wsUrl:`ws://127.0.0.1:${active.port}${active.wsPath}`})}const[only]=live;if(live.length===1&&only!==undefined)return only;if(live.length===0){throw new RunningBrowserError("not_found","No running browser has remote debugging on. Ask the user to open chrome://inspect/#remote-debugging and allow it, then retry.")}throw new RunningBrowserError("choose_browser",`More than one browser has remote debugging on (${live.map((row)=>row.id).join(", ")}); pass { browser: "<id>" }.`,live)}async function connectRunningBrowser(options={}){const found=await findRunningBrowser(options);const browser=await connect(found.wsUrl,options.connect??{});return{browser,found}}var LEGACY_PROBE_TIMEOUT_MS=1500;var MIN_FINGERPRINT_SEED=1e4;var MAX_FINGERPRINT_SEED=99999;var METADATA_FILE=".omowright-cloak.json";var DEFAULT_PROFILE_DIR=path11.join(os2.homedir(),".local","share","omowright-cloak");function errorField(error,key){return error===null||error===undefined?undefined:readProperty(error,key)}function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(typeof seed!=="number"||!Number.isInteger(seed)||seed<MIN_FINGERPRINT_SEED||seed>MAX_FINGERPRINT_SEED){throw new RangeError(`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`)}return seed}function platformFingerprint(){return process.platform==="darwin"?"macos":"windows"}function identityFlag(value){return/^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value)}function buildCloakBrowserArgs({profileDir,fingerprintSeed,extraArgs=[]}={}){const profile=path11.resolve(profileDir??DEFAULT_PROFILE_DIR);const seed=normalizeFingerprintSeed(fingerprintSeed);const conflicting=extraArgs.filter(identityFlag);if(conflicting.length>0){throw new Error(`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`)}return["--no-first-run","--no-default-browser-check","--disable-session-crashed-bubble",`--user-data-dir=${profile}`,`--fingerprint=${seed}`,`--fingerprint-platform=${platformFingerprint()}`,...extraArgs]}async function readMetadata(metadataPath){try{const parsed=JSON.parse(await readFile8(metadataPath,"utf8"));return normalizeFingerprintSeed(readProperty(parsed,"fingerprintSeed"))}catch(error){if(errorField(error,"code")==="ENOENT")return null;if(error instanceof SyntaxError){throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`)}throw error}}async function writeMetadata(metadataPath,fingerprintSeed){const handle=await open4(metadataPath,"wx",384);try{await handle.writeFile(`${JSON.stringify({fingerprintSeed},null,2)}
|
|
1338
|
+
`,"utf8")}finally{await handle.close()}try{await restrictToOwner(metadataPath,"file")}catch(error){await unlink4(metadataPath).catch(()=>{});throw error}}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path11.resolve(profileDir);const metadataPath=path11.join(resolvedProfile,METADATA_FILE);await mkdir6(resolvedProfile,{recursive:true,mode:448});await restrictToOwner(resolvedProfile,"directory");const requested=fingerprintSeed===undefined?null:normalizeFingerprintSeed(fingerprintSeed);let stored=await readMetadata(metadataPath);if(stored===null){const candidate=requested??normalizeFingerprintSeed(randomSeed());try{await writeMetadata(metadataPath,candidate);stored=candidate}catch(error){if(errorField(error,"code")!=="EEXIST")throw error;stored=await readMetadata(metadataPath);if(stored===null){throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`)}}}if(requested!==null&&requested!==stored){throw new Error(`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`)}await restrictToOwner(metadataPath,"file");return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path11.join(os2.homedir(),".cloakbrowser")}={}){const candidates=globSync(path11.join(path11.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).toSorted();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path11.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function assertCloakLaunchClear({browserPath,profileDir,registryRoot,legacyProbeUrl,probeTimeoutMs}){const records=await listInstances({registryRoot,probeTimeoutMs});for(const record of records){if(!record.alive||!record.responsive)continue;if(!record.profileDir)continue;if(path11.resolve(record.profileDir)===path11.resolve(profileDir))continue;if(path11.resolve(record.browserPath)!==path11.resolve(browserPath))continue;throw new Error(`CloakBrowser allows one instance: "${record.name}" (pid ${record.pid}, profile ${record.profileDir}) is live — connectNamed("${record.name}") to reuse it or close it first`)}if(legacyProbeUrl===undefined)return;const legacyHost=new URL(legacyProbeUrl).host;const explainedByRecord=records.some((record)=>record.alive&&record.responsive&&new URL(record.endpoint).host===legacyHost);if(explainedByRecord)return;try{const response=await fetch(new URL("/json/version",legacyProbeUrl),{signal:AbortSignal.timeout(probeTimeoutMs??LEGACY_PROBE_TIMEOUT_MS)});if(response.ok){throw new Error(`an unregistered CloakBrowser is answering on ${String(legacyProbeUrl)} — attach with connect("${String(legacyProbeUrl)}") or close it before launching`)}}catch(error){const unreachable=error instanceof TypeError||errorField(error,"name")==="TimeoutError"||errorField(error,"name")==="AbortError";if(!unreachable)throw error}}async function connectCloakProfile({browserPath=process.env["CLOAKBROWSER_BIN"]??findCloakBrowserPath(),profileDir=process.env["CLOAK_PROFILE_DIR"]??DEFAULT_PROFILE_DIR,fingerprintSeed=process.env["CLOAK_FINGERPRINT_SEED"],browserArgs=[],storageRoot,name,...options}={}){const profile=await resolveCloakProfile({profileDir,fingerprintSeed});const resolvedBrowserArgs=buildCloakBrowserArgs({profileDir:profile.profileDir,fingerprintSeed:profile.fingerprintSeed,extraArgs:browserArgs});if(name===undefined){return connectPipe({browserPath,browserArgs:resolvedBrowserArgs,storageRoot:storageRoot??profile.profileDir,...options})}const{legacyProbeUrl,...connectOptions}=options;return withEngineLock(connectOptions.registryRoot,browserPath,async()=>{await assertCloakLaunchClear({browserPath,profileDir:profile.profileDir,registryRoot:connectOptions.registryRoot,legacyProbeUrl,probeTimeoutMs:connectOptions.probeTimeoutMs});return connectNamed(name,{browserPath,browserArgs:resolvedBrowserArgs,profileDir:profile.profileDir,storageRoot:storageRoot??profile.profileDir,...connectOptions})})}var SNAPSHOT_PARSE_ERROR="compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";function isSnapshotLike(value){return typeof value==="object"&&value!==null||typeof value==="function"}function compactSnapshot(snapshot){const parsed=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;const obj=isSnapshotLike(parsed)?parsed:undefined;if(obj?.full===false&&obj.diff){const{added,changed,removed,focused}=obj.diff;const lines=[...added.map((node)=>`+ ${node.tree}`),...changed.map((node)=>`~ ${node.tree}`)];if(removed.length)lines.push(`- ${refRanges(removed)}`);lines.push(`@focused ${focused??"none"}`);return lines.join(`
|
|
1339
|
+
`)}if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);if(obj.find){const{query,matches}=obj.find;const header=`${matches} matching ${matches===1?"line":"lines"} for ${query}`;return obj.tree?`${header}:
|
|
1340
|
+
${obj.tree}`:header}return obj.tree}function refRanges(refs){const sorted=refs.map((ref)=>{const match=/^((?:f\d+)?e)(\d+)$/.exec(ref);if(match===null)throw new TypeError(`Cannot destructure a malformed snapshot ref: ${ref}`);const[,prefix="",number=""]=match;return{prefix,number:Number(number)}}).toSorted((a,b)=>a.prefix.localeCompare(b.prefix)||a.number-b.number);const ranges=[];for(let i=0;i<sorted.length;i++){const first=sorted[i];if(first===undefined)break;let last=first;let next=sorted[i+1];while(next?.prefix===first.prefix&&next.number===last.number+1){last=next;i+=1;next=sorted[i+1]}ranges.push(first===last?`${first.prefix}${first.number}`:`${first.prefix}${first.number}-${last.prefix}${last.number}`)}return ranges.join(", ")}function snapshotTokens(snapshot){const text=typeof snapshot==="string"?snapshot:JSON.stringify(snapshot);return{bytes:Buffer.byteLength(text,"utf8"),estTokens:Math.ceil(Buffer.byteLength(text,"utf8")/4)}}var toolSchemas=[{name:"newTab",description:"Open a tab and return its page. Waits for interactivity.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"attachPage",description:"Attach to an existing tab by targetId from listTargets().",parameters:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"]}},{name:"page.goto",description:"Navigate the page; resolves when the page looks interactive.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"page.snapshot",description:"PRIMARY page read. Snapshot once, act on refs, re-read with {diff:true} (fallback: full:true, reason) or {find} to search. Options: diff, find, context, maxDepth, maxChars, interactive, showHidden, selector, ref.",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.locator",description:"Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",parameters:{type:"object",properties:{selectorOrRef:{type:"string"}},required:["selectorOrRef"]}},{name:"page.evaluate",description:"Run JS in the page and return the result.",parameters:{type:"object",properties:{expression:{type:"string"}},required:["expression"]}},{name:"page.screenshot",description:"Capture page image bytes (path, fullPage, clip, type, quality).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.pdf",description:"Print the page to PDF bytes (path, format, margin, printBackground).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"compactSnapshot",description:"Compact page.snapshot() before reading: full results become raw trees; diffs use +/~ lines and removed ref ranges. Refs resolve in-page.",parameters:{type:"object",properties:{snapshot:{}},required:["snapshot"]}},{name:"createCua",description:"Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"createCaptcha",description:"Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"createChromeApi",description:"Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",parameters:{type:"object",properties:{connection:{},options:{type:"object"}},required:["connection"]}},{name:"injectCookies",description:"Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",parameters:{type:"object",properties:{page:{},cookies:{type:"array"}},required:["page","cookies"]}},{name:"createNetworkSnoop",description:"Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",parameters:{type:"object",properties:{page:{},match:{},bodies:{type:"boolean"},maxEntries:{type:"number"},maxBodyBytes:{type:"number"}},required:["page"]}},{name:"snoop.waitFor",description:"Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",parameters:{type:"object",properties:{match:{},timeoutMs:{type:"number"}}}},{name:"snoop.popJson",description:"Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",parameters:{type:"object",properties:{}}},{name:"snoop.summary",description:"Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",parameters:{type:"object",properties:{max:{type:"number"}}}},{name:"collectWhileScrolling",description:"Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",parameters:{type:"object",properties:{page:{},snoop:{},minItems:{type:"number"},maxScrolls:{type:"number"},extract:{},scroll:{type:"string",enum:["wheel","end"]},settleMs:{type:"number"}},required:["page","snoop"]}},{name:"createTrace",description:"Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",parameters:{type:"object",properties:{page:{},dir:{type:"string"},screenshots:{type:"boolean"},network:{type:"boolean"},console:{type:"boolean"},maxBodyBytes:{type:"number"},events:{}},required:["page","dir"]}},{name:"trace.step",description:"Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",parameters:{type:"object",properties:{name:{type:"string"},fn:{}},required:["name","fn"]}},{name:"trace.stop",description:"Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",parameters:{type:"object",properties:{}}},{name:"reconcileFrames",description:"Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"snapshotWithFrames",description:"Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"connectPipe.dialogPolicy",description:"Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",parameters:{type:"object",properties:{accept:{type:"boolean"},promptText:{type:"string"}}}},{name:"requestHuman",description:"Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",parameters:{type:"object",properties:{page:{},prompt:{type:"string"},until:{},timeoutMs:{type:"number"},pollMs:{type:"number"},signal:{}},required:["page"]}},{name:"describeLayers",description:"Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",parameters:{type:"object",properties:{page:{},grid:{type:"number"}},required:["page"]}},{name:"snapshotWithLayers",description:"Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"emulate",description:"Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",parameters:{type:"object",properties:{page:{},preset:{}},required:["page","preset"]}},{name:"createRoutes",description:"Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"route.continue",description:"Continue an intercepted request, optionally overriding url, method, headers, or postData.",parameters:{type:"object",properties:{url:{type:"string"},method:{type:"string"},headers:{type:"object"},postData:{}}}},{name:"route.fulfill",description:"Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",parameters:{type:"object",properties:{status:{type:"number"},headers:{type:"object"},contentType:{type:"string"},body:{}}}},{name:"route.abort",description:"Abort an intercepted request with a CDP errorReason (defaults to Failed).",parameters:{type:"object",properties:{reason:{type:"string"}}}}];var MODIFIER_KEYS2=new Set(["Alt","Control","Meta","Shift"]);function splitModifiers(keys=[]){const modifiers=keys.filter((key)=>MODIFIER_KEYS2.has(key)||/^(cmd|command|ctrl|option|controlormeta)$/i.test(key));const rest=keys.filter((key)=>!modifiers.includes(key));return{modifiers,rest}}function createCua(page){async function holdModifiers(keys,fn){const{modifiers}=splitModifiers(keys);for(const key of modifiers)await page.keyboard.down(key);try{return await fn()}finally{for(const key of modifiers.toReversed())await page.keyboard.up(key)}}return{page,async click({x,y,button="left",keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{button}))},async doubleClick({x,y,keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{clickCount:2}))},async drag({path,keys}){if(!Array.isArray(path)||path.length<2){throw new TypeError("cua.drag requires path with at least two points")}await holdModifiers(keys,async()=>{const[first,...rest]=path;await page.mouse.move(first.x,first.y);await page.mouse.down();try{for(const point of rest)await page.mouse.move(point.x,point.y)}finally{await page.mouse.up()}})},async getVisibleScreenshot(){const buffer=await page.screenshot({type:"png"});return buffer.toString("base64")},async keypress({keys}){if(!Array.isArray(keys)||keys.length===0){throw new TypeError("cua.keypress requires a non-empty keys array")}await page.keyboard.press(keys.join("+"))},async move({x,y,keys}){await holdModifiers(keys,()=>page.mouse.move(x,y))},async scroll({x,y,scrollX,scrollY,keypress}){await holdModifiers(keypress,async()=>{await page.mouse.move(x,y);await page.mouse.wheel(scrollX,scrollY)})},async type({text}){await page.keyboard.type(text)}}}var MAX_TIMER_MS=2147483647;var STOP=Symbol("wait stopped");async function waitForCaptcha(page,{until,timeoutMs=1e4,pollMs=100,signal}={}){if(typeof until!=="function")throw new TypeError("until must be a function");if(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>MAX_TIMER_MS){throw new RangeError("timeoutMs must be between 0 and 2147483647")}if(!Number.isFinite(pollMs)||pollMs<=0||pollMs>MAX_TIMER_MS){throw new RangeError("pollMs must be greater than 0 and at most 2147483647")}if(signal!==undefined&&(typeof signal?.aborted!=="boolean"||typeof signal.addEventListener!=="function"||typeof signal.removeEventListener!=="function")){throw new TypeError("signal must be AbortSignal-compatible")}const started=performance.now();const deadline=started+timeoutMs;const operation=new AbortController;let deadlineTimer;let pollTimer;const{promise:stopped,resolve:resolveStopped}=Promise.withResolvers();const stop=()=>resolveStopped(STOP);const terminal=()=>signal?.aborted?"cancelled":performance.now()>=deadline?"timed_out":null;const result=(outcome)=>({outcome,elapsedMs:performance.now()-started});const scheduleDeadline=()=>{const remaining=deadline-performance.now();if(remaining<=0)stop();else deadlineTimer=setTimeout(scheduleDeadline,Math.ceil(remaining))};try{const initial=terminal();if(initial)return result(initial);signal?.addEventListener("abort",stop,{once:true});scheduleDeadline();let evaluated=false;for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>(evaluated?terminal():signal?.aborted)?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}evaluated=true;const outcome=terminal();if(outcome)return result(outcome);if(accepted===true)return result("matched");await Promise.race([new Promise((resolve)=>{pollTimer=setTimeout(resolve,Math.ceil(Math.min(pollMs,deadline-performance.now())))}),stopped]);clearTimeout(pollTimer);const afterDelay=terminal();if(afterDelay)return result(afterDelay)}}finally{clearTimeout(deadlineTimer);clearTimeout(pollTimer);signal?.removeEventListener("abort",stop);operation.abort();stop()}}var DEFAULT_DRAG_STEPS=20;var POST_ACTION_SETTLE_MS=3000;function validatePoint(point){if(!Number.isFinite(point?.x)||!Number.isFinite(point?.y)){throw new TypeError("point coordinates must be finite numbers")}}function centerOf(bounds){validatePoint(bounds);if(!Number.isFinite(bounds.width)||bounds.width<=0||!Number.isFinite(bounds.height)||bounds.height<=0||!Number.isFinite(bounds.x+bounds.width)||!Number.isFinite(bounds.y+bounds.height)){throw new RangeError("bounds must have positive finite dimensions and finite edges")}return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}function validateSteps(steps){if(!Number.isSafeInteger(steps)||steps<=0){throw new RangeError("steps must be a positive safe integer")}}function validateSettleMs(value){if(!Number.isFinite(value)||value<0||value>2147483647){throw new RangeError("settleMs must be between 0 and 2147483647")}}var MACOS_VISION_OCR_SWIFT=`
|
|
1477
1341
|
import Vision
|
|
1478
1342
|
import AppKit
|
|
1479
1343
|
let path = CommandLine.arguments[1]
|
|
@@ -1488,33 +1352,47 @@ let text = (request.results ?? [])
|
|
|
1488
1352
|
.compactMap { $0.topCandidates(1).first?.string }
|
|
1489
1353
|
.joined(separator: " ")
|
|
1490
1354
|
print(text)
|
|
1491
|
-
`;async function macOSVisionOcr(pngBuffer){if(process.platform!=="darwin"){throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead")}const dir=mkdtempSync(path8.join(tmpdir2(),"omowright-ocr-"));try{const imagePath=path8.join(dir,"region.png");const scriptPath=path8.join(dir,"ocr.swift");writeFileSync2(imagePath,pngBuffer);writeFileSync2(scriptPath,MACOS_VISION_OCR_SWIFT);return await new Promise((resolve,reject)=>{const child=spawn3("swift",[scriptPath,imagePath],{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";child.stdout.on("data",(chunk)=>{stdout+=chunk});child.stderr.on("data",(chunk)=>{stderr+=chunk});child.on("error",reject);child.on("close",(code)=>{if(code===0){const text=stdout.trim();resolve(text.length>0?text:null)}else{reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`))}})})}finally{rmSync2(dir,{recursive:true,force:true})}}function createCaptcha(page,options={}){const ocr=options.ocr??macOSVisionOcr;function centerOf(bounds){validatePoint(bounds);if(!Number.isFinite(bounds.width)||bounds.width<=0||!Number.isFinite(bounds.height)||bounds.height<=0||!Number.isFinite(bounds.x+bounds.width)||!Number.isFinite(bounds.y+bounds.height)){throw new RangeError("bounds must have positive finite dimensions and finite edges")}return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}async function settleAndSnapshot(settleMs){await new Promise((resolve)=>setTimeout(resolve,settleMs));return compactSnapshot(await page.snapshot())}return{page,waitFor(opts){return waitForCaptcha(page,opts)},async click(bounds,opts={}){const center=centerOf(bounds);const point=opts.point===undefined?center:opts.point;validatePoint(point);if(point.x<bounds.x||point.x>=bounds.x+bounds.width||point.y<bounds.y||point.y>=bounds.y+bounds.height){throw new RangeError("point must be inside bounds")}const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);if(opts.approachSteps!==undefined){validateSteps(opts.approachSteps);await page.mouse.move(point.x,point.y,{steps:opts.approachSteps})}await page.mouse.click(point.x,point.y);return settleAndSnapshot(settleMs)},async drag(from,to,opts={}){validatePoint(from);validatePoint(to);const steps=opts.steps===undefined?DEFAULT_DRAG_STEPS:opts.steps;validateSteps(steps);const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);await page.mouse.move(from.x,from.y);await page.mouse.down();try{await page.mouse.move(to.x,to.y,{steps})}finally{await page.mouse.up()}return settleAndSnapshot(settleMs)},async readText(bounds){const buffer=await page.screenshot(bounds?{type:"png",clip:bounds}:{type:"png"});return ocr(buffer)}}}var EVENT_NAMES=["tabOpened","tabClosed","popupOpened","downloadStarted","downloadProgress","downloadFinished"];var BROWSER_EVENT_NAMES=Object.freeze([...EVENT_NAMES]);var DEFAULT_TIMEOUT=30000;var TERMINAL_LIMIT=4096;function pageTarget(info){return info?.type==="page"&&info?.targetId?info:null}function normalizeTarget(info){return{targetId:String(info.targetId),type:"page",url:info.url??"about:blank",title:info.title??"",openerId:info.openerId??null,openerFrameId:info.openerFrameId??null,browserContextId:info.browserContextId??null,attached:Boolean(info.attached),subtype:info.subtype??null}}function errorValue(value){return value instanceof Error?value:Error(String(value))}class BrowserEventBridge{#cdp;#options;#listeners=new Map;#unsubscribers=[];#targetInfos=new Map;#crashes=new Map;#downloads=new Map;#terminalDownloads=new Map;#terminal=new Set;#frameToTarget=new Map;#sessionToTarget=new Map;#waits=new Set;#disposed=false;#explicitDispose=false;ready;constructor(connection,options){if(!connection?.cdp)throw new TypeError("createEvents requires a browser connection");this.#cdp=connection.cdp;this.#options=this.#validate(options);this.#register();this.ready=this.#initialize()}#validate(options){const behavior=options.downloadBehavior??"default";if(!["default","allow","deny","allowAndName"].includes(behavior))throw new TypeError("Invalid downloadBehavior");if(behavior==="allow"&&!pathIsAbsolute(options.downloadPath))throw new TypeError("downloadPath must be an absolute path for allow");return{...options,downloadBehavior:behavior}}#register(){const on=(method,fn)=>this.#unsubscribers.push(this.#cdp.on(method,fn));on("Target.targetCreated",(info)=>this.#created(info,false));on("Target.targetDestroyed",(info)=>this.#destroyed(info));on("Target.targetInfoChanged",(info)=>{const target=pageTarget(info?.targetInfo);if(target&&this.#targetInfos.has(target.targetId))this.#targetInfos.set(target.targetId,normalizeTarget(target))});on("Target.targetCrashed",(info)=>{if(info?.targetId)this.#crashes.set(info.targetId,{status:info.status??"",errorCode:info.errorCode??0})});on("Target.attachedToTarget",(info,meta)=>{const targetId=info?.targetInfo?.targetId;const sessionId=info?.sessionId??meta?.sessionId;if(targetId&&sessionId){this.#sessionToTarget.set(sessionId,targetId)}});on("Target.detachedFromTarget",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId)this.#sessionToTarget.delete(sessionId)});on("Browser.downloadWillBegin",(info)=>this.#downloadBegin(info));on("Browser.downloadProgress",(info)=>this.#downloadProgress(info));on("Page.frameAttached",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frameId)this.#mapFrame(info.frameId,sessionId)});on("Page.frameNavigated",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frame?.id)this.#mapFrame(info.frame.id,sessionId)});if(this.#cdp.transportEvents?.on){this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected",()=>{this.#disconnectDownloads();this.#cancelWaits(Error("Browser transport disconnected"))}));this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected",()=>{this.#reconcile().catch((error)=>console.warn("[events] target reconciliation failed",error));this.#configureDownloads().catch((error)=>console.warn("[events] download reconfiguration failed",error))}))}}async#initialize(){await this.#cdp.ensureConnected();await this.#cdp.send("Target.setDiscoverTargets",{discover:true});const result=await this.#cdp.send("Target.getTargets");await this.#configureDownloads();const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#reconcile(){const result=await this.#cdp.send("Target.getTargets");const current=new Set((result?.targetInfos??[]).filter((info)=>pageTarget(info)).map((info)=>String(info.targetId)));for(const id of[...this.#targetInfos.keys()])if(!current.has(id))this.#destroyed({targetId:id});const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#configureDownloads(){const params={behavior:this.#options.downloadBehavior,eventsEnabled:true};if(this.#options.downloadBehavior==="allow"||this.#options.downloadBehavior==="allowAndName")params.downloadPath=this.#options.downloadPath;await this.#cdp.send("Browser.setDownloadBehavior",params)}#mapFrame(frameId,sessionId){const targetId=this.#sessionToTarget.get(sessionId)??[...this.#targetInfos.values()].find((info)=>info.attached&&info.targetId===sessionId)?.targetId;if(targetId)this.#frameToTarget.set(frameId,targetId)}#created(info,initial){const target=pageTarget(info?.targetInfo??info);if(!target)return;const normalized=normalizeTarget(target);const id=normalized.targetId;if(this.#targetInfos.has(id))return;this.#targetInfos.set(id,normalized);const popup=Boolean(normalized.openerId&&this.#targetInfos.has(normalized.openerId));this.#dispatch("tabOpened",{...normalized,popup,initial:Boolean(initial)});if(popup)this.#dispatch("popupOpened",{targetId:id,openerTargetId:normalized.openerId,openerFrameId:normalized.openerFrameId,url:normalized.url,title:normalized.title,initial:Boolean(initial)})}#destroyed(info){const id=info?.targetId;const last=this.#targetInfos.get(id);if(!last)return;this.#targetInfos.delete(id);const crash=this.#crashes.get(id)??null;this.#crashes.delete(id);for(const[frame,targetId]of this.#frameToTarget)if(targetId===id)this.#frameToTarget.delete(frame);this.#dispatch("tabClosed",{targetId:id,reason:crash?"crashed":"destroyed",lastKnown:last,crash})}#rememberTerminal(guid){this.#terminal.delete(guid);this.#terminal.add(guid);if(this.#terminal.size>TERMINAL_LIMIT){const oldest=this.#terminal.values().next().value;this.#terminal.delete(oldest);this.#terminalDownloads.delete(oldest)}}#downloadBegin(info={}){if(!info.guid||this.#terminal.has(info.guid))return;const record={guid:info.guid,url:info.url??null,suggestedFilename:info.suggestedFilename??"",frameId:info.frameId??null,targetId:this.#frameToTarget.get(info.frameId)??null,totalBytes:0,receivedBytes:0,filePath:null};this.#downloads.set(info.guid,record);this.#dispatch("downloadStarted",{guid:record.guid,url:record.url,suggestedFilename:record.suggestedFilename,frameId:record.frameId,targetId:record.targetId})}#downloadProgress(info={}){if(!info.guid)return;const alreadyTerminal=this.#terminal.has(info.guid);const record=this.#downloads.get(info.guid)??this.#terminalDownloads.get(info.guid);if(!record)return;Object.assign(record,{totalBytes:Number(info.totalBytes??0),receivedBytes:Number(info.receivedBytes??0),filePath:info.filePath??null});this.#dispatch("downloadProgress",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,filePath:record.filePath,targetId:record.targetId});if((info.state==="completed"||info.state==="canceled")&&!alreadyTerminal){this.#rememberTerminal(info.guid);this.#downloads.delete(info.guid);this.#terminalDownloads.set(info.guid,record);this.#dispatch("downloadFinished",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,cdpState:info.state,filePath:record.filePath,targetId:record.targetId,error:null})}}#disconnectDownloads(){if(this.#explicitDispose)return;for(const record of this.#downloads.values()){this.#rememberTerminal(record.guid);this.#dispatch("downloadFinished",{guid:record.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:"failed",cdpState:null,filePath:record.filePath,targetId:record.targetId,error:{code:"browserDisconnected",message:"Browser transport disconnected"}})}this.#downloads.clear()}#dispatch(name,payload){const listeners=[...this.#listeners.get(name)??[]];Promise.allSettled(listeners.map((listener)=>Promise.resolve().then(()=>listener(payload)))).then((results)=>results.filter((r)=>r.status==="rejected").forEach((r)=>console.warn(`[events] ${name} listener failed`,r.reason)))}on(name,listener){this.#assertName(name);if(typeof listener!=="function")throw new TypeError("listener must be a function");const set=this.#listeners.get(name)??new Set;set.add(listener);this.#listeners.set(name,set);return()=>this.off(name,listener)}off(name,listener){this.#assertName(name);this.#listeners.get(name)?.delete(listener)}#cancelWaits(error){for(const cancel of this.#waits)cancel(error);this.#waits.clear()}waitForEvent(name,options={}){this.#assertName(name);if(this.#disposed)return Promise.reject(Error("Events bridge is disposed"));const timeout=options.timeout??DEFAULT_TIMEOUT;return new Promise((resolve,reject)=>{let done=false;let timer;const off=this.on(name,async(value)=>{try{if(options.predicate&&!await options.predicate(value))return;if(done)return;done=true;clearTimeout(timer);this.#waits.delete(cancel);off();resolve(value)}catch(error){if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(errorValue(error))}}});const cancel=(error)=>{if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(error??Error("Events bridge disposed"))}};this.#waits.add(cancel);timer=setTimeout(()=>cancel(Error(`Timed out waiting for browser event "${name}"`)),timeout)})}#assertName(name){if(!EVENT_NAMES.includes(name))throw new TypeError(`Unknown browser event: ${String(name)}`)}async dispose(){if(this.#disposed)return;this.#disposed=true;this.#explicitDispose=true;this.#cancelWaits();for(const off of this.#unsubscribers)off();this.#unsubscribers=[];this.#listeners.clear();await this.ready.catch(()=>{})}}function pathIsAbsolute(value){return typeof value==="string"&&(value.startsWith("/")||/^[A-Za-z]:[\\/]/.test(value))}function createEvents(connection,options={}){return new BrowserEventBridge(connection,options)}init_agent_tabs();init_viewport();import{randomUUID as randomUUID4}from"node:crypto";import path11 from"node:path";import{mkdir as mkdir5,open as open5,readFile as readFile5,rename as rename3,lstat,chmod as chmod4}from"node:fs/promises";import{homedir}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync as mkdirSync2}from"node:fs";import path10 from"node:path";import{tmpdir as tmpdir3}from"node:os";import{existsSync,readFileSync as readFileSync3}from"node:fs";import path9 from"node:path";var DatabaseCtor;async function loadSqlite(){if(DatabaseCtor)return DatabaseCtor;try{const mod=await import("node:sqlite");DatabaseCtor=(file)=>new mod.DatabaseSync(file,{readOnly:true,readBigInts:true})}catch{const mod=await import("bun:sqlite");DatabaseCtor=(file)=>new mod.Database(file,{readonly:true})}return DatabaseCtor}var CHROME_EPOCH_OFFSET_MS=11644473600000;var chromeTimeToMs=(time)=>Number(BigInt(time)/1000n)-CHROME_EPOCH_OFFSET_MS;var msToChromeTime=(ms)=>BigInt(Math.floor((ms+CHROME_EPOCH_OFFSET_MS)*1000));var EXTENSION_BRIDGE_REQUIRED="requires the extension bridge in standalone OmOWright";function createProfileApis(profilePath){function profileDir(){if(!profilePath){throw new UnsupportedOperationError("chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })")}return path9.join(profilePath,"Default")}async function openDb(fileName){const file=path9.join(profileDir(),fileName);if(!existsSync(file))return null;const ctor=await loadSqlite();return ctor(file)}async function withDb(fileName,fn){const db=await openDb(fileName);if(!db)return[];try{return fn(db)}finally{db.close()}}function bookmarkRoots(){const file=path9.join(profileDir(),"Bookmarks");if(!existsSync(file))return[];const parsed=JSON.parse(readFileSync3(file,"utf8"));return Object.values(parsed.roots??{}).filter((node)=>node&&typeof node==="object"&&node.id)}function walkBookmarks(nodes,visit,acc=[]){for(const node of nodes){visit(node,acc);if(Array.isArray(node.children))walkBookmarks(node.children,visit,acc)}return acc}function findBookmark(id){for(const root of bookmarkRoots()){const found=walkBookmarks([root],(node,acc)=>{if(node.id===String(id))acc.push(node)});if(found.length>0)return found[0]}return null}function toBookmark(node){const out={id:node.id,title:node.name??"",type:node.type};if(node.url)out.url=node.url;if(node.date_added)out.dateAdded=chromeTimeToMs(node.date_added);if(node.children)out.children=node.children.map(toBookmark);return out}const bookmarks={async get(idOrIdList){const ids=Array.isArray(idOrIdList)?idOrIdList:[idOrIdList];return ids.map(findBookmark).filter(Boolean).map(toBookmark)},async getChildren(id){const node=findBookmark(id);return(node?.children??[]).map(toBookmark)},async getRecent(numberOfItems){const urls=walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type==="url")acc.push(node)});return urls.sort((a,b)=>Number(b.date_added??0)-Number(a.date_added??0)).slice(0,numberOfItems).map(toBookmark)},async getSubTree(id){const node=findBookmark(id);return node?[toBookmark(node)]:[]},async getTree(){return bookmarkRoots().map(toBookmark)},async search(query){const needle=typeof query==="string"?query.toLowerCase():(query.query??"").toLowerCase();const url=typeof query==="object"?query.url?.toLowerCase():undefined;const title=typeof query==="object"?query.title?.toLowerCase():undefined;return walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type!=="url")return;const name=(node.name??"").toLowerCase();const href=(node.url??"").toLowerCase();const ok=needle&&(name.includes(needle)||href.includes(needle))||url&&href.includes(url)||title&&name.includes(title);if(ok)acc.push(node)}).map(toBookmark)},async create(){throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`)},async update(){throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`)},async move(){throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`)},async remove(){throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`)},async removeTree(){throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`)}};const history={async search(query){const text=`%${query.text??""}%`;const start=query.startTime!=null?msToChromeTime(query.startTime):0n;const end=query.endTime!=null?msToChromeTime(query.endTime):99999999999999999n;const max=query.maxResults??100;return await withDb("History",(db)=>db.prepare(`SELECT id, url, title, visit_count, last_visit_time FROM urls
|
|
1355
|
+
`;async function macOSVisionOcr(pngBuffer){if(process.platform!=="darwin"){throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead")}const dir=mkdtempSync(path12.join(tmpdir3(),"omowright-ocr-"));try{const imagePath=path12.join(dir,"region.png");const scriptPath=path12.join(dir,"ocr.swift");writeFileSync2(imagePath,pngBuffer);writeFileSync2(scriptPath,MACOS_VISION_OCR_SWIFT);return await new Promise((resolve,reject)=>{const child=spawn5("swift",[scriptPath,imagePath],{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";child.stdout.on("data",(chunk)=>{stdout+=chunk});child.stderr.on("data",(chunk)=>{stderr+=chunk});child.on("error",reject);child.on("close",(code)=>{if(code===0){const text=stdout.trim();resolve(text.length>0?text:null)}else{reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`))}})})}finally{rmSync2(dir,{recursive:true,force:true})}}function createCaptcha(page,options={}){const ocr=options.ocr??macOSVisionOcr;async function settleAndSnapshot(settleMs){await new Promise((resolve)=>setTimeout(resolve,settleMs));return compactSnapshot(await page.snapshot())}return{page,waitFor(opts){return waitForCaptcha(page,opts)},async click(bounds,opts={}){const center=centerOf(bounds);const point=opts.point===undefined?center:opts.point;validatePoint(point);if(point.x<bounds.x||point.x>=bounds.x+bounds.width||point.y<bounds.y||point.y>=bounds.y+bounds.height){throw new RangeError("point must be inside bounds")}const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);if(opts.approachSteps!==undefined){validateSteps(opts.approachSteps);await page.mouse.move(point.x,point.y,{steps:opts.approachSteps})}await page.mouse.click(point.x,point.y);return settleAndSnapshot(settleMs)},async drag(from,to,opts={}){validatePoint(from);validatePoint(to);const steps=opts.steps===undefined?DEFAULT_DRAG_STEPS:opts.steps;validateSteps(steps);const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);await page.mouse.move(from.x,from.y);await page.mouse.down();try{await page.mouse.move(to.x,to.y,{steps})}finally{await page.mouse.up()}return settleAndSnapshot(settleMs)},async readText(bounds){const buffer=await page.screenshot(bounds?{type:"png",clip:bounds}:{type:"png"});return ocr(buffer)}}}var EVENT_NAMES=["tabOpened","tabClosed","popupOpened","downloadStarted","downloadProgress","downloadFinished"];var BROWSER_EVENT_NAMES=Object.freeze([...EVENT_NAMES]);var DEFAULT_TIMEOUT=30000;var TERMINAL_LIMIT=4096;function emptyListeners(){return{tabOpened:new Set,tabClosed:new Set,popupOpened:new Set,downloadStarted:new Set,downloadProgress:new Set,downloadFinished:new Set}}function isPageTarget(info){return info?.type==="page"&&Boolean(info?.targetId)}function pageTarget(info){return isPageTarget(info)?info:null}function normalizeTarget(info){return{targetId:String(info.targetId),type:"page",url:info.url??"about:blank",title:info.title??"",openerId:info.openerId??null,openerFrameId:info.openerFrameId??null,browserContextId:info.browserContextId??null,attached:Boolean(info.attached),subtype:info.subtype??null}}function errorValue(value){return value instanceof Error?value:Error(String(value))}function byOpenerLast(a,b){return Number(Boolean(a.openerId))-Number(Boolean(b.openerId))}class BrowserEventBridge{#cdp;#options;#listeners=emptyListeners();#unsubscribers=[];#targetInfos=new Map;#crashes=new Map;#downloads=new Map;#terminalDownloads=new Map;#terminal=new Set;#frameToTarget=new Map;#sessionToTarget=new Map;#waits=new Set;#disposed=false;#explicitDispose=false;ready;constructor(connection,options){if(!connection?.cdp)throw new TypeError("createEvents requires a browser connection");this.#cdp=connection.cdp;this.#options=this.#validate(options);this.#register();this.ready=this.#initialize()}#validate(options){const behavior=options.downloadBehavior??"default";if(!["default","allow","deny","allowAndName"].includes(behavior))throw new TypeError("Invalid downloadBehavior");if(behavior==="allow"&&!pathIsAbsolute(options.downloadPath))throw new TypeError("downloadPath must be an absolute path for allow");return{...options,downloadBehavior:behavior}}#register(){const on=(method,fn)=>this.#unsubscribers.push(this.#cdp.on(method,fn));on("Target.targetCreated",(info)=>this.#created(info,false));on("Target.targetDestroyed",(info)=>this.#destroyed(info));on("Target.targetInfoChanged",(info)=>{const target=pageTarget(info?.targetInfo);if(target&&this.#targetInfos.has(target.targetId))this.#targetInfos.set(target.targetId,normalizeTarget(target))});on("Target.targetCrashed",(info)=>{if(info?.targetId)this.#crashes.set(info.targetId,{status:info.status??"",errorCode:info.errorCode??0})});on("Target.attachedToTarget",(info,meta)=>{const targetId=info?.targetInfo?.targetId;const sessionId=info?.sessionId??meta?.sessionId;if(targetId&&sessionId){this.#sessionToTarget.set(sessionId,targetId)}});on("Target.detachedFromTarget",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId)this.#sessionToTarget.delete(sessionId)});on("Browser.downloadWillBegin",(info)=>this.#downloadBegin(info));on("Browser.downloadProgress",(info)=>this.#downloadProgress(info));on("Page.frameAttached",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frameId)this.#mapFrame(info.frameId,sessionId)});on("Page.frameNavigated",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frame?.id)this.#mapFrame(info.frame.id,sessionId)});if(this.#cdp.transportEvents?.on){this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected",()=>{this.#disconnectDownloads();this.#cancelWaits(Error("Browser transport disconnected"))}));this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected",()=>{this.#reconcile().catch((error)=>console.warn("[events] target reconciliation failed",error));this.#configureDownloads().catch((error)=>console.warn("[events] download reconfiguration failed",error))}))}}async#initialize(){await this.#cdp.ensureConnected();await this.#cdp.send("Target.setDiscoverTargets",{discover:true});const result=await this.#cdp.send("Target.getTargets");await this.#configureDownloads();const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort(byOpenerLast);for(const info of targets)this.#created(info,true)}async#reconcile(){const result=await this.#cdp.send("Target.getTargets");const current=new Set((result?.targetInfos??[]).filter((info)=>pageTarget(info)).map((info)=>String(info.targetId)));for(const id of[...this.#targetInfos.keys()])if(!current.has(id))this.#destroyed({targetId:id});const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort(byOpenerLast);for(const info of targets)this.#created(info,true)}async#configureDownloads(){const params={behavior:this.#options.downloadBehavior,eventsEnabled:true};if(this.#options.downloadBehavior==="allow"||this.#options.downloadBehavior==="allowAndName")params.downloadPath=this.#options.downloadPath;await this.#cdp.send("Browser.setDownloadBehavior",params)}#mapFrame(frameId,sessionId){const targetId=this.#sessionToTarget.get(sessionId)??[...this.#targetInfos.values()].find((info)=>info.attached&&info.targetId===sessionId)?.targetId;if(targetId)this.#frameToTarget.set(frameId,targetId)}#created(info,initial){const target=pageTarget(info?.targetInfo??info);if(!target)return;const normalized=normalizeTarget(target);const id=normalized.targetId;if(this.#targetInfos.has(id))return;this.#targetInfos.set(id,normalized);const popup=Boolean(normalized.openerId&&this.#targetInfos.has(normalized.openerId));this.#dispatch("tabOpened",{...normalized,popup,initial:Boolean(initial)});if(popup)this.#dispatch("popupOpened",{targetId:id,openerTargetId:normalized.openerId,openerFrameId:normalized.openerFrameId,url:normalized.url,title:normalized.title,initial:Boolean(initial)})}#destroyed(info){const id=info?.targetId;if(id===undefined)return;const last=this.#targetInfos.get(id);if(!last)return;this.#targetInfos.delete(id);const crash=this.#crashes.get(id)??null;this.#crashes.delete(id);for(const[frame,targetId]of this.#frameToTarget)if(targetId===id)this.#frameToTarget.delete(frame);this.#dispatch("tabClosed",{targetId:id,reason:crash?"crashed":"destroyed",lastKnown:last,crash})}#rememberTerminal(guid){this.#terminal.delete(guid);this.#terminal.add(guid);if(this.#terminal.size>TERMINAL_LIMIT){const oldest=this.#terminal.values().next().value;if(oldest!==undefined){this.#terminal.delete(oldest);this.#terminalDownloads.delete(oldest)}}}#downloadBegin(info={}){if(!info.guid||this.#terminal.has(info.guid))return;const targetId=info.frameId===undefined?undefined:this.#frameToTarget.get(info.frameId);const record={guid:info.guid,url:info.url??null,suggestedFilename:info.suggestedFilename??"",frameId:info.frameId??null,targetId:targetId??null,totalBytes:0,receivedBytes:0,filePath:null};this.#downloads.set(info.guid,record);this.#dispatch("downloadStarted",{guid:record.guid,url:record.url,suggestedFilename:record.suggestedFilename,frameId:record.frameId,targetId:record.targetId})}#downloadProgress(info={}){if(!info.guid)return;const alreadyTerminal=this.#terminal.has(info.guid);const record=this.#downloads.get(info.guid)??this.#terminalDownloads.get(info.guid);if(!record)return;Object.assign(record,{totalBytes:Number(info.totalBytes??0),receivedBytes:Number(info.receivedBytes??0),filePath:info.filePath??null});this.#dispatch("downloadProgress",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,filePath:record.filePath,targetId:record.targetId});if((info.state==="completed"||info.state==="canceled")&&!alreadyTerminal){this.#rememberTerminal(info.guid);this.#downloads.delete(info.guid);this.#terminalDownloads.set(info.guid,record);this.#dispatch("downloadFinished",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,cdpState:info.state,filePath:record.filePath,targetId:record.targetId,error:null})}}#disconnectDownloads(){if(this.#explicitDispose)return;for(const record of this.#downloads.values()){this.#rememberTerminal(record.guid);this.#dispatch("downloadFinished",{guid:record.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:"failed",cdpState:null,filePath:record.filePath,targetId:record.targetId,error:{code:"browserDisconnected",message:"Browser transport disconnected"}})}this.#downloads.clear()}#dispatch(name,payload){const listeners=[...this.#listeners[name]];Promise.allSettled(listeners.map((listener)=>Promise.resolve().then(()=>listener(payload)))).then((results)=>results.filter((r)=>r.status==="rejected").forEach((r)=>console.warn(`[events] ${name} listener failed`,r.reason)))}on(name,listener){this.#assertName(name);if(typeof listener!=="function")throw new TypeError("listener must be a function");this.#listeners[name].add(listener);return()=>this.off(name,listener)}off(name,listener){this.#assertName(name);this.#listeners[name].delete(listener)}#cancelWaits(error){for(const cancel of this.#waits)cancel(error);this.#waits.clear()}waitForEvent(name,options={}){this.#assertName(name);if(this.#disposed)return Promise.reject(Error("Events bridge is disposed"));const timeout=options.timeout??DEFAULT_TIMEOUT;return new Promise((resolve,reject)=>{let done=false;let timer;const off=this.on(name,async(value)=>{try{if(options.predicate&&!await options.predicate(value))return;if(done)return;done=true;clearTimeout(timer);this.#waits.delete(cancel);off();resolve(value)}catch(error){if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(errorValue(error))}}});const cancel=(error)=>{if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(error??Error("Events bridge disposed"))}};this.#waits.add(cancel);timer=setTimeout(()=>cancel(Error(`Timed out waiting for browser event "${name}"`)),timeout)})}#assertName(name){if(!EVENT_NAMES.some((known)=>known===name))throw new TypeError(`Unknown browser event: ${String(name)}`)}async dispose(){if(this.#disposed)return;this.#disposed=true;this.#explicitDispose=true;this.#cancelWaits();for(const off of this.#unsubscribers)off();this.#unsubscribers=[];this.#listeners=emptyListeners();await this.ready.catch(()=>{})}}function pathIsAbsolute(value){return typeof value==="string"&&(value.startsWith("/")||/^[A-Za-z]:[\\/]/.test(value))}function createEvents(connection,options={}){return new BrowserEventBridge(connection,options)}class ChromeProfileRowError extends TypeError{code="invalid_profile_row"}var DatabaseCtor;async function loadSqlite(){if(DatabaseCtor)return DatabaseCtor;try{const mod=await import("node:sqlite");DatabaseCtor=(file)=>new mod.DatabaseSync(file,{readOnly:true,readBigInts:true})}catch{const mod=await import("bun:sqlite");DatabaseCtor=(file)=>new mod.Database(file,{readonly:true})}return DatabaseCtor}function isSqlValue(value){return value===null||typeof value==="string"||typeof value==="number"||typeof value==="bigint"||value instanceof Uint8Array}function isSqlRow(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&Object.values(value).every(isSqlValue)}function parseSqlRow(value){if(!isSqlRow(value))throw new ChromeProfileRowError("SQLite returned an invalid profile row");return value}function selectRows(db,sql,...params){return db.prepare(sql).all(...params).map(parseSqlRow)}function parseChromeTime(value){if(value===null||value===undefined){throw new ChromeProfileRowError(`Cannot convert ${String(value)} to a BigInt`)}return value instanceof Uint8Array?value.toString():value}var CHROME_EPOCH_OFFSET_MS=11644473600000;var chromeTimeToMs=(time)=>Number(BigInt(time)/1000n)-CHROME_EPOCH_OFFSET_MS;var msToChromeTime=(ms)=>BigInt(Math.floor((ms+CHROME_EPOCH_OFFSET_MS)*1000));var EXTENSION_BRIDGE_REQUIRED="requires the extension bridge in standalone OmOWright";function isBookmarkFileNode(node){return Boolean(node&&typeof node==="object"&&"id"in node&&node.id)}function walkBookmarks(nodes,visit,acc=[]){for(const node of nodes){visit(node,acc);if(Array.isArray(node.children))walkBookmarks(node.children,visit,acc)}return acc}function toBookmark(node){const out={id:node.id,title:node.name??"",type:node.type};if(node.url)out.url=node.url;if(node.date_added)out.dateAdded=chromeTimeToMs(node.date_added);if(node.children)out.children=node.children.map(toBookmark);return out}function createProfileApis(profilePath){function profileDir(){if(!profilePath){throw new UnsupportedOperationError("chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })")}return path13.join(profilePath,"Default")}async function openDb(fileName){const file=path13.join(profileDir(),fileName);if(!existsSync2(file))return null;const ctor=await loadSqlite();return ctor(file)}async function withDb(fileName,fn){const db=await openDb(fileName);if(!db)return[];try{return fn(db)}finally{db.close()}}function bookmarkRoots(){const file=path13.join(profileDir(),"Bookmarks");if(!existsSync2(file))return[];const parsed=JSON.parse(readFileSync3(file,"utf8"));return Object.values(readProperty(parsed,"roots")??{}).filter(isBookmarkFileNode)}function findBookmark(id){for(const root of bookmarkRoots()){const found=walkBookmarks([root],(node,acc)=>{if(node.id===String(id))acc.push(node)});const[first]=found;if(first)return first}return null}const bookmarks={async get(idOrIdList){const ids=Array.isArray(idOrIdList)?idOrIdList:[idOrIdList];return ids.map((id)=>findBookmark(id)).filter((node)=>node!==null).map(toBookmark)},async getChildren(id){const node=findBookmark(id);return(node?.children??[]).map(toBookmark)},async getRecent(numberOfItems){const urls=walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type==="url")acc.push(node)});return urls.toSorted((a,b)=>Number(b.date_added??0)-Number(a.date_added??0)).slice(0,numberOfItems).map(toBookmark)},async getSubTree(id){const node=findBookmark(id);return node?[toBookmark(node)]:[]},async getTree(){return bookmarkRoots().map(toBookmark)},async search(query){const needle=typeof query==="string"?query.toLowerCase():(query.query??"").toLowerCase();const url=typeof query==="object"?query.url?.toLowerCase():undefined;const title=typeof query==="object"?query.title?.toLowerCase():undefined;return walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type!=="url")return;const name=(node.name??"").toLowerCase();const href=(node.url??"").toLowerCase();const ok=needle&&(name.includes(needle)||href.includes(needle))||url&&href.includes(url)||title&&name.includes(title);if(ok)acc.push(node)}).map(toBookmark)},async create(..._args){throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`)},async update(..._args){throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`)},async move(..._args){throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`)},async remove(..._args){throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`)},async removeTree(..._args){throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`)}};const history={async search(query){const text=`%${query.text??""}%`;const start=query.startTime!=null?msToChromeTime(query.startTime):0n;const end=query.endTime!=null?msToChromeTime(query.endTime):99999999999999999n;const max=query.maxResults??100;return await withDb("History",(db)=>selectRows(db,`SELECT id, url, title, visit_count, last_visit_time FROM urls
|
|
1492
1356
|
WHERE (url LIKE ? OR title LIKE ?) AND last_visit_time BETWEEN ? AND ?
|
|
1493
|
-
ORDER BY last_visit_time DESC LIMIT
|
|
1357
|
+
ORDER BY last_visit_time DESC LIMIT ?`,text,text,start,end,max).map((row)=>({id:String(row["id"]),url:row["url"],title:row["title"]??"",visitCount:Number(row["visit_count"]),lastVisitTime:chromeTimeToMs(parseChromeTime(row["last_visit_time"]))})))},async getVisits(details){return await withDb("History",(db)=>selectRows(db,`SELECT v.id, v.visit_time, v.transition FROM visits v
|
|
1494
1358
|
JOIN urls u ON u.id = v.url WHERE u.url = ?
|
|
1495
|
-
ORDER BY v.visit_time DESC
|
|
1359
|
+
ORDER BY v.visit_time DESC`,details.url).map((row)=>({id:String(row["id"]),url:details.url,visitTime:chromeTimeToMs(parseChromeTime(row["visit_time"])),transition:Number(row["transition"])})))},async addUrl(..._args){throw new UnsupportedOperationError(`chrome.history.addUrl ${EXTENSION_BRIDGE_REQUIRED}`)},async deleteUrl(..._args){throw new UnsupportedOperationError(`chrome.history.deleteUrl ${EXTENSION_BRIDGE_REQUIRED}`)},async deleteRange(..._args){throw new UnsupportedOperationError(`chrome.history.deleteRange ${EXTENSION_BRIDGE_REQUIRED}`)}};const topSites={async get(){return(await withDb("Top Sites",(db)=>selectRows(db,`SELECT url, title, url_rank FROM top_sites ORDER BY url_rank ASC LIMIT 50`))).map((row)=>({url:row["url"],title:row["title"]??""}))}};return{bookmarks,history,topSites,withDb}}function textColumn(row,column){const value=readProperty(row,column);if(value===null||typeof value==="string")return value;throw new TypeError(`History column ${column} is not text`)}function timeColumn(row,column){const value=readProperty(row,column);if(value===null||typeof value==="string"||typeof value==="number"||typeof value==="bigint")return value;throw new TypeError(`History column ${column} is not a time value`)}var EXTENSION_BRIDGE_REQUIRED2="requires the extension bridge in standalone OmOWright";var WINDOW_FOCUS_UNKNOWN="is unavailable in standalone OmOWright: CDP exposes no window focus state; track chrome.windows.onFocusChanged through the extension bridge instead";var DOWNLOAD_TIMEOUT_MS=30000;function matchUrlPattern(url,pattern){const patterns=Array.isArray(pattern)?pattern:[pattern];return patterns.some((item)=>{if(!item.includes("*"))return url.startsWith(item);const regex=new RegExp(`^${item.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`);return regex.test(url)})}function createChromeApi(connection,options={}){const profile=createProfileApis(options.profilePath);const cdp=connection.cdp;async function pageTargets(){return(await connection.listTargets()).filter((target)=>target.type==="page")}async function toTab(target){let windowId=0;try{const win=await cdp.send("Browser.getWindowForTarget",{targetId:target.targetId??target.id});windowId=win.windowId}catch{}return{id:target.targetId??target.id,url:target.url??"",title:target.title??"",windowId,active:false,pinned:false,audible:false,discarded:false,groupId:-1,index:-1}}const tabs={async query(queryInfo={}){let targets=await pageTargets();const{url,title}=queryInfo;if(url)targets=targets.filter((t)=>matchUrlPattern(t.url??"",url));if(title)targets=targets.filter((t)=>(t.title??"").includes(title));const out=[];for(const target of targets){const tab=await toTab(target);if(queryInfo.windowId!=null&&tab.windowId!==queryInfo.windowId)continue;out.push(tab)}return out},async get(tabId){const targets=await pageTargets();const target=targets.find((t)=>(t.targetId??t.id)===tabId);if(!target)throw new Error(`No tab with id: ${tabId}`);return toTab(target)}};async function collectWindows(queryOptions={}){const byWindow=new Map;for(const target of await pageTargets()){const tab=await toTab(target);const list=byWindow.get(tab.windowId)??[];list.push(tab);byWindow.set(tab.windowId,list)}return[...byWindow.entries()].map(([windowId,windowTabs])=>{const win={id:windowId,type:"normal",state:"normal",alwaysOnTop:false,incognito:false};if(queryOptions.populate)win.tabs=windowTabs;return win})}const windows={async get(windowId,queryOptions={}){const all=await collectWindows(queryOptions);const win=all.find((item)=>item.id===windowId);if(!win)throw new Error(`No window with id: ${windowId}`);return win},async getCurrent(queryOptions={}){const[first]=await collectWindows(queryOptions);if(first===undefined)throw new Error("No browser window found");return first},async getLastFocused(){throw new UnsupportedOperationError(`chrome.windows.getLastFocused ${WINDOW_FOCUS_UNKNOWN}`)},async getAll(queryOptions={}){return collectWindows(queryOptions)}};const downloads={async search(query={}){return profile.withDb("History",(db)=>{const rows=db.prepare(`SELECT d.id, d.target_path, d.start_time, d.received_bytes, d.total_bytes, d.state,
|
|
1496
1360
|
(SELECT url FROM downloads_url_chains c WHERE c.id = d.id AND c.chain_index = 0) AS url
|
|
1497
|
-
FROM downloads d ORDER BY d.start_time DESC LIMIT ?`).all(query.limit??100);return rows.map((row)=>({id:Number(row
|
|
1361
|
+
FROM downloads d ORDER BY d.start_time DESC LIMIT ?`).all(query.limit??100);return rows.map((row)=>{const startTime=timeColumn(row,"start_time");const state=Number(readProperty(row,"state"));return{id:Number(readProperty(row,"id")),url:textColumn(row,"url")??"",filename:textColumn(row,"target_path"),startTime:startTime?new Date(chromeTimeToMs(startTime)).toISOString():null,bytesReceived:Number(readProperty(row,"received_bytes")),totalBytes:Number(readProperty(row,"total_bytes")),state:state===1?"complete":state===2?"canceled":state===3?"interrupted":"in_progress"}}).filter((item)=>!query.url||item.url.includes(query.url)).filter((item)=>{if(!query.filename)return true;if(item.filename===null)throw new TypeError("Cannot read properties of null (reading 'includes')");return item.filename.includes(query.filename)})})},async download(downloadOptions){const downloadDir=options.downloadDir??path14.join(tmpdir4(),"omowright-downloads");mkdirSync2(downloadDir,{recursive:true});const{promise:began,resolve:resolveBegin}=Promise.withResolvers();const{promise:done,resolve:resolveDone,reject:rejectDone}=Promise.withResolvers();const offBegin=cdp.on("Browser.downloadWillBegin",(params)=>resolveBegin(params));const offProgress=cdp.on("Browser.downloadProgress",(params)=>{if(params.state==="completed")resolveDone(params);else if(params.state==="canceled")rejectDone(new Error("Download was canceled"))});const timer=setTimeout(()=>rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)),DOWNLOAD_TIMEOUT_MS);const page=await connection.newTab("about:blank");try{await cdp.send("Browser.setDownloadBehavior",{behavior:"allow",downloadPath:downloadDir,eventsEnabled:true});await page.evaluate(`(() => {
|
|
1498
1362
|
const a = document.createElement("a");
|
|
1499
1363
|
a.href = ${JSON.stringify(downloadOptions.url)};
|
|
1500
1364
|
document.body.appendChild(a);
|
|
1501
1365
|
a.click();
|
|
1502
|
-
})()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path10.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var HOST_NAME="com.omowright.cloakbridge";var PROTOCOL=1;var MAX_MESSAGE_BYTES=1024*1024;var EVENT_NAMES2=Object.freeze(["notifications.shown","notifications.clicked","notifications.closed","tabGroups.created","tabGroups.updated","tabGroups.moved","tabs.activated","windows.focusChanged"]);var COMMAND_NAMES=Object.freeze(["bookmarks.create","bookmarks.move","bookmarks.remove","history.deleteUrl","history.deleteRange","tabGroups.update","debugger.attach","debugger.detach"]);var MUTATING_COMMANDS=new Set(COMMAND_NAMES);var id=string2().min(1).max(128);var uuid3=string2().regex(/^[0-9a-fA-F-]{16,128}$/);var finite=number2().finite();var color=_enum2(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]);var group=object({id:number2().int().min(0),collapsed:boolean2(),color,title:string2().max(1024).nullable().optional(),windowId:number2().int().min(-1)}).strict();var bookmarkNode=lazy(()=>object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2(),url:string2().optional(),dateAdded:finite.min(0).optional(),dateGroupModified:finite.min(0).optional(),dateLastUsed:finite.min(0).optional(),folderType:string2().optional(),syncing:boolean2().optional(),unmodifiable:string2().optional(),type:_enum2(["bookmark","folder","url"]).optional(),children:array(bookmarkNode).optional()}).strict());var empty=object({}).strict();var payloadSchemas={"notifications.shown":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.clicked":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.closed":object({notificationId:string2().min(1).max(1024),byUser:boolean2()}).strict(),"tabGroups.created":object({group}).strict(),"tabGroups.updated":object({group}).strict(),"tabGroups.moved":object({group}).strict(),"tabs.activated":object({tabId:number2().int().min(0),windowId:number2().int().min(-1),previousTabId:number2().int().min(0).optional()}).strict(),"windows.focusChanged":object({windowId:number2().int().min(-1)}).strict()};var commandParams={"bookmarks.create":object({details:object({parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2().max(8192),url:string2().url().max(8192).optional()}).strict()}).strict(),"bookmarks.move":object({details:object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional()}).strict()}).strict(),"bookmarks.remove":object({details:object({id:string2().min(1)}).strict()}).strict(),"history.deleteUrl":object({details:object({url:string2().url().max(8192)}).strict()}).strict(),"history.deleteRange":object({details:object({startTime:finite.min(0),endTime:finite.min(0)}).strict()}).strict().refine((v)=>v.details.startTime<=v.details.endTime,"startTime must not exceed endTime"),"tabGroups.update":object({details:object({groupId:number2().int().min(0),updateProperties:object({collapsed:boolean2().optional(),color:color.optional(),title:string2().max(1024).nullable().optional()}).strict().refine((v)=>Object.keys(v).length>0,"updateProperties must not be empty")}).strict()}).strict(),"debugger.attach":object({details:object({tabId:number2().int().min(0),requiredVersion:string2().regex(/^\d+\.\d+$/)}).strict()}).strict(),"debugger.detach":object({details:object({tabId:number2().int().min(0)}).strict()}).strict()};var resultSchemas={"bookmarks.create":bookmarkNode,"bookmarks.move":bookmarkNode,"bookmarks.remove":empty,"history.deleteUrl":empty,"history.deleteRange":empty,"tabGroups.update":group,"debugger.attach":object({tabId:number2().int().min(0),attached:literal(true),requiredVersion:string2()}).strict(),"debugger.detach":object({tabId:number2().int().min(0),detached:literal(true)}).strict()};var base={protocol:literal(PROTOCOL)};function unique(values,ctx){if(new Set(values).size!==values.length)ctx.addIssue({code:ZodIssueCode.custom,message:"array entries must be unique"})}var names=(allowed)=>array(_enum2([...allowed])).superRefine(unique);var ExtensionHelloSchema=object({...base,type:literal("hello"),role:literal("extension"),connectionId:id,extensionId:string2().regex(/^[a-p]{32}$/),extensionVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var HostHelloSchema=object({...base,type:literal("hello"),role:literal("host"),connectionId:id,hostName:literal(HOST_NAME),hostVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var EventSchema=object({...base,type:literal("event"),connectionId:id,seq:number2().int().min(1),occurredAt:number2().int().min(0),name:_enum2(EVENT_NAMES2),payload:record(string2(),unknown())}).strict().superRefine((v,ctx)=>{if(!payloadSchemas[v.name].safeParse(v.payload).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid event payload"})});var CommandSchema=object({...base,type:literal("command"),requestId:uuid3,name:_enum2(COMMAND_NAMES),params:record(string2(),unknown()),deadlineAt:number2().int().min(0).optional()}).strict().superRefine((v,ctx)=>{if(!commandParams[v.name].safeParse(v.params).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command parameters"})});var errorSchema=object({code:_enum2(["INVALID_MESSAGE","UNKNOWN_COMMAND","UNSUPPORTED_COMMAND","CHROME_ERROR","DEBUGGER_ERROR","NATIVE_HOST_DISCONNECTED","TIMEOUT","PAYLOAD_TOO_LARGE","INTERNAL_ERROR"]),message:string2().min(1).max(512),details:record(string2(),unknown()).optional()}).strict();var responseNames=[...COMMAND_NAMES,"protocolError"];var ResponseSchema=object({...base,type:literal("response"),requestId:uuid3,name:_enum2(responseNames),ok:boolean2(),result:unknown().optional(),error:errorSchema.optional()}).strict().superRefine((v,ctx)=>{const valid=v.ok?v.result!==undefined&&v.error===undefined&&v.name!=="protocolError":v.error!==undefined&&v.result===undefined;if(!valid)ctx.addIssue({code:ZodIssueCode.custom,message:"response must contain exactly one result or error"});if(v.ok&&resultSchemas[v.name]&&!resultSchemas[v.name].safeParse(v.result).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command result"})});class BridgeUnavailableError extends Error{constructor(message="Cloak bridge is unavailable"){super(message);this.name="BridgeUnavailableError"}}class BridgeProtocolError extends Error{constructor(message){super(message);this.name="BridgeProtocolError"}}var decoder=new TextDecoder2("utf-8",{fatal:true});var checked=(schema,value,message)=>{const result=schema.safeParse(value);if(!result.success)throw new BridgeProtocolError(message);return result.data};function schemaFor(value){if(value.type==="hello")return value.role==="host"?HostHelloSchema:ExtensionHelloSchema;if(value.type==="event")return EventSchema;if(value.type==="command")return CommandSchema;if(value.type==="response")return ResponseSchema;return null}function encodeFrame(value,maxMessageBytes=MAX_MESSAGE_BYTES){const schema=schemaFor(value);if(schema)checked(schema,value,"invalid outbound message");let json;try{json=JSON.stringify(value)}catch{throw new BridgeProtocolError("invalid JSON")}const body=Buffer.from(json,"utf8");if(body.length===0||body.length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");const frame=Buffer.allocUnsafe(4+body.length);frame.writeUInt32LE(body.length,0);body.copy(frame,4);return frame}function decodeFrames(buffer,maxMessageBytes=MAX_MESSAGE_BYTES){const frames=[];let offset=0;while(buffer.length-offset>=4){const length=buffer.readUInt32LE(offset);if(!length||length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");if(buffer.length-offset<length+4)break;const body=buffer.subarray(offset+4,offset+4+length);let text;try{text=decoder.decode(body)}catch{throw new BridgeProtocolError("invalid UTF-8")}try{frames.push(JSON.parse(text))}catch{throw new BridgeProtocolError("invalid JSON")}offset+=length+4}return{frames,remainder:buffer.subarray(offset)}}function createNativeMessagingHost({stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,extensionId,hostName=HOST_NAME,maxMessageBytes=MAX_MESSAGE_BYTES,commandTimeoutMs=30000,maxPendingWrites=256,onEvent,onDisconnect}={}){if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("a valid extensionId is required");if(!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)||hostName!==HOST_NAME)throw new BridgeProtocolError("invalid hostName");let buffer=Buffer.alloc(0),closed=false,hello=null,hostConnectionId=null,effectiveMax=maxMessageBytes,lastEventSeq=0,sequence=0,mutationBusy=false;const pending=new Map,listeners=new Map,commandQueue=[],writeQueue=[];let writing=false;const disconnect=(reason)=>{if(closed)return;closed=true;const error=reason instanceof Error?reason:new BridgeUnavailableError(reason??"native host disconnected");for(const item of pending.values()){item.cleanup?.();item.reject(error)}pending.clear();for(const item of commandQueue.splice(0)){item.cleanup?.();item.reject(error)}for(const item of writeQueue.splice(0))item.reject(error);onDisconnect?.(error)};const write=(value)=>{if(closed)return Promise.reject(new BridgeUnavailableError);let frame;try{const schema=schemaFor(value);if(!schema)throw new BridgeProtocolError("invalid outbound message type");checked(schema,value,"invalid outbound message");frame=encodeFrame(value,effectiveMax)}catch(error){return Promise.reject(error)}if(writeQueue.length+(writing?1:0)>=maxPendingWrites)return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return new Promise((resolve,reject)=>{writeQueue.push({frame,resolve,reject});pumpWrites()})};const pumpWrites=()=>{if(writing||closed||!writeQueue.length)return;writing=true;const item=writeQueue.shift();let finished=false;const done=(error)=>{if(finished)return;finished=true;writing=false;if(error){item.reject(error);disconnect(error)}else item.resolve();pumpWrites()};try{const result=stdout.write(item.frame,(error)=>done(error));if(result===false&&stdout.once)stdout.once("error",done)}catch(error){done(error)}};const pumpCommands=()=>{if(closed||mutationBusy||!commandQueue.length)return;const item=commandQueue.shift();item.started=true;mutationBusy=true;pending.set(item.requestId,item);write(item.command).catch((error)=>{if(pending.delete(item.requestId)){item.settled=true;item.cleanup();item.reject(error)}disconnect(error)})};const dispatchEvent=(event)=>{if(!hello||event.connectionId!==hello.connectionId||event.seq<=lastEventSeq||!hello.events.includes(event.name))throw new BridgeProtocolError("invalid event ordering or capability");lastEventSeq=event.seq;try{Promise.resolve(onEvent?.(event)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
`);await handle.sync()}finally{await handle.close()}await rename3(temp,file);const parsed=JSON.parse(await readFile5(file,"utf8"));await chmod4(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload.notificationId,payload.byUser]:namespace==="notifications"?[payload.notificationId]:namespace==="tabGroups"?[payload.group]:namespace==="windows"?[payload.windowId]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies)})}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){if(!DEVICE_PRESETS[presetNameOrObject]){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=DEVICE_PRESETS[presetNameOrObject]}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:"0.0.1"});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)har._errorText=entry.errorText??"";return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep3(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep3(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root?.host??null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return(el.innerText||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).sort((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
|
|
1510
|
-
|
|
1511
|
-
`)}function dispose(){if(disposed)return;disposed=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}return{pop,peek,popJson,waitFor,summary,dispose}}function globToRegExp(glob){let source="";for(const char of glob){if(char==="*")source+=".*";else if(char==="?")source+=".";else if("\\^$+{}[]()|.".includes(char))source+=`\\${char}`;else source+=char}return new RegExp(`^${source}$`)}function hasGlobChars(value){return value.includes("*")||value.includes("?")}function matches(match,request){if(typeof match==="function"){return Boolean(match({url:request.url,method:request.method,resourceType:request.resourceType,headers:request.headers}))}if(match instanceof RegExp)return match.test(request.url);if(typeof match==="string"){if(hasGlobChars(match))return globToRegExp(match).test(request.url);return request.url.includes(match)}return false}function sameMatch(left,right){if(left===right)return true;if(left instanceof RegExp&&right instanceof RegExp)return left.source===right.source&&left.flags===right.flags;return false}function toHeaderEntries(headers){if(!headers)return[];if(Array.isArray(headers)){return headers.map((header)=>({name:String(header.name),value:String(header.value??"")}))}return Object.entries(headers).map(([name,value])=>({name,value:String(value??"")}))}function encodeBody(body){if(body==null)return"";if(Buffer.isBuffer(body))return body.toString("base64");if(body instanceof Uint8Array)return Buffer.from(body).toString("base64");return Buffer.from(String(body)).toString("base64")}function buildContinue(requestId,{url,method,headers,postData}={}){const params={requestId};if(url!==undefined)params.url=url;if(method!==undefined)params.method=method;if(headers!==undefined)params.headers=toHeaderEntries(headers);if(postData!==undefined)params.postData=encodeBody(postData);return params}function buildFulfill(requestId,{status=200,headers={},contentType,body=""}={}){const responseHeaders=toHeaderEntries(headers);if(contentType!=null&&String(contentType).length>0){const hasType=responseHeaders.some((header)=>header.name.toLowerCase()==="content-type");if(!hasType)responseHeaders.push({name:"content-type",value:String(contentType)})}return{requestId,responseCode:status,responseHeaders,body:encodeBody(body)}}function createRoutes(page){if(!page?.cdp)throw new TypeError("createRoutes requires a page with cdp");const entries=[];const warned=new WeakSet;const settledIds=new Set;let enabled=false;let sessionId;let unsubscribe=null;let enablePromise=null;function warnOnce(handler,error){if(typeof handler==="function"){if(warned.has(handler))return;warned.add(handler)}if(error)console.warn("[routes] route handler failed; continuing request",error);else console.warn("[routes] route handler did not settle the request; continuing")}function findHandler(request){for(const entry of entries){if(matches(entry.match,request))return entry.handler}return}async function handlePaused(params,meta){if(!sessionId||meta?.sessionId!==sessionId)return;const requestId=params?.requestId;if(!requestId||settledIds.has(requestId))return;const request={url:params.request?.url??"",method:params.request?.method??"GET",headers:params.request?.headers??{},postData:params.request?.postData,resourceType:params.resourceType};let settled=false;const settle=(method,cdpParams)=>{if(settled)return Promise.resolve();settled=true;settledIds.add(requestId);return page.cdp.send(method,cdpParams,sessionId)};const route={request,continue(overrides={}){return settle("Fetch.continueRequest",buildContinue(requestId,overrides))},fulfill(options={}){return settle("Fetch.fulfillRequest",buildFulfill(requestId,options))},abort(errorReason="Failed"){return settle("Fetch.failRequest",{requestId,errorReason})}};const handler=findHandler(request);if(!handler){await settle("Fetch.continueRequest",{requestId});return}try{await handler(route)}catch(error){warnOnce(handler,error)}if(!settled){warnOnce(handler);await settle("Fetch.continueRequest",{requestId})}}function onPaused(params,meta){handlePaused(params,meta).catch((error)=>{console.warn("[routes] requestPaused handling failed",error)})}async function ensureEnabled(){if(enabled)return;if(!enablePromise){enablePromise=(async()=>{sessionId=await page.resolveSessionId();if(!unsubscribe)unsubscribe=page.cdp.on("Fetch.requestPaused",onPaused);await page.cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]},sessionId);enabled=true})()}try{await enablePromise}catch(error){enablePromise=null;throw error}}async function disableFetch(){const pending=enablePromise;enablePromise=null;if(pending)await pending.catch(()=>{});if(unsubscribe){unsubscribe();unsubscribe=null}if(!enabled)return;enabled=false;await page.cdp.send("Fetch.disable",{},sessionId)}async function route(match,handler){if(typeof handler!=="function")throw new TypeError("handler must be a function");entries.push({match,handler});await ensureEnabled()}async function unroute(match){if(match===undefined)entries.length=0;else{for(let index=entries.length-1;index>=0;index-=1){if(sameMatch(entries[index].match,match))entries.splice(index,1)}}if(entries.length===0)await disableFetch()}async function dispose(){entries.length=0;await disableFetch()}return{route,unroute,dispose,get enabled(){return enabled}}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>scrollTo(0,document.scrollingElement.scrollHeight));return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>document.scrollingElement.scrollHeight);if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}import{mkdir as mkdir6,writeFile as writeFile2}from"node:fs/promises";import path12 from"node:path";var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;const entries=typeof api==="function"?await api.call(page):await api?.logs?.();return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const shotDir=path12.join(dir,"screenshots");const ready=mkdir6(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog?.type??null,message:dialog?.message??"",defaultPrompt:dialog?.defaultPrompt??"",url:dialog?.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(step,phase){const file=path12.join(shotDir,`${step.seq}-${slug(step.name)}-${phase}.png`);try{await writeFile2(file,await page.screenshot({type:"png"}));step.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:step.seq,message:messageOf(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record({kind:"console",...entry});consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=[...records].sort((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile2(path12.join(dir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
`));socket.on("data",(chunk)=>{buffer+=chunk.toString("utf8");const idx=buffer.indexOf(`
|
|
1517
|
-
`)
|
|
1366
|
+
})()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path14.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(..._args){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(..._args){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(..._args){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(..._args){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var SYSTEM="S-1-5-18";var ADMINISTRATORS="S-1-5-32-544";var TRUSTED_INSTALLER="S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";var OWNER_RIGHTS="S-1-3-4";var CREATOR_OWNER="S-1-3-0";var WRITE_DATA=2;var APPEND_DATA=4;var WRITE_EA=16;var DELETE_CHILD=64;var WRITE_ATTRIBUTES=256;var DELETE=65536;var WRITE_DAC=262144;var WRITE_OWNER=524288;var GENERIC_ALL=268435456;var GENERIC_WRITE=1073741824;var MODIFY=WRITE_DATA|APPEND_DATA|WRITE_EA|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE;var FORBIDDEN={executable:MODIFY,manifest:MODIFY,final:MODIFY|DELETE_CHILD,ancestor:DELETE_CHILD|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL};var WIN32_REGISTRY_KEYS=Object.freeze({chrome:"HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",chromium:"HKCU\\Software\\Chromium\\NativeMessagingHosts"});var isWin32RegistryKey=(key)=>typeof key==="string"&&/^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);function win32PathRisk(item,kind,userSid){const trusted=new Set([userSid,SYSTEM,ADMINISTRATORS,TRUSTED_INSTALLER]);if(item?.inaccessible)return"could not be inspected";if(!item?.exists)return"is missing";if(item.reparse)return"is a symlink, junction or other reparse point";if(kind==="executable"||kind==="manifest"){if(item.directory)return"is not a regular file";if(kind==="executable"&&!/\.(exe|cmd|bat|com)$/i.test(item.path))return"is not a .exe, .cmd, .bat or .com file"}else if(!item.directory)return"is not a directory";if(!trusted.has(item.owner))return`is owned by untrusted ${item.owner}`;trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER);for(const ace of item.aces??[]){if(!readProperty(ace,"allow")||trusted.has(readProperty(ace,"sid")))continue;const mask=!readProperty(ace,"inheritOnly")?FORBIDDEN[kind]:kind==="final"&&readProperty(ace,"objectInherit")?MODIFY:0;if((Number(readProperty(ace,"rights"))&mask)!==0)return`grants ${readProperty(ace,"sid")} write access`}return null}var systemBinary=(...segments)=>{const file=path15.win32.join(process.env["SystemRoot"]||"C:\\Windows","System32",...segments);if(!existsSync3(file))throw new Error(`${file} is missing`);return file};function run(file,args){return new Promise((resolve,reject)=>{execFile3(file,args,{timeout:15000,windowsHide:true,maxBuffer:4194304,encoding:"utf8"},(error,stdout,stderr)=>{if(error&&(typeof error.code!=="number"||error.killed))reject(error);else resolve({code:error?error.code:0,stdout,stderr})})})}var INSPECT=`$ErrorActionPreference = 'Stop'
|
|
1367
|
+
$paths = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATHS__')))
|
|
1368
|
+
$sid = [System.Security.Principal.SecurityIdentifier]
|
|
1369
|
+
$items = @(foreach ($p in $paths) {
|
|
1370
|
+
try { $i = Get-Item -LiteralPath $p -Force; $acl = Get-Acl -LiteralPath $p }
|
|
1371
|
+
catch [System.Management.Automation.ItemNotFoundException] { [pscustomobject]@{ exists = $false; inaccessible = $false }; continue }
|
|
1372
|
+
catch { [pscustomobject]@{ exists = $false; inaccessible = $true }; continue }
|
|
1373
|
+
$aces = @(foreach ($r in $acl.GetAccessRules($true, $true, $sid)) { [pscustomobject]@{
|
|
1374
|
+
sid = $r.IdentityReference.Value; allow = ($r.AccessControlType -eq 'Allow'); rights = [int64]$r.FileSystemRights
|
|
1375
|
+
inheritOnly = (($r.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0)
|
|
1376
|
+
objectInherit = (($r.InheritanceFlags -band [System.Security.AccessControl.InheritanceFlags]::ObjectInherit) -ne 0) } })
|
|
1377
|
+
[pscustomobject]@{ exists = $true; inaccessible = $false; directory = [bool]$i.PSIsContainer; owner = $acl.GetOwner($sid).Value
|
|
1378
|
+
aces = $aces; reparse = (($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) }
|
|
1379
|
+
})
|
|
1380
|
+
ConvertTo-Json -Depth 6 -Compress @{ user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; items = $items }`;var reportItem=(raw,file)=>({exists:readProperty(raw,"exists"),inaccessible:readProperty(raw,"inaccessible"),directory:readProperty(raw,"directory"),owner:readProperty(raw,"owner"),reparse:readProperty(raw,"reparse"),path:file,aces:[readProperty(raw,"aces")??[]].flat()});function lastDirectory(chain){const last=chain.at(-1);if(last===undefined)throw new Error("empty directory chain");return last}var kindAt=(chain,index)=>index===chain.length-1?"final":"ancestor";async function inspectWin32Paths(paths){let out;try{const script=INSPECT.replace("__PATHS__",Buffer.from(JSON.stringify(paths),"utf8").toString("base64"));const powershell=systemBinary("WindowsPowerShell","v1.0","powershell.exe");const result=await run(powershell,["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(script,"utf16le").toString("base64")]);if(result.code!==0)throw new Error(String(result.stderr).trim()||`exit ${result.code}`);out=JSON.parse(result.stdout)}catch(error){throw new Error(`native host security could not be verified (the PowerShell ACL inspection failed; Constrained Language Mode or a policy may block it): ${readProperty(error,"message")}`,{cause:error})}const items=[readProperty(out,"items")??[]].flat();const user=readProperty(out,"user");if(typeof user!=="string"||items.length!==paths.length)throw new Error("native host security could not be verified: unexpected ACL report");return{user,items:paths.map((file,index)=>reportItem(items[index],file))}}function win32DirectoryChain(dir){const absolute=path15.win32.resolve(dir);const{root}=path15.win32.parse(absolute);if(!/^[A-Za-z]:\\$/.test(root)||dir.startsWith("\\\\"))throw new Error(`${dir} is not on a local drive-letter path`);const chain=[root];for(const part of absolute.slice(root.length).split("\\").filter(Boolean))chain.push(path15.win32.join(lastDirectory(chain),part));return chain}async function registryDefault(key,view){const result=await run(systemBinary("reg.exe"),["query",key,"/ve",...view?[`/reg:${view}`]:[]]);if(result.code!==0)return null;return/REG_SZ\s+(.*?)\s*$/m.exec(result.stdout)?.[1]??""}async function installWin32NativeHost({hostName,hostPath,dir,registryKey,force,writeManifest}){const hostChain=win32DirectoryChain(path15.win32.dirname(hostPath));win32DirectoryChain(hostPath);const dirChain=win32DirectoryChain(dir);const{user,items}=await inspectWin32Paths([hostPath,...hostChain,...dirChain]);const reject=(prefix,item,kind)=>{const risk=win32PathRisk(item,kind,user);if(risk)throw new Error(`${prefix}: ${readProperty(item,"path")} ${risk}`)};reject("hostPath must be a securely owned executable file",items[0],"executable");items.slice(1,1+hostChain.length).forEach((item,index)=>reject("hostPath directory security rejected",item,kindAt(hostChain,index)));const dirItems=items.slice(1+hostChain.length);const firstMissing=dirItems.findIndex((item)=>!item.exists&&!item.inaccessible);dirItems.slice(0,firstMissing===-1?undefined:firstMissing).forEach((item,index)=>reject("nativeMessagingHostDir security rejected",item,kindAt(dirChain,index)));if(firstMissing===0)throw new Error(`nativeMessagingHostDir security rejected: ${dirChain[0]} is missing`);const created=firstMissing>0?dirChain.slice(firstMissing):[];const file=path15.win32.join(lastDirectory(dirChain),`${hostName}.json`);const firstMade=created.length?await mkdir7(lastDirectory(dirChain),{recursive:true}):undefined;const madeDepth=firstMade===undefined?0:firstMade.replace(/^\\\\\?\\/,"").split(/[\\/]+/).filter(Boolean).length;const made=madeDepth>0&&madeDepth<=dirChain.length?dirChain.slice(madeDepth-1):[];let wroteManifest=false;try{if(created.length){const again=await inspectWin32Paths(created);if(again.user!==user)throw new Error("native host security could not be verified: user changed");again.items.forEach((item,offset)=>reject("nativeMessagingHostDir security rejected",item,kindAt(dirChain,firstMissing+offset)))}const hostKey=`${registryKey}\\${hostName}`;const machineKey=`HKLM\\${hostKey.slice("HKCU\\".length)}`;for(const view of["32","64"]){if(await registryDefault(machineKey,view)!==null)throw new Error(`${hostKey} is shadowed by a machine-level registration at ${machineKey} (/reg:${view})`)}const current=await registryDefault(hostKey);if(current!==null&¤t.toLowerCase()!==file.toLowerCase()&&!force)throw new Error(`${hostKey} already points at ${current}; use force`);const manifest=await writeManifest(file);wroteManifest=true;const written=await inspectWin32Paths([file]);const manifestRisk=win32PathRisk(written.items[0],"manifest",user);if(manifestRisk){await unlink5(file).catch(()=>{});throw new Error(`native messaging manifest security rejected: ${file} ${manifestRisk}`)}const added=await run(systemBinary("reg.exe"),["add",hostKey,"/ve","/t","REG_SZ","/d",file,"/f"]);if(added.code!==0)throw new Error(`native host registry write failed: ${String(added.stderr).trim()}`);return{path:file,manifest,registryKey:hostKey}}catch(error){if(made.length){if(wroteManifest)await unlink5(file).catch(()=>{});for(const entry of made.toReversed())await rmdir(entry).catch(()=>{})}throw error}}var HOST_NAME="com.omowright.cloakbridge";var PROTOCOL=1;var MAX_MESSAGE_BYTES=1048576;var EVENT_NAMES2=Object.freeze(["notifications.shown","notifications.clicked","notifications.closed","tabGroups.created","tabGroups.updated","tabGroups.moved","tabs.activated","windows.focusChanged"]);var COMMAND_NAMES=Object.freeze(["bookmarks.create","bookmarks.move","bookmarks.remove","history.deleteUrl","history.deleteRange","tabGroups.update","debugger.attach","debugger.detach"]);var MUTATING_COMMANDS=new Set(COMMAND_NAMES);var EVENT_SET=new Set(EVENT_NAMES2);var COMMAND_SET=new Set(COMMAND_NAMES);var id=string2().min(1).max(128);var uuid3=string2().regex(/^[0-9a-fA-F-]{16,128}$/);var finite=number2().finite();var color=_enum2(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]);var group=object({id:number2().int().min(0),collapsed:boolean2(),color,title:string2().max(1024).nullable().optional(),windowId:number2().int().min(-1)}).strict();var bookmarkNode=lazy(()=>object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2(),url:string2().optional(),dateAdded:finite.min(0).optional(),dateGroupModified:finite.min(0).optional(),dateLastUsed:finite.min(0).optional(),folderType:string2().optional(),syncing:boolean2().optional(),unmodifiable:string2().optional(),type:_enum2(["bookmark","folder","url"]).optional(),children:array(bookmarkNode).optional()}).strict());var empty=object({}).strict();var payloadSchemas={"notifications.shown":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.clicked":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.closed":object({notificationId:string2().min(1).max(1024),byUser:boolean2()}).strict(),"tabGroups.created":object({group}).strict(),"tabGroups.updated":object({group}).strict(),"tabGroups.moved":object({group}).strict(),"tabs.activated":object({tabId:number2().int().min(0),windowId:number2().int().min(-1),previousTabId:number2().int().min(0).optional()}).strict(),"windows.focusChanged":object({windowId:number2().int().min(-1)}).strict()};var commandParams={"bookmarks.create":object({details:object({parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2().max(8192),url:string2().url().max(8192).optional()}).strict()}).strict(),"bookmarks.move":object({details:object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional()}).strict()}).strict(),"bookmarks.remove":object({details:object({id:string2().min(1)}).strict()}).strict(),"history.deleteUrl":object({details:object({url:string2().url().max(8192)}).strict()}).strict(),"history.deleteRange":object({details:object({startTime:finite.min(0),endTime:finite.min(0)}).strict()}).strict().refine((v)=>v.details.startTime<=v.details.endTime,"startTime must not exceed endTime"),"tabGroups.update":object({details:object({groupId:number2().int().min(0),updateProperties:object({collapsed:boolean2().optional(),color:color.optional(),title:string2().max(1024).nullable().optional()}).strict().refine((v)=>Object.keys(v).length>0,"updateProperties must not be empty")}).strict()}).strict(),"debugger.attach":object({details:object({tabId:number2().int().min(0),requiredVersion:string2().regex(/^\d+\.\d+$/)}).strict()}).strict(),"debugger.detach":object({details:object({tabId:number2().int().min(0)}).strict()}).strict()};var resultSchemas={"bookmarks.create":bookmarkNode,"bookmarks.move":bookmarkNode,"bookmarks.remove":empty,"history.deleteUrl":empty,"history.deleteRange":empty,"tabGroups.update":group,"debugger.attach":object({tabId:number2().int().min(0),attached:literal(true),requiredVersion:string2()}).strict(),"debugger.detach":object({tabId:number2().int().min(0),detached:literal(true)}).strict()};var base={protocol:literal(PROTOCOL)};function unique(values,ctx){if(new Set(values).size!==values.length)ctx.addIssue({code:ZodIssueCode.custom,message:"array entries must be unique"})}var names=(allowed)=>array(_enum2([...allowed])).superRefine(unique);var ExtensionHelloSchema=object({...base,type:literal("hello"),role:literal("extension"),connectionId:id,extensionId:string2().regex(/^[a-p]{32}$/),extensionVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var HostHelloSchema=object({...base,type:literal("hello"),role:literal("host"),connectionId:id,hostName:literal(HOST_NAME),hostVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var EventSchema=object({...base,type:literal("event"),connectionId:id,seq:number2().int().min(1),occurredAt:number2().int().min(0),name:_enum2(EVENT_NAMES2),payload:record(string2(),unknown())}).strict().superRefine((v,ctx)=>{if(!payloadSchemas[v.name].safeParse(v.payload).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid event payload"})});var CommandSchema=object({...base,type:literal("command"),requestId:uuid3,name:_enum2(COMMAND_NAMES),params:record(string2(),unknown()),deadlineAt:number2().int().min(0).optional()}).strict().superRefine((v,ctx)=>{if(!commandParams[v.name].safeParse(v.params).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command parameters"})});var errorSchema=object({code:_enum2(["INVALID_MESSAGE","UNKNOWN_COMMAND","UNSUPPORTED_COMMAND","CHROME_ERROR","DEBUGGER_ERROR","NATIVE_HOST_DISCONNECTED","TIMEOUT","PAYLOAD_TOO_LARGE","INTERNAL_ERROR"]),message:string2().min(1).max(512),details:record(string2(),unknown()).optional()}).strict();var responseNames=[...COMMAND_NAMES,"protocolError"];var ResponseSchema=object({...base,type:literal("response"),requestId:uuid3,name:_enum2(responseNames),ok:boolean2(),result:unknown().optional(),error:errorSchema.optional()}).strict().superRefine((v,ctx)=>{const valid=v.ok?v.result!==undefined&&v.error===undefined&&v.name!=="protocolError":v.error!==undefined&&v.result===undefined;if(!valid)ctx.addIssue({code:ZodIssueCode.custom,message:"response must contain exactly one result or error"});const resultSchema=v.name==="protocolError"?undefined:resultSchemas[v.name];if(v.ok&&resultSchema&&!resultSchema.safeParse(v.result).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command result"})});var messageOf=(error)=>readProperty(error,"message");class BridgeUnavailableError extends Error{constructor(message="Cloak bridge is unavailable"){super(message);this.name="BridgeUnavailableError"}}class BridgeProtocolError extends Error{constructor(message){super(message);this.name="BridgeProtocolError"}}var decoder=new TextDecoder2("utf-8",{fatal:true});var checked=(schema,value,message)=>{const result=schema.safeParse(value);if(!result.success)throw new BridgeProtocolError(message);return result.data};function schemaFor(value){if(value["type"]==="hello")return value["role"]==="host"?HostHelloSchema:ExtensionHelloSchema;if(value["type"]==="event")return EventSchema;if(value["type"]==="command")return CommandSchema;if(value["type"]==="response")return ResponseSchema;return null}function encodeFrame(value,maxMessageBytes=MAX_MESSAGE_BYTES){const schema=schemaFor(value);if(schema)checked(schema,value,"invalid outbound message");let json;try{json=JSON.stringify(value)}catch{throw new BridgeProtocolError("invalid JSON")}const body=Buffer.from(json,"utf8");if(body.length===0||body.length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");const frame=Buffer.allocUnsafe(4+body.length);frame.writeUInt32LE(body.length,0);body.copy(frame,4);return frame}function decodeFrames(buffer,maxMessageBytes=MAX_MESSAGE_BYTES){const frames=[];let offset=0;while(buffer.length-offset>=4){const length=buffer.readUInt32LE(offset);if(!length||length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");if(buffer.length-offset<length+4)break;const body=buffer.subarray(offset+4,offset+4+length);let text;try{text=decoder.decode(body)}catch{throw new BridgeProtocolError("invalid UTF-8")}try{frames.push(JSON.parse(text))}catch{throw new BridgeProtocolError("invalid JSON")}offset+=length+4}return{frames,remainder:buffer.subarray(offset)}}function createNativeMessagingHost({stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,extensionId,hostName=HOST_NAME,maxMessageBytes=MAX_MESSAGE_BYTES,commandTimeoutMs=30000,maxPendingWrites=256,onEvent,onDisconnect}={}){if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("a valid extensionId is required");if(!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)||hostName!==HOST_NAME)throw new BridgeProtocolError("invalid hostName");let buffer=Buffer.alloc(0),closed=false,hello=null,hostConnectionId=null,effectiveMax=maxMessageBytes,lastEventSeq=0,sequence=0,mutationBusy=false;const pending=new Map,listeners=new Map,commandQueue=[],writeQueue=[];let writing=false;const disconnect=(reason)=>{if(closed)return;closed=true;const error=reason instanceof Error?reason:new BridgeUnavailableError(reason===undefined?"native host disconnected":String(reason));for(const item of pending.values()){item.cleanup?.();item.reject(error)}pending.clear();for(const item of commandQueue.splice(0)){item.cleanup?.();item.reject(error)}for(const item of writeQueue.splice(0))item.reject(error);onDisconnect?.(error)};const write=(value)=>{if(closed)return Promise.reject(new BridgeUnavailableError);let frame;try{const schema=schemaFor(value);if(!schema)throw new BridgeProtocolError("invalid outbound message type");checked(schema,value,"invalid outbound message");frame=encodeFrame(value,effectiveMax)}catch(error){return Promise.reject(error)}if(writeQueue.length+(writing?1:0)>=maxPendingWrites)return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return new Promise((resolve,reject)=>{writeQueue.push({frame,resolve,reject});pumpWrites()})};const pumpWrites=()=>{if(writing||closed||!writeQueue.length)return;writing=true;const item=writeQueue.shift();if(!item){writing=false;return}let finished=false;const done=(error)=>{if(finished)return;finished=true;writing=false;if(error){item.reject(error);disconnect(error)}else item.resolve();pumpWrites()};try{const result=stdout.write(item.frame,(error)=>done(error));if(result===false&&stdout.once)stdout.once("error",done)}catch(error){done(error)}};const pumpCommands=()=>{if(closed||mutationBusy||!commandQueue.length)return;const item=commandQueue.shift();if(!item)return;item.started=true;mutationBusy=true;pending.set(item.requestId,item);write(item.command).catch((error)=>{if(pending.delete(item.requestId)){item.settled=true;item.cleanup?.();item.reject(error)}disconnect(error)})};const dispatchEvent=(event)=>{if(!hello||event.connectionId!==hello.connectionId||event.seq<=lastEventSeq||!hello.events.includes(event.name))throw new BridgeProtocolError("invalid event ordering or capability");lastEventSeq=event.seq;try{Promise.resolve(onEvent?.(event)).catch((error)=>stderr.write?.(`bridge listener: ${messageOf(error)}
|
|
1381
|
+
`))}catch(error){stderr.write?.(`bridge listener: ${messageOf(error)}
|
|
1382
|
+
`)}for(const fn of listeners.get(event.name)??[]){try{Promise.resolve(fn(event.payload)).catch((error)=>stderr.write?.(`bridge listener: ${messageOf(error)}
|
|
1383
|
+
`))}catch(error){stderr.write?.(`bridge listener: ${messageOf(error)}
|
|
1384
|
+
`)}}};const handle=(raw)=>{if(!hello){const parsed=checked(ExtensionHelloSchema,raw,"extension hello rejected");if(parsed.extensionId!==extensionId)throw new BridgeProtocolError("extension hello rejected");hello=parsed;hostConnectionId=randomUUID3();effectiveMax=Math.min(maxMessageBytes,parsed.maxMessageBytes);lastEventSeq=0;return write({protocol:PROTOCOL,type:"hello",role:"host",connectionId:hostConnectionId,hostName,hostVersion:"0.1.0",events:EVENT_NAMES2.filter((x)=>parsed.events.includes(x)),commands:COMMAND_NAMES.filter((x)=>parsed.commands.includes(x)),maxMessageBytes:effectiveMax})}const frameType=readProperty(raw,"type");if(frameType==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(frameType==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error?.message??"protocol error"),{code:parsed.error?.code,details:parsed.error?.details});const item=pending.get(parsed.requestId);if(!item||item.name!==parsed.name)throw new BridgeProtocolError("invalid or unknown response");item.settled=true;pending.delete(parsed.requestId);item.cleanup?.();mutationBusy=false;if(parsed.ok)item.resolve(parsed.result);else item.reject(Object.assign(new Error(parsed.error?.message),{code:parsed.error?.code,details:parsed.error?.details}));pumpCommands();return}throw new BridgeProtocolError("unexpected message")};const onData=(chunk)=>{try{buffer=Buffer.concat([buffer,Buffer.from(chunk)]);const out=decodeFrames(buffer,effectiveMax);buffer=out.remainder;for(const raw of out.frames)Promise.resolve(handle(raw)).catch((error)=>{stderr.write?.(`bridge: ${messageOf(error)}
|
|
1385
|
+
`);disconnect(error)})}catch(error){stderr.write?.(`bridge: ${messageOf(error)}
|
|
1386
|
+
`);disconnect(error)}};stdin.on("data",onData);stdin.once?.("end",()=>disconnect());stdin.once?.("error",disconnect);return{get isConnected(){return!closed&&!!hello},get capabilities(){return{commands:new Set(hello?.commands??[]),events:new Set(hello?.events??[])}},send:write,request(name,params,{signal,timeoutMs=commandTimeoutMs}={}){if(!hello||!hello.commands.includes(name))return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`));let command;try{command=checked(CommandSchema,{protocol:PROTOCOL,type:"command",requestId:randomUUID3(),name,params},"invalid command parameters")}catch(error){return Promise.reject(error)}return new Promise((resolve,reject)=>{if(commandQueue.length+pending.size>=maxPendingWrites){reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return}const item={requestId:command.requestId,name,command,resolve,reject,timer:null,abortHandler:null,cleanup:()=>{},settled:false};const cleanup=()=>{if(item.timer!==null)clearTimeout(item.timer);if(item.abortHandler){signal?.removeEventListener("abort",item.abortHandler);item.abortHandler=null}};item.cleanup=cleanup;const failIndeterminate=(code,reason=null)=>{if(item.settled)return;item.settled=true;cleanup();if(pending.delete(item.requestId)||commandQueue.includes(item)){const i=commandQueue.indexOf(item);if(i>=0)commandQueue.splice(i,1);item.reject(reason??Object.assign(new Error(`bridge command timed out: ${name}`),{code}))}if(item.started)disconnect(Object.assign(new Error("mutation completion is indeterminate"),{code}))};item.timer=setTimeout(()=>failIndeterminate("TIMEOUT"),timeoutMs);if(signal?.aborted){item.settled=true;cleanup();reject(signal?.reason??Object.assign(new Error(`bridge command aborted: ${name}`),{code:"ABORT_ERR"}));return}item.abortHandler=()=>failIndeterminate("ABORT_ERR",signal?.reason);signal?.addEventListener("abort",item.abortHandler,{once:true});commandQueue.push(item);pumpCommands()})},on(name,listener){if(!EVENT_NAMES2.includes(name))throw new BridgeProtocolError("invalid event name");const set=listeners.get(name)??new Set;set.add(listener);listeners.set(name,set);return()=>{set.delete(listener);if(!set.size)listeners.delete(name)}},emitEvent(name,payload){if(!hello?.events.includes(name))return Promise.reject(new BridgeUnavailableError("unsupported bridge event"));const checkedPayload=payloadSchemas[name].safeParse(payload);if(!checkedPayload.success)return Promise.reject(new BridgeProtocolError("invalid event payload"));sequence+=1;return write({protocol:PROTOCOL,type:"event",connectionId:hostConnectionId,seq:sequence,occurredAt:Date.now(),name,payload:checkedPayload.data})},close(){disconnect("closed");stdin.removeListener?.("data",onData)}}}var NATIVE_HOST_DIRS={darwin:{chrome:["Library","Application Support","Google","Chrome"],chromium:["Library","Application Support","Chromium"]},linux:{chrome:[".config","google-chrome"],chromium:[".config","chromium"]}};function defaultNativeMessagingHostDir(browser="chrome",platform=process.platform){if(platform==="win32"){if(WIN32_REGISTRY_KEYS[browser]===undefined)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path16.win32.join(process.env["LOCALAPPDATA"]||path16.win32.join(homedir2(),"AppData","Local"),"omowright","NativeMessagingHosts",browser)}const byBrowser=NATIVE_HOST_DIRS[platform];if(!byBrowser)throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`);const segments=byBrowser[browser];if(!segments)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path16.join(homedir2(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path16.resolve(dir);const parts=absolute.split(path16.sep).filter(Boolean);let current=path16.parse(absolute).root;let final;while(parts.length){const part=parts.shift();if(part===undefined)break;current=path16.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir8(current,{mode:448});info=await lstat(current)}if(info.isSymbolicLink()){if(process.platform!=="darwin"||!["/tmp","/var","/etc"].includes(current)||info.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: symlink is not a root-owned macOS system alias`);let target,resolved;try{target=await readlink(current);resolved=await realpath(current)}catch(error){throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias could not be resolved (${String(readProperty(error,"code")??readProperty(error,"message"))})`)}if(!resolved.startsWith("/private/"))throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias target is outside /private`);parts.unshift(...target.split(path16.sep).filter(Boolean));current=path16.isAbsolute(target)?path16.parse(target).root:path16.dirname(current);continue}if(!info.isDirectory())throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: not a directory`);if(info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);const stickyRootAncestor=parts.length>0&&info.uid===0&&(info.mode&512)!==0;if(!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: writable by others`);final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);if((final.mode&63)!==0)await chmod2(absolute,448)}async function secureExecutable(hostPath){const info=await lstat(hostPath).catch(()=>null);if(!info?.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&73)===0||(info.mode&18)!==0)throw new BridgeProtocolError("hostPath must be a securely owned executable file")}async function installNativeMessagingHost({hostName=HOST_NAME,hostPath,extensionId,browser="chrome",nativeMessagingHostDir,force=false,endpointPath,registryKey}={}){const win32=process.platform==="win32";if(endpointPath!==undefined)throw new BridgeProtocolError("endpointPath is not supported");if(hostName!==HOST_NAME||!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName))throw new BridgeProtocolError("invalid hostName");if(hostPath===undefined||!path16.isAbsolute(hostPath))throw new BridgeProtocolError("hostPath must be absolute");if(!win32)await secureExecutable(hostPath);if(extensionId===undefined||!/^[a-p]{32}$/.test(extensionId))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");if(registryKey!==undefined&&!win32)throw new BridgeProtocolError("registryKey is only used on win32");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const writeManifest=async(file)=>{if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID3()}.tmp`;const handle=await open5(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`
|
|
1387
|
+
`);await handle.sync()}finally{await handle.close()}await rename2(temp,file);return JSON.parse(await readFile9(file,"utf8"))};if(win32){const key=registryKey??WIN32_REGISTRY_KEYS[browser];if(!isWin32RegistryKey(key))throw new BridgeProtocolError(registryKey===undefined?"custom browser requires registryKey on win32":"registryKey must be HKCU\\Software\\...\\NativeMessagingHosts");try{return await installWin32NativeHost({hostName,hostPath,dir,registryKey:key,force,writeManifest})}catch(error){throw error instanceof BridgeProtocolError?error:new BridgeProtocolError(String(readProperty(error,"message")))}}await secureDirectory(dir);const file=path16.join(dir,`${hostName}.json`);const parsed=await writeManifest(file);await chmod2(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload["notificationId"],payload["byUser"]]:namespace==="notifications"?[payload["notificationId"]]:namespace==="tabGroups"?[payload["group"]]:namespace==="windows"?[payload["windowId"]]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var presetsByName=DEVICE_PRESETS;var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){const named=presetsByName[presetNameOrObject];if(!named){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=named}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:"0.0.1"});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)Object.assign(har,{_errorText:entry.errorText??""});return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep3(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep3(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root instanceof ShadowRoot?root.host:null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return((el instanceof HTMLElement?el.innerText:undefined)||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).toSorted((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);if(typeof snapshot!=="object"||snapshot===null||!("tree"in snapshot)||typeof snapshot.tree!=="string"){throw new TypeError("snapshotWithLayers needs the full snapshot (no diff or find options)")}const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
|
|
1388
|
+
${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/json\s*(;|$)|\+json\s*(;|$)/i;function matchesText(value,pattern){if(pattern===undefined)return true;if(value===null||value===undefined)return false;if(pattern instanceof RegExp)return pattern.test(String(value));return String(value).includes(String(pattern))}function matchesToken(value,expected){if(expected===undefined)return true;if(value===null||value===undefined)return false;return String(value).toLowerCase()===String(expected).toLowerCase()}function toPredicate(match){if(match===undefined||match===null)return()=>true;if(typeof match==="function")return match;if(typeof match!=="object")throw new TypeError("match must be a predicate function or a descriptor object");return(entry)=>matchesText(entry.url,match.url)&&matchesToken(entry.method,match.method)&&matchesText(entry.mimeType,match.mimeType)&&matchesToken(entry.resourceType,match.resourceType)}function startedAtOf(params){const wallTime=Number(params?.wallTime);return Number.isFinite(wallTime)&&wallTime>0?Math.round(wallTime*1000):Date.now()}function decodeBody(entry){if(typeof entry.body!=="string")return null;return entry.base64Encoded?Buffer.from(entry.body,"base64").toString("utf8"):entry.body}function createNetworkSnoop(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createNetworkSnoop requires a page with cdp and resolveSessionId")}const{match,bodies=true,maxEntries=500,maxBodyBytes=5000000}=options;const wanted=toPredicate(match);const inflight=new Map;const buffer=[];const waiters=new Set;const handlers={};let disposed=false;let queue=Promise.resolve();function subscribe(method,handler){handlers[method]=handler}function enqueue(task){queue=queue.then(task).catch((error)=>console.warn("[network-snoop] entry processing failed",error))}async function loadBody(entry,record){if(entry.encodedDataLength>maxBodyBytes){entry.bodySkipped=true;return}try{if(record===undefined)throw new TypeError("Cannot read properties of undefined (reading 'rawBody')");const result=await record.rawBody();entry.body=result?.body??null;entry.base64Encoded=Boolean(result?.base64Encoded)}catch{entry.body=null}}function commit(entry){buffer.push(entry);while(buffer.length>maxEntries)buffer.shift();for(const waiter of[...waiters])if(waiter.test(entry))waiter.resolve(entry)}subscribe("Network.requestWillBeSent",(params)=>{const requestId=params?.requestId;if(!requestId)return;inflight.set(requestId,{requestId,url:params.request?.url??params.documentURL??"",method:params.request?.method??"GET",resourceType:params.type??null,status:null,statusText:null,mimeType:null,requestHeaders:params.request?.headers??{},responseHeaders:null,remoteIPAddress:null,postData:params.request?.postData??null,encodedDataLength:0,body:null,base64Encoded:false,bodySkipped:false,failed:false,errorText:null,startedAt:startedAtOf(params),finishedAt:null})});subscribe("Network.responseReceived",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;const response=params.response??{};entry.status=response.status??null;entry.statusText=response.statusText??"";entry.mimeType=response.mimeType??null;entry.responseHeaders=response.headers??{};entry.remoteIPAddress=response.remoteIPAddress??null;if(params.type)entry.resourceType=params.type});subscribe("Network.loadingFinished",(params,record)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.encodedDataLength=Number(params.encodedDataLength??0);entry.finishedAt=Date.now();enqueue(async()=>{if(!wanted(entry))return;if(bodies)await loadBody(entry,record);commit(entry)})});subscribe("Network.loadingFailed",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.failed=true;entry.errorText=params.errorText??"";entry.encodedDataLength=Number(readProperty(params,"encodedDataLength")??entry.encodedDataLength);entry.finishedAt=Date.now();enqueue(async()=>{if(wanted(entry))commit(entry)})});function pop(){return buffer.splice(0,buffer.length)}function peek(){return[...buffer]}function popJson(){const values=[];for(const entry of pop()){if(!JSON_MIME.test(String(entry.mimeType??"")))continue;const text=decodeBody(entry);if(text===null)continue;try{values.push(JSON.parse(text))}catch{}}return values}function waitFor(entryMatch,{timeoutMs=DEFAULT_TIMEOUT_MS}={}){if(disposed)return Promise.reject(Error("Network snoop is disposed"));const predicate=toPredicate(entryMatch);return new Promise((resolve,reject)=>{let settled=false;const finish=(callback)=>(value)=>{if(settled)return;settled=true;clearTimeout(timer);waiters.delete(waiter);callback(value)};const waiter={resolve:finish(resolve),reject:finish(reject),test:(entry)=>{try{return Boolean(predicate(entry))}catch(error){waiter.reject(error instanceof Error?error:Error(String(error)));return false}}};const timer=setTimeout(()=>waiter.reject(Error(`Timed out waiting for network response after ${timeoutMs}ms`)),timeoutMs);waiters.add(waiter)})}function summary({max=50}={}){const shown=buffer.slice(0,max);const lines=shown.map((entry)=>[entry.method,entry.status??(entry.failed?"FAILED":"-"),entry.mimeType??"-",`${entry.encodedDataLength}B`,entry.url].join(" "));const hidden=buffer.length-shown.length;if(hidden>0)lines.push(`... +${hidden} more`);return lines.join(`
|
|
1389
|
+
`)}function dispose(){if(disposed)return;disposed=true;unsubscribe();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}const unsubscribe=subscribeNetwork(page,handlers);return{pop,peek,popJson,waitFor,summary,dispose}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");scrollTo(0,element.scrollHeight)});return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");return element.scrollHeight});if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf2(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;let entries;if(typeof api==="function")entries=await api.call(page);else{const logs=api===null||api===undefined?undefined:readProperty(api,"logs");if(logs!==null&&logs!==undefined){if(typeof logs!=="function")throw new TypeError("api.logs is not a function");entries=await logs.call(api)}}return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const traceDir=dir;const shotDir=path17.join(dir,"screenshots");const ready=mkdir9(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf2(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog.type()??null,message:dialog.message()??"",defaultPrompt:dialog.defaultValue(),url:dialog.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(stepRecord,phase){const file=path17.join(shotDir,`${stepRecord.seq}-${slug(stepRecord.name)}-${phase}.png`);try{await writeFile3(file,await page.screenshot({type:"png"}));stepRecord.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:stepRecord.seq,message:messageOf2(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record(Object.assign({kind:"console"},entry));consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf2(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=records.toSorted((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile3(path17.join(traceDir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
|
|
1390
|
+
`).join(""));await writeFile3(path17.join(traceDir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}
|
|
1391
|
+
`);await writeFile3(path17.join(traceDir,"summary.json"),`${JSON.stringify(summary,null,2)}
|
|
1392
|
+
`);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}function isDaemonInfo(value){if(!value||typeof value!=="object"||!("sock_path"in value))return false;return typeof value.sock_path==="string"&&value.sock_path.length>0}function resolveBskHome(env=process.env){const override=env["BSK_HOME"];if(typeof override==="string"&&override.length>0)return override;const home=env["HOME"]&&env["HOME"].length>0?env["HOME"]:homedir3();return path18.join(home,".bsk")}function daemonInfoPath(home){return path18.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync4(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!isDaemonInfo(info))return null;return info}function findBskBinary(env=process.env){const home=env["HOME"]&&env["HOME"].length>0?env["HOME"]:homedir3();const candidates=[env["BSK_BIN"],path18.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter((candidate)=>Boolean(candidate));for(const candidate of candidates)if(existsSync4(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash2("sha256").update(path18.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}var powershellLiteral=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;function windowsDaemonLaunch(home,bskBin){const script=`$env:BSK_HOME = ${powershellLiteral(home)}; & ${powershellLiteral(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless "${windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe")}" -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,bskBin,timeoutMs}){const script=["$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT","$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew","Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null","Start-ScheduledTask -TaskName $env:BSK_TASK_NAME"].join("; ");return runToExit(windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(home,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn6(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let output="";const keep=(chunk)=>{output=(output+chunk).slice(-4096)};child.stdout.on("data",keep);child.stderr.on("data",keep);const timer=setTimeout(()=>{child.kill("SIGKILL");reject(new Error(`${label} did not return within ${timeoutMs}ms`))},timeoutMs);child.on("error",(error)=>{clearTimeout(timer);reject(new Error(`could not run ${command}: ${error.message}`))});child.on("exit",(code)=>{clearTimeout(timer);resolve({code,output:output.trim()})})})}async function startDaemonWithCli({home,env=process.env,bskBin=findBskBinary(env),timeoutMs=20000}={}){const status=await runToExit(bskBin,["status","--json"],{env:{...env,BSK_HOME:home},timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){if(home===undefined)throw new TypeError("startDaemonWithCli needs a home to register the Windows daemon task");const task=await startDaemonInWindowsTask({home,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`${status.output}; registering the bsk daemon task exited with ${task.code}${task.output?`: ${task.output}`:""}`)}throw new Error(`bsk status exited with ${status.code}${status.output?`: ${status.output}`:""}`)}function optionalProperty(value,key){return value===null||value===undefined?undefined:readProperty(value,key)}function listOrEmpty(value,what){if(value===null||value===undefined)return[];if(!Array.isArray(value))throw new TypeError(`${what} is not a list`);const list=value;return list}var DEFAULT_TIMEOUT_MS2=35000;var DISCOVERY_RETRY_MS=250;var DISCOVERY_BUDGET_MS=15000;var TOOL_TIMEOUT_GRACE_MS=5000;var HUMAN_WAIT_METHODS=new Set(["tool.request_help","tool.tab_borrow"]);var HUMAN_WAIT_BACKSTOP_MS=3600000;function ownBudgetMs(params){const budgets=[optionalProperty(params,"timeout_ms"),optionalProperty(params,"confirmation_timeout_ms")].filter((value)=>typeof value==="number");return budgets.length>0?Math.max(...budgets)+TOOL_TIMEOUT_GRACE_MS:undefined}var PROBE_TIMEOUT_MS=2000;function defaultSocketPath(home,env=process.env){if(process.platform!=="win32")return path19.join(home,"run","daemon.sock");return`\\\\.\\pipe\\bsk-daemon-${rustStrHash(env["USERNAME"]??"default",home)}`}function rustStrHash(...values){const bytes=Buffer.concat(values.flatMap((value)=>[Buffer.from(value,"utf8"),Buffer.from([255])]));const mask=(1n<<64n)-1n;const rotl=(x,b)=>(x<<b|x>>64n-b)&mask;let[v0,v1,v2,v3]=[0x736f6d6570736575n,0x646f72616e646f6dn,0x6c7967656e657261n,0x7465646279746573n];const round=()=>{v0=v0+v1&mask;v1=rotl(v1,13n)^v0;v0=rotl(v0,32n);v2=v2+v3&mask;v3=rotl(v3,16n)^v2;v0=v0+v3&mask;v3=rotl(v3,21n)^v0;v2=v2+v1&mask;v1=rotl(v1,17n)^v2;v2=rotl(v2,32n)};const compress=(word)=>{v3^=word;round();v0^=word};const whole=bytes.length-bytes.length%8;for(let i=0;i<whole;i+=8)compress(bytes.readBigUInt64LE(i));let last=BigInt(bytes.length&255)<<56n;for(let i=whole;i<bytes.length;i+=1)last|=BigInt(bytes.readUInt8(i))<<BigInt(8*(i-whole));compress(last);v2^=0xffn;round();round();round();return((v0^v1^v2^v3)&mask).toString(16).padStart(16,"0")}function socketExists(sockPath){if(process.platform!=="win32")return existsSync5(sockPath);try{return readdirSync("\\\\.\\pipe\\").includes(path19.win32.basename(sockPath))}catch{return false}}function probeSocket(sockPath){if(!socketExists(sockPath))return Promise.resolve(false);return new Promise((resolve)=>{const socket=connect2(sockPath);const done=(alive)=>{clearTimeout(timer);socket.destroy();resolve(alive)};const timer=setTimeout(()=>done(false),PROBE_TIMEOUT_MS);socket.on("error",()=>done(false));socket.on("connect",()=>socket.write(JSON.stringify({id:"probe-orphan",method:"system.ping"})+`
|
|
1393
|
+
`));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}var noop2=()=>{};function shortId(){return randomBytes(6).toString("hex")}function sleep4(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}var NO_LISTENER=new Set(["ENOENT","ECONNREFUSED"]);function sameRecord(info,stale){return Boolean(stale)&&JSON.stringify(info)===JSON.stringify(stale?.info)}class BskIpcClient{#home;#env;#sockPath;#autoStart;#startDaemon;#timeoutMs;#starting=null;constructor({home,env=process.env,sockPath,autoStart,startDaemon,timeoutMs=DEFAULT_TIMEOUT_MS2,bskBin}={}){this.#home=home??resolveBskHome(env);this.#sockPath=sockPath??null;this.#autoStart=autoStart??env["BSK_AUTO_START"]!=="0";this.#startDaemon=startDaemon??(()=>startDaemonWithCli({home:this.#home,env,bskBin}));this.#timeoutMs=timeoutMs;this.#env=env}get home(){return this.#home}async resolveSocket({isAborted=()=>false,stale}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found&&!sameRecord(found,stale))return found.sock_path;const orphan=defaultSocketPath(this.#home,this.#env);if(socketExists(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){if(stale){throw new BskRpcError("no_daemon",`${this.#home}/daemon.json names a BrowserSkill daemon at ${stale.info.sock_path} that is no longer listening (${stale.code}) and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}throw new BskRpcError("no_daemon",`no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}if(!this.#starting)this.#starting=this.#startDaemon().finally(()=>{this.#starting=null});await this.#starting;const deadline=Date.now()+DISCOVERY_BUDGET_MS;while(Date.now()<deadline&&!isAborted()){const info=readDaemonInfo(this.#home);if(info&&!sameRecord(info,stale))return info.sock_path;await sleep4(DISCOVERY_RETRY_MS)}if(isAborted())throw new BskRpcError("cancelled","cancelled while waiting for the daemon to publish daemon.json");throw new BskRpcError("no_daemon",`daemon start was requested but ${this.#home}/daemon.json never appeared`)}call(method,params,options={}){return this.callWithHandle(method,params,options).promise}callWithHandle(method,params,{idPrefix=method.replace(/[^a-z0-9]+/gi,"-"),timeoutMs}={}){const ownBudget=ownBudgetMs(params);const humanWait=HUMAN_WAIT_METHODS.has(method);const waitMs=humanWait&&ownBudget===undefined&&timeoutMs===undefined?HUMAN_WAIT_BACKSTOP_MS:Math.max(timeoutMs??this.#timeoutMs,ownBudget??0);const rpcId=`${idPrefix}-${shortId()}`;const frame={id:rpcId,method};if(params!==undefined)frame.params=params;let aborted=false;let abortSocket=noop2;const exchange=(sockPath,onNoListener)=>new Promise((resolve,reject)=>{const socket=connect2(sockPath);let buffer="";let settled=false;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();fn(value)};const timer=setTimeout(()=>{const cancels=method!=="cancel"&&!humanWait;finish(reject,new BskRpcError("timeout",`${method} did not answer within ${waitMs}ms${cancels?"; a cancel was requested at the daemon":""}`));if(cancels)this.cancel(rpcId).catch(()=>{})},waitMs);abortSocket=()=>finish(reject,new BskRpcError("cancelled",`${method} cancelled by caller`));socket.on("error",(error)=>{if(error.code!==undefined&&NO_LISTENER.has(error.code))onNoListener(error.code);finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`))});socket.setEncoding("utf8");socket.on("connect",()=>socket.write(JSON.stringify(frame)+`
|
|
1394
|
+
`));socket.on("data",(chunk)=>{buffer+=chunk;const idx=buffer.indexOf(`
|
|
1395
|
+
`);if(idx===-1)return;try{finish(resolve,decodeResponse(buffer.slice(0,idx),rpcId,method))}catch(error){finish(reject,error)}});socket.on("close",()=>finish(reject,new BskRpcError("protocol_error",`${method}: daemon closed the connection without a reply`)))});const promise=(async()=>{let stale;for(;;){const sockPath=await this.resolveSocket({isAborted:()=>aborted,stale});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);let refused;try{return await exchange(sockPath,(code)=>{refused=code})}catch(error){const info=refused&&!stale&&!this.#sockPath?readDaemonInfo(this.#home):null;if(info?.sock_path!==sockPath)throw error;stale={info,code:refused}}}})();return{rpcId,promise,abort:()=>{aborted=true;abortSocket()}}}async cancel(rpcId){return this.call("cancel",{rpc_id:rpcId},{idPrefix:"cancel",timeoutMs:2000})}}function decodeResponse(line,rpcId,method){let reply;try{reply=JSON.parse(line)}catch{throw new BskRpcError("protocol_error",`${method}: daemon reply is not JSON: ${line.slice(0,120)}`)}const replyId=readProperty(reply,"id");const replyError=readProperty(reply,"error");const undecodableFrame=replyId==="0"&&replyError;if(replyId!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${replyId} does not match request ${rpcId}`)}if(replyError){const code=readProperty(replyError,"code");const message=readProperty(replyError,"message");throw new BskRpcError(code===undefined?"protocol_error":String(code),message===undefined?"daemon error":String(message),readProperty(replyError,"data"))}return readProperty(reply,"result")}var REF_SHAPE=/^@?e\d+$/;function resolveTarget(target){if(typeof target==="string"){return REF_SHAPE.test(target)?{ref:target}:{selector:target}}if(target&&typeof target==="object"){const spec=target;if(typeof spec.ref==="string")return{ref:spec.ref};if(typeof spec.selector==="string")return{selector:spec.selector};if(typeof spec.captureId==="string"){return{capture_id:spec.captureId,image_x:spec.x,image_y:spec.y}}}throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}")}function optionalTarget(target){return target===undefined?{}:resolveTarget(target)}function compact(params){const out={};for(const[key,value]of Object.entries(params))if(value!==undefined)out[key]=value;return out}function fromBase64(value,field){if(typeof value!=="string")throw new TypeError(`${field} is not base64 text`);return Buffer.from(value,"base64")}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs,context,dependsOn}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:fromBase64(readProperty(result,"image_base64"),"image_base64"),width:readProperty(result,"width"),height:readProperty(result,"height"),format:readProperty(result,"format"),captureId:readProperty(result,"capture_id")??null,captureUnavailable:readProperty(result,"capture_unavailable")??null,tabId:readProperty(result,"tab_id"),dialogs:readProperty(result,"dialogs")??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs,context_id:context,depends_on:dependsOn});const buffer=await readCapture(session,readProperty(started,"capture_id"),readProperty(started,"byte_size"));return{buffer,width:readProperty(started,"width"),height:readProperty(started,"height"),format:readProperty(started,"format"),captureId:readProperty(started,"capture_id"),scope:readProperty(started,"scope")??scope??null,tabId:readProperty(started,"tab_id"),dialogs:readProperty(started,"dialogs")??[]}}async function readCapture(session,captureId,byteSize){const chunks=[];let offset=0;try{for(;;){const chunk=await session.tool("screenshot_read",{capture_id:captureId,offset});const bytes=fromBase64(readProperty(chunk,"data_base64")??"","data_base64");chunks.push(bytes);if(readProperty(chunk,"eof")||bytes.length===0)break;const nextOffset=readProperty(chunk,"next_offset");if(typeof nextOffset!=="number"||nextOffset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=nextOffset}}finally{await session.tool("screenshot_release",{capture_id:captureId}).catch(()=>{})}const buffer=Buffer.concat(chunks);if(typeof byteSize==="number"&&buffer.length!==byteSize){throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`)}return buffer}var SESSION_STOP_TIMEOUT_MS=3600000;function sharedTab({context,dependsOn,...unknown}){const extra=Object.keys(unknown);if(extra.length>0){throw new TypeError(`unknown option ${extra.map((key)=>JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`)}return{context_id:context,depends_on:dependsOn}}class BskSession{#client;#stopped=false;constructor(client,{sessionId,browserInstanceId=null,agentWindowId=null,interaction=null}={}){if(typeof sessionId!=="string"||sessionId.length===0)throw new TypeError("BskSession requires a sessionId");this.#client=client;this.sessionId=sessionId;this.browserInstanceId=browserInstanceId;this.agentWindowId=agentWindowId;this.interaction=interaction}get client(){return this.#client}get stopped(){return this.#stopped}tool(name,params={}){if(this.#stopped)return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));return this.#client.call(`tool.${name}`,compact({session_id:this.sessionId,...params}),{idPrefix:name.replace(/_/g,"-")})}cooperate(action,{tabId,timeoutMs,maxTokens}={}){return this.tool("cooperate",{action,tab_id:tabId,timeout_ms:timeoutMs,max_tokens:maxTokens})}navigate(url,{tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}back({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}forward({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}reload({tabId,waitUntil,timeoutMs,hard,...shared}={}){return this.tool("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard,...sharedTab(shared)})}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover,...shared}={}){return this.tool("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover,...sharedTab(shared)})}snapshot({tabId,maxDepth,maxTokens}={}){return this.tool("snapshot",{tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens})}getHtml({ref,tabId,maxBytes}={}){return this.tool("get_html",{ref,tab_id:tabId,max_bytes:maxBytes})}screenshot(options){return captureScreenshot(this,options)}click(target,{button,clickCount,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}hover(target,{modifiers,settleMs,tabId,timeoutMs,...shared}={}){return this.tool("hover",{...resolveTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}focus(target,{tabId,timeoutMs,...shared}={}){return this.tool("focus",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}blur(target,{tabId,timeoutMs,...shared}={}){return this.tool("blur",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}fill(target,value,{clearBefore,tabId,timeoutMs,...shared}={}){return this.tool("fill",{...resolveTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}press(key,{target,modifiers,holdMs,tabId,timeoutMs,...shared}={}){return this.tool("press",{key,...optionalTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}select(target,values,{tabId,timeoutMs,...shared}={}){return this.tool("select",{...resolveTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}scrollTo(target,{tabId,timeoutMs,...shared}={}){return this.tool("scroll_to",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("wheel",{...optionalTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs,...shared}={}){return this.tool("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs,...sharedTab(shared)})}tabList({scope}={}){return this.tool("tab_list",{scope})}tabCreate({url,active,index}={}){return this.tool("tab_create",{url,active,index})}tabClose(tabId,shared={}){return this.tool("tab_close",{tab_id:tabId,...sharedTab(shared)})}tabSelect(tabId){return this.tool("tab_select",{tab_id:tabId})}tabBorrow(tabId,{confirmationTimeoutMs}={}){return this.tool("tab_borrow",{tab_id:tabId,confirmation_timeout_ms:confirmationTimeoutMs})}tabReturn(tabId){return this.tool("tab_return",{tab_id:tabId})}waitForNavigation({tabId,waitUntil,timeoutMs}={}){return this.tool("wait_for_navigation",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}requestHelp({prompt,title,targets,completionCriteria,tabId,timeoutMs}={}){return this.tool("request_help",{prompt,title,tab_id:tabId,timeout_ms:timeoutMs,targets:targets?.map((t)=>resolveTarget(t)),completion_criteria:completionCriteria})}console({tabId,since,limit,maxTextChars,includeStack}={}){return this.tool("console",{tab_id:tabId,since,limit,max_text_chars:maxTextChars,include_stack:includeStack})}network({tabId,since,limit,maxTextChars}={}){return this.tool("network",{tab_id:tabId,since,limit,max_text_chars:maxTextChars})}resize(width,height,shared={}){return this.tool("window_resize",{width,height,...sharedTab(shared)})}emulate({tabId,off,overrides,...shared}={}){return this.tool("emulate",{tab_id:tabId,off,overrides,...sharedTab(shared)})}async stop(){if(this.#stopped)return null;this.#stopped=true;return this.#client.call("session.stop",{session_id:this.sessionId},{idPrefix:"session-stop",timeoutMs:SESSION_STOP_TIMEOUT_MS})}}var DEFAULT_WAIT_FOR_BROWSER_MS=15000;var TAB_GROUPING_EXTENSION_VERSIONS=new Set(["0.4.0"]);function isTabGroupingExtension(browser){return TAB_GROUPING_EXTENSION_VERSIONS.has(optionalProperty(browser,"extension_version"))}var TAB_GROUPING_EXTENSION_STEP=`Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a "BrowserSkill" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved "BrowserSkill" tab groups by hand.`;function outdatedError(browser){return new BskRpcError("extension_outdated",`the BrowserSkill extension in ${readProperty(browser,"browser_name")??"the browser"} [${readProperty(browser,"instance_id")}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`)}function namesBrowser(b,browser){return readProperty(b,"instance_id")===browser||Boolean(readProperty(b,"label")&&readProperty(b,"label")===browser)}function chooseBrowser(browser,browsers){const resolved=resolveBrowser(browser,browsers);if(resolved!==undefined&&resolved!==null){const entry=browsers.find((b)=>namesBrowser(b,resolved));if(entry&&isTabGroupingExtension(entry))throw outdatedError(entry);return resolved}const outdated=browsers.filter(isTabGroupingExtension);if(outdated.length===0)return resolved;const usable=browsers.find((b)=>!isTabGroupingExtension(b));if(!usable)throw outdatedError(outdated[0]);return readProperty(usable,"instance_id")}async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return listOrEmpty(readProperty(status,"browsers"),"system.status browsers")}function resolveBrowser(browser,browsers){if(browser===undefined||browser===null)return browser;if(browsers.some((b)=>namesBrowser(b,browser)))return browser;const named=browsers.filter((b)=>readProperty(b,"browser_name")===browser);if(named.length>1){throw new BskRpcError("invalid_params",`browser "${browser}" matches ${named.length} connected browsers (${named.map((b)=>readProperty(b,"instance_id")).join(", ")}); pass the instance id instead`)}return named.length===1?readProperty(named[0],"instance_id"):browser}async function connectBrowserSkill({client,home,env,sockPath,autoStart,timeoutMs,bskBin,name,browser,width,height,focused=false,waitForBrowserMs=DEFAULT_WAIT_FOR_BROWSER_MS}={}){const ipc=client??new BskIpcClient({home,env,sockPath,autoStart,timeoutMs,bskBin});const browsers=await listBrowsers(ipc,{waitForBrowserMs});if(browsers.length===0){throw new BskRpcError("no_browser_connected","the BrowserSkill daemon is up but no browser extension is connected; open the browser that has the BrowserSkill extension enabled (bskDoctor() explains the remaining step); never substitute another browser for the user's without telling them")}const started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:chooseBrowser(browser,browsers),width,height,focused}),{idPrefix:"session-start"});return new BskSession(ipc,{sessionId:readProperty(started,"session_id"),browserInstanceId:readProperty(started,"browser_instance_id")??null,agentWindowId:readProperty(started,"agent_window_id")??null,interaction:readProperty(started,"interaction")??null})}var CSS_PATH_FN=String(function cssPath(el){if(!(el instanceof Element))return null;if(el.getRootNode()!==document)return null;const parts=[];let node=el;while(node&&node.nodeType===1&&node!==document.documentElement){let part=node.localName;if(node.id&&/^[A-Za-z_][\w-]*$/.test(node.id)&&document.querySelectorAll("#"+node.id).length===1){parts.unshift("#"+node.id);return parts.join(" > ")}const parent=node.parentElement;if(parent){const same=Array.from(parent.children).filter((c)=>c.localName===part);if(same.length>1)part+=`:nth-of-type(${same.indexOf(node)+1})`}parts.unshift(part);node=parent}parts.unshift("html");return parts.join(" > ")});function buildSnapshotExpression(options={}){return`(function () {
|
|
1518
1396
|
const globalThis = {};
|
|
1519
1397
|
${pageBundle}
|
|
1520
1398
|
const api = globalThis.__omowright;
|
|
@@ -1523,5 +1401,18 @@ ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/jso
|
|
|
1523
1401
|
const css = {};
|
|
1524
1402
|
for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));
|
|
1525
1403
|
return { tree: result.tree, refs: result.refs || {}, css, error: result.error };
|
|
1526
|
-
})()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{spawn as spawn5}from"node:child_process";import path16 from"node:path";import{existsSync as existsSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path15 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);function macRow(b,home,exists){const apps=[path15.join("/Applications",`${b.app}.app`),path15.join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=path15.join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:path15.join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>path15.join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path15.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const localAppData=env.LOCALAPPDATA??path15.join(home,"AppData","Local");const programFiles=[localAppData,env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);const userDataDir=path15.join(localAppData,b.userData);const binary=programFiles.map((root)=>path15.join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync4}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`
|
|
1527
|
-
`;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path16.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path16.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync5}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path16.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn5("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync3,readFile=readFileSync5,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeStep=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync3(path16.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync5(entry.path);if(present)rmSync3(entry.path,{force:true});return{...entry,removed:present}}import{execFile as execFile2}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir4}from"node:os";import path17 from"node:path";var PROBE_TIMEOUT_MS2=3000;function runDefault(command,args){return new Promise((resolve)=>{execFile2(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8*1024*1024},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=JSON.parse(plistJson)?.LSHandlers}catch{return null}if(!Array.isArray(handlers))return null;const pick=(scheme)=>handlers.find((h)=>h?.LSHandlerURLScheme===scheme&&typeof h.LSHandlerRoleAll==="string");const handler=pick("https")??pick("http");return handler?handler.LSHandlerRoleAll.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?match[1].toLowerCase():null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path17.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path17.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run("reg",["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run("tasklist",["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat){let latest=null;for(const rel of["Local State",path17.join("Default","History"),path17.join("Default","Preferences")]){try{const mtime=stat(path17.join(browser.userDataDir,rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir4(),browsers=[],run=runDefault,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat)]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=7*24*60*60*1000;function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter(Boolean);return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);if(defaultBrowser.supported===false){const suggested=inUse.length===1?inUse[0].id:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);if(inUse.length===1)return choose(candidates,inUse[0],"only-in-use",`${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`,defaultBrowser);if(runningNow.length===1)return choose(candidates,runningNow[0],"only-running",`${runningNow[0].label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1)return choose(candidates,candidates[0],"only-installed",`${candidates[0].label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}import{existsSync as existsSync6,readFileSync as readFileSync6,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{homedir as homedir5}from"node:os";import path18 from"node:path";import{spawn as spawn6}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault2(command,args,env){return new Promise((resolve)=>{const child=spawn6(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path18.join(home,name);snapshot.set(file,existsSync6(file)?readFileSync6(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync6(file)?readFileSync6(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync4(file,{force:true});else writeFileSync4(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir5(),installDir=path18.join(home,".local","bin"),version,run=runDefault2}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path18.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync6(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn6(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir6}from"node:os";import{existsSync as existsSync7,readFileSync as readFileSync7}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync7(entry.path)&&readFileSync7(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env.OMOWRIGHT_BROWSER??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor({cli,daemon,browsers,browsersConnected,identification,primary}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0&&!primary)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(daemon.browsers.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else{const registration=await registerExternalExtension({platform,browser:primary});registrations.push({browser:primary.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:primary.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OMOWRIGHT_PAGE_CDP_METHODS,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,SharedConnectionError,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectNamed,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,identifyBrowser,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,listInstances,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};
|
|
1404
|
+
})()`}async function bskSnapshot(session,{tabId,timeoutMs,context,dependsOn,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,context,dependsOn,awaitPromise:false,returnByValue:true});if(!reply||readProperty(reply,"ok")===false){const text=optionalProperty(optionalProperty(reply,"error"),"text")??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=readProperty(reply,"value");const tree=value?readProperty(value,"tree"):undefined;if(!value||typeof tree!=="string")throw new Error("bskSnapshot: page returned no tree");const error=readProperty(value,"error");if(error)throw new Error(`bskSnapshot: ${error}`);return{tree,refs:readProperty(value,"refs"),css:readProperty(value,"css")}}var SCRIPT_AT_EOF=/piped stdin runs as one script/i;var LISTS_REPL_TOOL=/^\s*repl\b/m;function captureCli({spawn,command,args,env,timeoutMs}){return new Promise((resolve)=>{const[bin,...lead]=command;let child;try{child=spawn(bin,[...lead,...args],{env,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch{resolve({out:null,timedOut:false});return}let out="";const timer=setTimeout(()=>{child.kill();resolve({out:null,timedOut:true})},timeoutMs);child.stdout?.setEncoding("utf8");child.stdout?.on("data",(chunk)=>{out+=chunk});child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>{out+=chunk});child.once("error",()=>{clearTimeout(timer);resolve({out:null,timedOut:false})});child.once("close",(code)=>{clearTimeout(timer);resolve({out:code===0?out:null,timedOut:false})})})}async function replTransportFor(options){const help=await captureCli({...options,args:["repl","--help"]});if(help.out!==null)return SCRIPT_AT_EOF.test(help.out)?"mcp":"line";if(!help.timedOut)return"line";const mcpHelp=await captureCli({...options,args:["mcp","--help"]});return mcpHelp.out!==null&&LISTS_REPL_TOOL.test(mcpHelp.out)?"mcp":"line"}async function asideCliVersion(options){const{out}=await captureCli({...options,args:["--version"]});return out?.trim()||null}class AsideReplError extends Error{constructor(code,message,{output=[],setup}={}){super(message);this.name="AsideReplError";this.code=code;this.output=output;if(setup)this.setup=setup}}var CLOSE_TIMEOUT_MS=5000;var PROMPT="repl > ";var MARKER=/^\[(ok|error) \| \d+ms\]$/;var ANSI=/\x1B\[[0-9;?]*[ -/]*[@-~]/g;var plain=(text)=>text.replace(ANSI,"");var finished2=(lines,tag)=>MARKER.test(lines.at(-1)??"")&&(lines.at(-2)??"").startsWith(tag);class LineTransport{#child;#buffer="";#lines=[];#waiter=null;#closed=false;#exit;constructor(child){this.#child=child;this.#exit=new Promise((resolve)=>child.once("exit",(code,signal)=>{this.#closed=true;this.#settle(new AsideReplError("repl_closed",`aside repl exited (code ${code}, signal ${signal})`,{output:this.#lines.splice(0)}));resolve()}));child.stdout.setEncoding("utf8");child.stdout.on("data",(chunk)=>this.#onData(chunk));child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>this.#onData(chunk));child.stdin.on?.("error",(error)=>{if(error.code!=="EPIPE"){this.#settle(new AsideReplError("repl_closed",`aside repl stdin failed: ${error.message}`,{output:this.#lines.splice(0)}))}})}async ready(timeoutMs){const banner=await this.#waitFor((pending)=>pending.endsWith(PROMPT),timeoutMs,"repl_start_timeout");const info={};for(const line of banner){const account=/^account: (\S+)/.exec(line)?.[1];if(account!==undefined)info.account=account;const dir=/^sessionDir: (.+)$/.exec(line)?.[1];if(dir!==undefined)info.sessionDir=dir.trim()}return info}async call(line,{tag,timeoutMs}){if(this.#closed)throw new AsideReplError("repl_closed","aside repl session is closed");this.#child.stdin.write(`${line}
|
|
1405
|
+
`);const output=await this.#waitFor((pending,lines)=>pending.endsWith(PROMPT)&&finished2(lines,tag),timeoutMs,"repl_timeout");const markerAt=output.findLastIndex((entry)=>MARKER.test(entry));if(markerAt===-1)throw new AsideReplError("repl_protocol","aside repl answered without an [ok|error] marker",{output});const body=output.slice(0,markerAt);if(output[markerAt]?.startsWith("[error")){throw new AsideReplError("repl_error",body.join(`
|
|
1406
|
+
`)||"aside repl reported an error",{output:body})}return body}async close(){if(this.#closed)return;this.#child.stdin.end(`exit
|
|
1407
|
+
`);let timer;const timedOut=new Promise((resolve)=>{timer=setTimeout(()=>resolve(true),CLOSE_TIMEOUT_MS)});const late=await Promise.race([this.#exit.then(()=>false),timedOut]);clearTimeout(timer);if(late){this.#child.kill();await this.#exit}}#onData(chunk){this.#buffer+=chunk;let newline;while((newline=this.#buffer.indexOf(`
|
|
1408
|
+
`))!==-1){let line=plain(this.#buffer.slice(0,newline)).replace(/\r$/,"");this.#buffer=this.#buffer.slice(newline+1);while(line.startsWith(PROMPT))line=line.slice(PROMPT.length);this.#lines.push(line)}this.#check()}#waitFor(isDone,timeoutMs,timeoutCode){return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.#waiter=null;const output=this.#lines.splice(0);reject(new AsideReplError(timeoutCode,`aside repl did not answer within ${timeoutMs} ms`,{output}));this.#child.kill()},timeoutMs);this.#waiter={isDone,resolve,reject,timer};this.#check()})}#check(){const waiter=this.#waiter;if(!waiter||!waiter.isDone(plain(this.#buffer),this.#lines))return;this.#waiter=null;clearTimeout(waiter.timer);this.#buffer="";waiter.resolve(this.#lines.splice(0))}#settle(error){const waiter=this.#waiter;if(!waiter)return;this.#waiter=null;clearTimeout(waiter.timer);waiter.reject(error)}}var PROTOCOL_VERSION="2025-06-18";var CLOSE_TIMEOUT_MS2=5000;var KILL_GRACE_MS=2000;var STDERR_LINES=50;var optional2=(value,key)=>value===null||value===undefined?undefined:readProperty(value,key);var textLines=(part)=>{const text=optional2(part,"text");if(optional2(part,"type")!=="text"||typeof text!=="string"||!text)return[];return text.replace(/\r?\n$/,"").split(/\r?\n/)};class McpTransport{#child;#buffer="";#nextId=1;#pending=new Map;#stderr=[];#closed=false;#exited=false;#terminated=false;#exit;constructor(child){this.#child=child;this.#exit=new Promise((resolve)=>child.once("exit",(code,signal)=>{this.#closed=true;this.#exited=true;const error=new AsideReplError("repl_closed",`aside mcp exited (code ${code}, signal ${signal})`,{output:this.#stderr.splice(0)});for(const{reject,timer}of this.#pending.values()){clearTimeout(timer);reject(error)}this.#pending.clear();resolve()}));child.stdin.on?.("error",()=>{});child.stdout.setEncoding("utf8");child.stdout.on("data",(chunk)=>this.#onData(chunk));child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>{this.#stderr.push(...chunk.split(/\r?\n/).filter(Boolean));this.#stderr.splice(0,Math.max(0,this.#stderr.length-STDERR_LINES))})}async ready(timeoutMs){const init=await this.#request("initialize",{protocolVersion:PROTOCOL_VERSION,capabilities:{},clientInfo:{name:"omowright",version:"1"}},timeoutMs,"repl_start_timeout");this.#send({method:"notifications/initialized"});const version=String(optional2(optional2(init,"serverInfo"),"version")??"of unknown version");const listed=await this.#request("tools/list",{},timeoutMs,"repl_start_timeout");const tools=optional2(listed,"tools")??[];if(!Array.isArray(tools)||!tools.some((tool)=>optional2(tool,"name")==="repl")){throw new AsideReplError("repl_unsupported_cli",`Aside CLI ${version} runs a piped \`aside repl\` as one script at EOF and its \`aside mcp\` has no repl tool, so omowright cannot keep a REPL session with it; update the Aside CLI (\`aside --update\`)`)}try{await this.call("void 0",{timeoutMs,timeoutCode:"repl_start_timeout"})}catch(error){if(!(error instanceof AsideReplError)||error.code!=="repl_error")throw error;throw new AsideReplError("repl_start_failed",`aside mcp could not start a REPL session: ${error.message}`,{output:error.output})}return{version}}async call(code,{timeoutMs,timeoutCode="repl_timeout"}){const result=await this.#request("tools/call",{name:"repl",arguments:{title:"omowright",code}},timeoutMs,timeoutCode);const content=optional2(result,"content")??[];const output=Array.isArray(content)?content.flatMap((part)=>textLines(part)):[];if(optional2(result,"isError")){throw new AsideReplError("repl_error",output.join(`
|
|
1409
|
+
`)||"aside repl reported an error",{output})}return output}async close(){this.#closed=true;if(this.#exited)return;if(!this.#terminated){this.#child.stdin.end();if(await this.#exitsWithin(CLOSE_TIMEOUT_MS2))return;this.#terminate()}if(await this.#exitsWithin(KILL_GRACE_MS))return;this.#child.kill("SIGKILL");await this.#exit}async#exitsWithin(ms){let timer;const timedOut=new Promise((resolve)=>{timer=setTimeout(()=>resolve(false),ms)});const exited=await Promise.race([this.#exit.then(()=>true),timedOut]);clearTimeout(timer);return exited}#terminate(){this.#terminated=true;this.#child.stdin.end();this.#child.kill()}#send(message){this.#child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",...message})}
|
|
1410
|
+
`)}#request(method,params,timeoutMs,timeoutCode){if(this.#closed)return Promise.reject(new AsideReplError("repl_closed","aside repl session is closed"));const id=this.#nextId++;return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.#pending.delete(id);this.#closed=true;this.#terminate();reject(new AsideReplError(timeoutCode,`aside mcp did not answer ${method} within ${timeoutMs} ms`,{output:this.#stderr.splice(0)}))},timeoutMs);this.#pending.set(id,{resolve,reject,timer,method});this.#send({id,method,params})})}#onData(chunk){this.#buffer+=chunk;let newline;while((newline=this.#buffer.indexOf(`
|
|
1411
|
+
`))!==-1){const line=this.#buffer.slice(0,newline).trim();this.#buffer=this.#buffer.slice(newline+1);let message;try{message=JSON.parse(line)}catch{continue}if(message===null||typeof message!=="object")continue;const id=readProperty(message,"id");const method=readProperty(message,"method");if(method!==undefined){this.#answer(id,method);continue}if(!("result"in message)&&!("error"in message))continue;if(typeof id!=="number")continue;const pending=this.#pending.get(id);if(!pending)continue;this.#pending.delete(id);clearTimeout(pending.timer);const error=readProperty(message,"error");if(error){const reason=optional2(error,"message")??JSON.stringify(error);pending.reject(new AsideReplError("repl_protocol",`aside mcp refused ${pending.method}: ${String(reason)}`))}else pending.resolve(readProperty(message,"result"))}}#answer(id,method){if(id===undefined||id===null||this.#closed)return;if(method==="ping")this.#send({id,result:{}});else this.#send({id,error:{code:-32601,message:`Method not found: ${String(method)}`}})}}var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function windowsPowerShellEnv(env){const key=Object.keys(process.env).find((name)=>name.toUpperCase()==="PSMODULEPATH");if(!key)return env;const value=process.env[key];if(value===undefined)throw new TypeError(`${key} has no value`);const kept=value.split(";").filter((entry)=>entry&&!/[\\/]PowerShell[\\/]/i.test(entry));return{...env,[key]:kept.length>0?kept.join(";"):undefined}}function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env["BSK_VERSION"]=version;if(platform==="win32"){return{command:windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env:windowsPowerShellEnv(env)}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault(command,args,env){return new Promise((resolve)=>{const child=spawn7(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path20.join(home,name);snapshot.set(file,existsSync6(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync6(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir4(),installDir=path20.join(home,".local","bin"),version,run=runDefault}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path20.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync6(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn7(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}function findAsideBinary({env=process.env,home=homedir5(),exists=existsSync7}={}){if(env["ASIDE_BIN"])return env["ASIDE_BIN"];const candidates=[path21.join(home,".local","bin",process.platform==="win32"?"aside.exe":"aside")];if(process.platform==="win32"&&env["LOCALAPPDATA"])candidates.push(path21.join(env["LOCALAPPDATA"],"Aside","CLI","current","aside.exe"));for(const dir of(env["PATH"]??"").split(path21.delimiter)){if(dir)candidates.push(path21.join(dir,process.platform==="win32"?"aside.exe":"aside"))}return candidates.find((candidate)=>exists(candidate))??null}var INSTALL_SH2="https://releases.aside.com/install.sh";var APP_STEP="Ask the user to install the Aside browser (aside.com, macOS 15+ or Windows 10 22H2+) and sign in, then re-run asideOnboard().";var loginStep=(bin,account)=>`Ask the user to sign the CLI in: run \`${bin}${account?` --account ${account}`:""} login\` in their terminal and approve the 8-digit code in Aside > Settings > Account > Devices. Then re-run asideOnboard().`;var WINDOWS_CLI_STEP="Ask the user to install the Aside CLI from Aside > Settings > Developers, then re-run asideOnboard().";function asideCliInstallCommand(){return{command:"bash",args:["-c",`curl -fsSL ${INSTALL_SH2} | bash`],env:{}}}async function installAsideCli({home=homedir6(),run=runDefault}={}){const spec=asideCliInstallCommand();const rcBefore=snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const asideBin=path222.join(home,".local","bin","aside");const installed=result.code===0&&existsSync8(asideBin);return{installed,asideBin:installed?asideBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function capture(command,args,env){return new Promise((resolve)=>{const child=spawn8(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let out="";child.stdout.on("data",(chunk)=>{out+=chunk});child.stderr.on("data",(chunk)=>{out+=chunk});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out:null))})}function plistString(file,key){try{const text=readFileSync6(file,"utf8");const match=new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(text);return match?match[1]:null}catch{return null}}function findAsideApp({platform=process.platform,home=homedir6(),exists=existsSync8}={}){if(platform!=="darwin")return{installed:null,path:null,version:null};for(const dir of["/Applications",path222.join(home,"Applications")]){const app=path222.join(dir,"Aside.app");if(!exists(app))continue;const info=path222.join(app,"Contents","Info.plist");return{installed:true,path:app,version:plistString(info,"CFBundleShortVersionString")}}return{installed:false,path:null,version:null}}function parseAccountStatus(output,account){const rows=[];for(const line of output.split(`
|
|
1412
|
+
`)){const match=/^\s*(\*\s+)?(\S+)\s.*\bsigned (in|out)\b/.exec(line);const id=match?.[2];if(match&&id!==undefined)rows.push({active:Boolean(match[1]),id,signedIn:match[3]==="in"})}const row=account?rows.find((r)=>r.id===account):rows.find((r)=>r.active);return row?{signedIn:row.signedIn,account:row.id}:{signedIn:false,account:account??null}}async function cliReport({asideCommand,env,home,account}){const command=asideCommand??[findAsideBinary({env,home})];const[bin,...lead]=command;if(!bin)return{cli:{installed:false,bin:null,version:null},auth:{signedIn:false,account:null}};const version=await capture(bin,[...lead,"--version"],env);if(version===null)return{cli:{installed:false,bin,version:null},auth:{signedIn:false,account:null}};const status=await capture(bin,[...lead,...account?["--account",account]:[],"account","status"],env);return{cli:{installed:true,bin,version:version.trim()},auth:status===null?{signedIn:false,account:account??null}:parseAccountStatus(status,account)}}function nextStepFor({platform,app,cli,auth}){if(app.installed===false)return APP_STEP;if(!cli.installed)return platform==="win32"?WINDOWS_CLI_STEP:"Install the Aside CLI (asideOnboard() runs the official installer).";if(!auth.signedIn)return loginStep(cli.bin,auth.account);return null}async function asideDoctor({platform=process.platform,home=homedir6(),env=process.env,exists=existsSync8,asideCommand,account}={}){const app=findAsideApp({platform,home,exists});const{cli,auth}=await cliReport({asideCommand,env,home,account});const report={platform,app,cli,auth,ready:app.installed!==false&&cli.installed&&auth.signedIn,nextStep:null};report.nextStep=nextStepFor(report);return report}async function asideOnboard({platform=process.platform,home=homedir6(),env=process.env,exists=existsSync8,asideCommand,account,installOnlyWithApp=false,installCli=installAsideCli}={}){let report=await asideDoctor({platform,home,env,exists,asideCommand,account});let install=null;const appAllows=installOnlyWithApp?report.app.installed===true:report.app.installed!==false;if(!report.cli.installed&&platform!=="win32"&&appAllows){install=await installCli({home});if(install.installed)report=await asideDoctor({platform,home,env,exists,asideCommand:[install.asideBin],account})}return{...report,install}}var isObject2=(value)=>typeof value==="object"&&value!==null;var hasPipes=(child)=>child.stdin!==null&&child.stdout!==null;var DEFAULT_START_TIMEOUT_MS=15000;var DEFAULT_CALL_TIMEOUT_MS=125000;var CLI_PROBE_TIMEOUT_MS=5000;class AsideSession{#transport;#queue=Promise.resolve();#callTimeoutMs;constructor(child,{callTimeoutMs=DEFAULT_CALL_TIMEOUT_MS,protocol="line",account=null}={}){this.#transport=protocol==="mcp"?new McpTransport(child):new LineTransport(child);this.#callTimeoutMs=callTimeoutMs;this.engine="aside";this.account=account;this.sessionDir=null}async ready(timeoutMs=DEFAULT_START_TIMEOUT_MS){const{account,sessionDir}=await this.#transport.ready(timeoutMs);if(account)this.account=account;if(sessionDir)this.sessionDir=sessionDir;return this}async run(code){return(await this.runWithLogs(code)).value}async runWithLogs(code){if(typeof code!=="string"||code.trim()==="")throw new TypeError("run() needs JavaScript source");const tag=`OMOW_RESULT_${randomBytes2(6).toString("hex")}:`;const body=`(async () => {
|
|
1413
|
+
${code}
|
|
1414
|
+
})()`;const line=`try { const omowValue = await eval(${JSON.stringify(body)}); const omowJson = JSON.stringify(omowValue ?? null); console.log(${JSON.stringify(tag)} + (omowJson === undefined ? '{"unserializable":true}' : '{"value":' + omowJson + '}')); } catch (omowError) { console.log(${JSON.stringify(tag)} + JSON.stringify({ error: String(omowError?.stack ?? omowError) })); }`;const output=await this.#call(line,tag);const logs=[];let value;let found=false;for(const entry of output){if(entry.startsWith(tag)){let parsed;try{parsed=JSON.parse(entry.slice(tag.length))}catch{parsed={unserializable:true}}const result=isObject2(parsed)?parsed:{};if(result["error"]!==undefined)throw new AsideReplError("repl_error",String(result["error"]),{output:logs});if(result["unserializable"])throw new AsideReplError("repl_unserializable","the code returned a value with no JSON form (a function, symbol or undefined member); return plain data",{output});value=result["value"];found=true}else{logs.push(entry)}}if(!found)throw new AsideReplError("repl_no_result","aside repl finished the call without a result line",{output});return{value,logs}}async open(url){return this.run(`const omowTab = await openTab(${JSON.stringify(String(url))});
|
|
1415
|
+
return { url: omowTab.url(), title: await omowTab.title() };`)}async snapshot({find,context,interactive,showHidden,selector,ref}={}){validateSnapshotOptions({find,context});const options=Object.fromEntries(Object.entries({interactive,showHidden,selector,ref}).filter(([,value])=>value!==undefined));const result=await this.run(`if (!page) throw new Error("no current page: call open(url) first");
|
|
1416
|
+
const omowSnap = await snapshot(page, ${JSON.stringify(options)});
|
|
1417
|
+
return { tree: omowSnap.tree, diff: omowSnap.diff };`);if(find===undefined)return result;const tree=isObject2(result)&&typeof result["tree"]==="string"?result["tree"]:undefined;const found=findSnapshotLines({tree,refs:{}},find,context);return{tree:found.tree,find:found.find}}async close(){await this.#transport.close()}#call(line,tag){const run=this.#queue.then(()=>this.#transport.call(line,{tag,timeoutMs:this.#callTimeoutMs}));this.#queue=run.catch(()=>{});return run}}async function connectAside({account,host,asideCommand,autoSetup=true,env=process.env,home,startTimeoutMs=DEFAULT_START_TIMEOUT_MS,callTimeoutMs=DEFAULT_CALL_TIMEOUT_MS,spawn=spawnChild}={}){let command=asideCommand;if(!command&&autoSetup){const setup=await asideOnboard({env,account,installOnlyWithApp:true,...home?{home}:{}});if(!setup.ready)throw new AsideReplError("aside_not_ready",String(setup.nextStep),{setup});command=[setup.cli.bin]}command??=[findAsideBinary({env,...home?{home}:{}})];const[bin,...lead]=command;if(!bin){throw new AsideReplError("aside_not_found","the Aside CLI is not installed: install it from Aside Settings > Developers, or set ASIDE_BIN")}const cliCommand=[bin,...lead];const cli={spawn,command:cliCommand,env};const protocol=await replTransportFor({...cli,timeoutMs:CLI_PROBE_TIMEOUT_MS});const subcommand=protocol==="mcp"?"mcp":"repl";const args=[...lead,subcommand];if(account)args.push("--account",account);if(host)args.push("--host",host);const childEnv=protocol==="mcp"&&env["ASIDE_MCP_REPL_IDLE_TIMEOUT_MS"]===undefined?{...env,ASIDE_MCP_REPL_IDLE_TIMEOUT_MS:"0"}:env;const child=spawn(bin,args,{env:childEnv,stdio:["pipe","pipe","pipe"],windowsHide:true});const spawned=new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",(error)=>reject(new AsideReplError("repl_start_failed",`could not start aside ${subcommand}: ${error.message}`)))});await spawned;if(!hasPipes(child)){child.kill();throw new AsideReplError("repl_start_failed",`aside ${subcommand} started without stdin and stdout pipes`)}const session=new AsideSession(child,{callTimeoutMs,protocol,account:account??null});try{return await session.ready(startTimeoutMs)}catch(error){child.kill();if(!(error instanceof AsideReplError)||error.code!=="repl_start_timeout")throw error;const version=await asideCliVersion({...cli,timeoutMs:CLI_PROBE_TIMEOUT_MS});throw new AsideReplError("repl_start_timeout",`aside ${subcommand} (Aside CLI ${version??"of unknown version"}) did not answer within ${startTimeoutMs} ms`,{output:error.output})}}function requireEgo(ego){if(!ego||typeof ego.sendCDPMessage!=="function"){throw new EgoCdpError("ego_unavailable","Ego Lite bindings are unavailable: run inside `ego-browser nodejs`, or pass { ego }")}return ego}class EgoCdpError extends Error{constructor(code,message,{method}={}){super(message);this.name="EgoCdpError";this.code=code;if(method)this.method=method}}var DEFAULT_COMMAND_TIMEOUT_MS3=30000;var isObject3=(value)=>typeof value==="object"&&value!==null;var sessionIdOf=(value)=>typeof value==="string"?value:undefined;var stringOr=(value,fallback)=>typeof value==="string"?value:fallback;class EgoCdpClient{#ego;#seq=randomInt2(1,1073741824);#onMessageHandler=(payload)=>this.#onMessage(payload);#onSendErrorHandler=(message,code)=>this.#onSendError(message,code);#pending=new Map;#closedSessions=new Set;#events=new SerialEmitter;#connected=false;#commandTimeoutMs;#dialogPolicy;transportEvents=new SerialEmitter;logId;isHeadless=false;constructor({ego=globalThis.ego,commandTimeoutMs,logId,dialogPolicy}={}){this.#ego=requireEgo(ego);this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS3;this.logId=logId??`cdp-ego-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;if(this.#ego.onCDPMessage||this.#ego.onSendCDPMessageError){throw new EgoCdpError("ego_busy","another client already holds Ego's CDP callbacks in this runtime; close it first")}this.#ego.onCDPMessage=this.#onMessageHandler;this.#ego.onSendCDPMessageError=this.#onSendErrorHandler;this.#connected=true;await this.#dispatch("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected",undefined)}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO."))throw Error(`Extension commands are unavailable over the Ego transport: ${method}`);await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}#dispatch(method,params,sessionId,opts={}){if(!this.#connected)return Promise.reject(new EgoCdpError("ego_closed",`Ego CDP client is closed: ${method}`,{method}));if(sessionId&&this.#closedSessions.has(sessionId)&&method!=="Page.close"){return Promise.reject(new CdpSessionDetachedError(`Page closed: ${method}`,{method,sessionId}))}const id=this.#seq++;const message={id,method};if(params!==undefined)message.params=params;if(sessionId)message.sessionId=sessionId;const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(new CdpCommandTimeoutError(`CDP command timeout: ${method}`,{method,sessionId:sessionId??null}))},timeoutMs):undefined;this.#pending.set(id,{method,sessionId,resolve,reject,timeout});try{this.#ego.sendCDPMessage(JSON.stringify(message))}catch(error){this.#take(id);const errorCode=isObject3(error)?error["error_code"]:undefined;const errorMessage=isObject3(error)?error["message"]:undefined;return Promise.reject(new EgoCdpError(String(errorCode??"ego_send_failed"),String(errorMessage??String(error)),{method}))}return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const result=await this.send("Target.getTargets");const targetInfos=isObject3(result)?result.targetInfos:undefined;if(!Array.isArray(targetInfos))throw new TypeError("Target.getTargets returned no targetInfos array");return targetInfos.map((t)=>{const info=isObject3(t)?t:{};return{id:stringOr(info["targetId"],""),type:stringOr(info["type"],""),url:stringOr(info["url"],""),title:stringOr(info["title"],""),description:stringOr(info["description"],undefined),faviconUrl:stringOr(info["faviconUrl"],undefined),parentId:stringOr(info["openerId"],undefined)}})}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failWhere((entry)=>entry.sessionId===sessionId,(entry)=>new CdpSessionDetachedError(`Page closed: ${entry.method}`,{method:entry.method,sessionId}))}async close(){if(!this.#connected)return;this.#connected=false;if(this.#ego.onCDPMessage===this.#onMessageHandler)this.#ego.onCDPMessage=undefined;if(this.#ego.onSendCDPMessageError===this.#onSendErrorHandler)this.#ego.onSendCDPMessageError=undefined;this.#failWhere(()=>true,(entry)=>new EgoCdpError("ego_closed",`Ego CDP client closed: ${entry.method}`,{method:entry.method}));await this.transportEvents.emit("disconnected",undefined).catch(()=>{})}#take(id){const entry=this.#pending.get(id);if(!entry)return null;this.#pending.delete(id);if(entry.timeout)clearTimeout(entry.timeout);return entry}#failWhere(match,makeError){for(const[id,entry]of this.#pending){if(!match(entry))continue;this.#take(id);entry.reject(makeError(entry))}}#onSendError(message,code){let id;try{const parsed=JSON.parse(message);id=isObject3(parsed)?parsed["id"]:undefined}catch{id=undefined}const reason=`Ego refused the CDP send (${code??"unknown"})`;if(typeof id==="number"){const entry=this.#take(id);if(entry)entry.reject(new EgoCdpError(code??"ego_send_refused",`${reason}: ${entry.method}`,{method:entry.method}));return}this.#failWhere(()=>true,(entry)=>new EgoCdpError(code??"ego_send_refused",`${reason}: ${entry.method}`,{method:entry.method}))}#onMessage(payload){let msg;try{msg=JSON.parse(payload)}catch{return}if(msg===null)throw new TypeError("Cannot read properties of null (reading 'id')");if(!isObject3(msg))return;if(typeof msg["id"]==="number"){const entry=this.#take(msg["id"]);if(!entry)return;if(msg["error"]){const cdpError=isObject3(msg["error"])?msg["error"]:{};const error=Object.assign(Error(String(cdpError["message"]??`CDP command failed: ${entry.method}`)),{code:cdpError["code"],data:cdpError["data"]});entry.reject(error)}else{entry.resolve(msg["result"])}return}const method=msg["method"];if(typeof method!=="string")return;const params=msg["params"];const sessionId=sessionIdOf(msg["sessionId"]);const detachedSessionId=isObject3(params)?params["sessionId"]:undefined;if(method==="Target.detachedFromTarget"&&detachedSessionId){this.#failWhere((entry)=>entry.sessionId===detachedSessionId,(entry)=>new CdpSessionDetachedError(`CDP session detached: ${entry.method}`,{method:entry.method,sessionId:detachedSessionId}))}else if(method==="Inspector.targetCrashed"&&sessionId){this.#failWhere((entry)=>entry.sessionId===sessionId&&entry.method!=="Page.reload",(entry)=>new CdpSessionCrashedError(`CDP session crashed: ${entry.method}`,{method:entry.method,sessionId}))}const meta={sessionId};const dialog=method==="Page.javascriptDialogOpening"&&sessionId?new Dialog(dialogPolicyParams(params),(action)=>this.send("Page.handleJavaScriptDialog",action,sessionId)):undefined;if(dialog)meta.dialog=dialog;const emitted=this.#events.emit(method,{data:{payload:params,meta}}).catch(()=>{});return dialog?emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,dialogPolicyParams(params))).catch(()=>{}):undefined}}async function selectTaskSpace(ego,{taskSpace,taskName,profileId}){if(taskSpace!==undefined){if(!Number.isInteger(taskSpace))throw new TypeError("taskSpace is Ego's numeric task-space id (ego.listTaskSpaces()[i].id)");ego.useTaskSpace(taskSpace);return{id:taskSpace}}if(typeof ego.createTaskSpace!=="function"||typeof ego.useTaskSpace!=="function"){throw new EgoCdpError("ego_task_space_unsupported","this Ego runtime has no createTaskSpace/useTaskSpace; pass taskSpace with an id the agent already claimed")}const created=await ego.createTaskSpace(taskName??`omowright-${Date.now()}`,...profileId?[profileId]:[]);if(!created||created.error){throw new EgoCdpError(String(created?.error_code??"ego_task_space_failed"),`Ego could not create a task space: ${created?.error??"no result"}`)}ego.useTaskSpace(created.id);return created}async function connectEgo({ego:egoOption=globalThis.ego,taskSpace,taskName,profileId,storageRoot,commandTimeoutMs,logId,dialogPolicy}={}){const ego=requireEgo(egoOption);const client=new EgoCdpClient({ego,commandTimeoutMs,logId,dialogPolicy});if(ego.onCDPMessage||ego.onSendCDPMessageError){throw new EgoCdpError("ego_busy","another client already holds Ego's CDP callbacks in this runtime; close it first")}const space=await selectTaskSpace(ego,{taskSpace,taskName,profileId});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();return Object.assign(connection,{engine:"ego",taskSpace:space})}function requireDir(dir,join){if(typeof dir==="string")return dir;Reflect.apply(join,undefined,[dir]);throw new TypeError(`path.join accepted a ${typeof dir} directory`)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`
|
|
1418
|
+
`;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:pathFor(platform).join(requireDir(browser.externalDir,pathFor(platform).join),`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:pathFor(platform).join(requireDir(browser.userDataDir,pathFor(platform).join),"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync7}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path23.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}const uninstalls=optionalProperty(optionalProperty(prefs,"extensions"),"external_uninstalls");if(Array.isArray(uninstalls)&&uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn9(windowsSystemTool("reg.exe"),args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync4,readFile=readFileSync7,runReg=runRegDefault}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeHint=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeHint}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeHint};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync3(path23.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){const code=readProperty(error,"code");if(code==="EACCES"||code==="EPERM"||code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeHint}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync9(entry.path);if(present)rmSync4(entry.path,{force:true});return{...entry,removed:present}}var PROBE_TIMEOUT_MS2=3000;function runDefault2(command,args){return new Promise((resolve)=>{execFile4(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=optionalProperty(JSON.parse(plistJson),"LSHandlers")}catch{return null}if(!Array.isArray(handlers))return null;const list=handlers;const pick=(scheme)=>{const handler=list.find((h)=>optionalProperty(h,"LSHandlerURLScheme")===scheme&&typeof readProperty(h,"LSHandlerRoleAll")==="string");return handler===undefined?undefined:readProperty(handler,"LSHandlerRoleAll")};const role=pick("https")??pick("http");return typeof role==="string"?role.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?.[1]?.toLowerCase()??null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path24.posix.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path24.posix.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run(windowsSystemTool("reg.exe"),["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run(windowsSystemTool("tasklist.exe"),["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat,{join}){let latest=null;for(const rel of[["Local State"],["Default","History"],["Default","Preferences"]]){try{const mtime=stat(join(browser.userDataDir,...rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir7(),browsers=[],run=runDefault2,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat,pathFor(platform))]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=604800000;var OWN_TOKEN_NAMES=new Set(["edge","opera","brave","arc"]);var FAMILY_NAMES=new Set(["chrome","chromium"]);var ALWAYS_SEND_OWN_TOKEN=new Set(["edge","opera"]);function sentBy(name,candidates){if(OWN_TOKEN_NAMES.has(name))return candidates.filter((c)=>c.id===name);if(!FAMILY_NAMES.has(name))return[];const running=candidates.filter((c)=>!ALWAYS_SEND_OWN_TOKEN.has(c.id)&&c.running===true);return running.length===1?running:[]}function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter((signal)=>Boolean(signal));return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser:_browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser:_browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,connected=[],now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const attached=[...new Set(connected.flatMap((name)=>sentBy(name,candidates)))];const firstAttached=attached[0];if(attached.length===1&&firstAttached)return choose(candidates,firstAttached,"connected",`${firstAttached.label} has the BrowserSkill extension connected`,defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);const firstInUse=inUse[0];if(defaultBrowser.supported===false){const suggested=inUse.length===1?firstInUse?.id??null:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);const firstRunning=runningNow[0];const onlyCandidate=candidates[0];if(inUse.length===1&&firstInUse)return choose(candidates,firstInUse,"only-in-use",`${firstInUse.label} is the only browser ${firstInUse.signals.join(", ")}`,defaultBrowser);if(runningNow.length===1&&firstRunning)return choose(candidates,firstRunning,"only-running",`${firstRunning.label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1&&onlyCandidate)return choose(candidates,onlyCandidate,"only-installed",`${onlyCandidate.label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}function requirePrimary(primary){if(!primary)throw new TypeError("identifyBrowser chose no primary browser without asking for a choice");return primary}var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport2({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:readProperty(status,"daemon_version"),protocolVersion:readProperty(status,"protocol_version"),browsers:readProperty(status,"browsers")??[],sessions:readProperty(status,"sessions")??[]}}catch(error){const message=readProperty(error,"message");return{running:false,error:message,code:readProperty(error,"code"),startBlocked:NO_BREAKAWAY2.test(String(message)),browsers:[],sessions:[]}}}var NO_BREAKAWAY2=/Job Object|breakaway/i;var FOREGROUND_STEP="run `bsk daemon start --foreground` in a persistent background session of the agent host (one that outlives the command, not a one-shot shell call), then check it with `bsk status` from a separate call";function daemonStep(daemon){if(daemon.startBlocked)return`Start the BrowserSkill daemon: this host does not let a command detach it (Windows Job Object breakaway is prohibited), so retrying \`bsk status\` or \`bsk daemon start\` fails the same way; ${FOREGROUND_STEP}.`;return`Start the BrowserSkill daemon: bskOnboard() (or \`bsk status\` once) starts it. If the host reaps background processes or the start fails, ${FOREGROUND_STEP}; do not retry a detached \`bsk daemon start\`.`}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync10(entry.path)&&readFileSync8(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,connected,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env["OMOWRIGHT_BROWSER"]??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,connected,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor2({cli,daemon,browsers,browsersConnected,identification,primary:chosen}){if(browsersConnected.length>0)return browsersConnected.every(isTabGroupingExtension)?TAB_GROUPING_EXTENSION_STEP:null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return daemonStep(daemon);if(browsers.length===0&&!chosen)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);const primary=requirePrimary(chosen);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir8(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync10,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport2({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const browsersConnected=listOrEmpty(daemon.browsers,"system.status browsers");const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,connected:browsersConnected.map((b)=>readProperty(b,"browser_name")),signals,probeSignals,now});const outdatedExtensions=browsersConnected.filter(isTabGroupingExtension);const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,outdatedExtensions,ready:browsersConnected.length>outdatedExtensions.length};report.nextStep=nextStepFor2(report);return report}async function bskOnboard({platform=process.platform,home=homedir8(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync10,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport2({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport2({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);let browsersConnected=listOrEmpty(daemon.browsers,"system.status browsers");const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,connected:browsersConnected.map((b)=>readProperty(b,"browser_name")),signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(browsersConnected.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else if(daemon.running){const chosen=requirePrimary(primary);const registration=await registerExternalExtension({platform,browser:chosen});registrations.push({browser:chosen.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:chosen.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const outdatedExtensions=browsersConnected.filter(isTabGroupingExtension);const ready=browsersConnected.length>outdatedExtensions.length;if(!ready&&outdatedExtensions.length>0){humanStep=TAB_GROUPING_EXTENSION_STEP;onHumanStep({browser:readProperty(outdatedExtensions[0],"browser_name"),step:humanStep,registered:true,needsRestart:false})}const nextStep=ready?null:humanStep??nextStepFor2({cli,daemon,browsers,browsersConnected,identification,primary});return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,nextStep,browsersConnected,outdatedExtensions,ready}}var ENGINE_ORDER=Object.freeze(["aside","ego","bsk","cloak"]);var ENGINE_NAMES=new Set(ENGINE_ORDER);var isEngineName=(name)=>ENGINE_NAMES.has(name);function engineName(name){if(!isEngineName(name))throw new TypeError(`unknown browser engine "${name}"; expected one of ${ENGINE_ORDER.join(", ")}`);return name}class NoBrowserEngineError extends Error{constructor(attempts){super(`no browser engine connected: ${attempts.map((a)=>`${a.engine}: ${a.reason}`).join("; ")}`);this.name="NoBrowserEngineError";this.code="no_engine";this.attempts=attempts}}async function targetCount(handle){try{return(await handle.listTargets()).length}catch(error){await handle.close().catch(()=>{});throw error}}var ENGINES={aside:async(options)=>{let handle;try{handle=await connectAside(options)}catch(error){if(error instanceof AsideReplError&&error.code==="aside_not_ready")return{skipped:error.message};throw error}try{if(await handle.run("return true")!==true)throw new Error("aside repl did not echo a probe value")}catch(error){await handle.close().catch(()=>{});throw error}return{handle,verified:"aside repl evaluated a probe call"}},ego:async(options)=>{const ego=options.ego??globalThis.ego;if(!ego||typeof ego.sendCDPMessage!=="function")return{skipped:"Ego Lite bindings are absent (only inside `ego-browser nodejs`)"};const handle=await connectEgo({...options,ego});return{handle,verified:`CDP listed ${await targetCount(handle)} targets in task space ${handle.taskSpace?.id??"?"}`}},bsk:async(options)=>{const handle=await connectBrowserSkill(options);return{handle,verified:`BrowserSkill started session ${handle.sessionId} in browser ${String(handle.browserInstanceId??"?")}`}},cloak:async(options)=>{const handle=await connectCloakProfile(options);return{handle,verified:`CDP listed ${await targetCount(handle)} targets in the CloakBrowser profile`}}};function runEngine(engine,options){return ENGINES[engine](options)}function reasonOf(error){const code=optionalProperty(error,"code");return`${code?`${code}: `:""}${optionalProperty(error,"message")??String(error)}`}function closeHandle(handle){return handle instanceof BskSession?handle.stop():handle.close()}async function connectBrowser({prefer,allow=ENGINE_ORDER,crossCheck=false,...perEngine}={}){for(const name of[prefer,...allow].filter(Boolean))engineName(name);const order=prefer?[engineName(prefer),...ENGINE_ORDER.filter((name)=>name!==prefer)]:[...ENGINE_ORDER];const attempts=[];let primary=null;const extra=[];for(const engine of order){if(!allow.includes(engine)){attempts.push({engine,ok:false,reason:"not allowed by the caller"});continue}if(primary&&!crossCheck){attempts.push({engine,ok:false,reason:`not tried: ${primary.engine} connected first`});continue}const started=performance.now();try{const result=await runEngine(engine,perEngine[engine]??{});const ms=Math.round(performance.now()-started);if(result.skipped!==undefined){attempts.push({engine,ok:false,ms,reason:result.skipped});continue}attempts.push({engine,ok:true,ms,verified:result.verified});if(primary)extra.push({engine,handle:result.handle});else primary={engine,handle:result.handle}}catch(error){attempts.push({engine,ok:false,ms:Math.round(performance.now()-started),reason:reasonOf(error)})}}if(!primary)throw new NoBrowserEngineError(attempts);const opened=[primary,...extra];return{engine:primary.engine,handle:primary.handle,attempts,attached:opened.map((entry)=>entry.engine),crossCheck:extra,closeAll:async()=>{await Promise.all(opened.map(({handle})=>closeHandle(handle).catch(()=>{})))}}}export{AgentTabManager,AsideReplError,AsideSession,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CdpCommandTimeoutError,CdpPipeClosedError,CdpSessionCrashedError,CdpSessionDetachedError,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ENGINE_ORDER,EgoCdpClient,EgoCdpError,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,NetworkBodyUnavailableError,NoBrowserEngineError,OMOWRIGHT_PAGE_CDP_METHODS,OmOKeyboard,OmOMouse,OmOPage,PAGE_EVENT_NAMES,PipeCdpClient,ResponseSchema,RunningBrowserError,STORE_PAGE_URLS,SessionManager,SharedConnectionError,TabRepository,UnsupportedOperationError,VideoRecordingError,WaitForFunctionTimeoutError,asideDoctor,asideOnboard,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectAside,connectBrowser,connectBrowserSkill,connectCloakProfile,connectEgo,connectNamed,connectPipe,connectRunningBrowser,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findAsideBinary,findCloakBrowserPath,findRunningBrowser,identifyBrowser,injectCookies,installAsideCli,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,listInstances,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,readDevToolsActivePort,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,selectors,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};
|