@diffclarity/companion 0.3.1 → 0.4.0
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/README.md +20 -3
- package/dist/main.js +20 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -16,8 +16,8 @@ ${ind(d)}}`;output=wrap(v,body)}}return ancestors.delete(v),output}return String
|
|
|
16
16
|
`);lines.splice(1,3),error.stack=lines.join(`
|
|
17
17
|
`)}return error};var Reference=Service;var isArrayNonEmpty=(self)=>self.length>0;var succeed2=succeed,fail2=fail;var isFailure2=isFailure;var match=dual(2,(self,{onFailure,onSuccess})=>isFailure2(self)?onFailure(self.failure):onSuccess(self.success));var Array2=globalThis.Array;var append=dual(2,(self,last)=>[...self,last]);var isArray=Array2.isArray;var isArrayNonEmpty2=isArrayNonEmpty,isReadonlyArrayNonEmpty=isArrayNonEmpty;var empty2=()=>[];var map=dual(2,(self,f)=>self.map(f));var Scheduler=Reference("effect/Scheduler",{fiberCached:!0,defaultValue:()=>new MixedScheduler}),setMicrotask=(f)=>{let cancelled=!1;return Promise.resolve().then(()=>{if(!cancelled)f()}),()=>{cancelled=!0}},setTimer="setImmediate"in globalThis?(f)=>{let timer=globalThis.setImmediate(f);return()=>globalThis.clearImmediate(timer)}:(f)=>{let timer=setTimeout(f,0);return()=>clearTimeout(timer)},setImmediate=(f)=>{try{return setTimer(f)}catch{return setMicrotask(f)}};class PriorityBuckets{buckets=[];scheduleTask(task,priority){let buckets=this.buckets,len=buckets.length,bucket,index=0;for(;index<len;index++){if(buckets[index][0]>priority)break;bucket=buckets[index]}if(bucket&&bucket[0]===priority)bucket[1].push(task);else if(index===len)buckets.push([priority,[task]]);else buckets.splice(index,0,[priority,[task]])}drain(){let buckets=this.buckets;return this.buckets=[],buckets}}class MixedScheduler{executionMode;setImmediate;constructor(executionMode="async",setImmediateFn){this.executionMode=executionMode,this.setImmediate=setImmediateFn??(executionMode==="sync"?setMicrotask:setImmediate)}shouldYield(fiber){return fiber.currentOpCount>=fiber.cache.maxOpsBeforeYield}makeDispatcher(){return new MixedSchedulerDispatcher(this.setImmediate)}}class MixedSchedulerDispatcher{tasks=new PriorityBuckets;running=void 0;setImmediate;constructor(setImmediateFn=setImmediate){this.setImmediate=setImmediateFn}scheduleTask(task,priority){if(this.tasks.scheduleTask(task,priority),this.running===void 0)this.running=this.setImmediate(this.afterScheduled)}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let buckets=this.tasks.drain();for(let i=0;i<buckets.length;i++){let toRun=buckets[i][1];for(let j=0;j<toRun.length;j++)toRun[j]()}}flush(){while(this.tasks.buckets.length>0){if(this.running!==void 0)this.running(),this.running=void 0;this.runTasks()}}}var MaxOpsBeforeYield=Reference("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:!0,defaultValue:()=>2048}),PreventSchedulerYield=Reference("effect/Scheduler/PreventSchedulerYield",{fiberCached:!0,defaultValue:()=>!1});var TaggedError2=TaggedError;var EncodingErrorTypeId="~effect/encoding/EncodingError";class EncodingError extends TaggedError2("EncodingError"){[EncodingErrorTypeId]=EncodingErrorTypeId}var ParentSpanKey="effect/Tracer/ParentSpan";var TracerKey="effect/Tracer";var FiberRuntimeMetricsKey="effect/Metric/FiberRuntimeMetrics";var CurrentStackFrame=Reference("effect/References/CurrentStackFrame",{fiberCached:!0,defaultValue:constUndefined}),TracerEnabled=Reference("effect/References/TracerEnabled",{fiberCached:!0,defaultValue:constTrue});var CurrentLogLevel=Reference("effect/References/CurrentLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),MinimumLogLevel=Reference("effect/References/MinimumLogLevel",{fiberCached:!0,defaultValue:()=>"Info"});class Interrupt extends ReasonBase{constructor(fiberId,annotations=constEmptyAnnotations){super("Interrupt",annotations,"Interrupted");this.fiberId=fiberId}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[symbol2](that){return isInterruptReason(that)&&this.fiberId===that.fiberId&&this.annotations===that.annotations}[symbol](){return string(`${this._tag}:${this.fiberId}`)}}var causeInterrupt=(fiberId)=>new CauseImpl([new Interrupt(fiberId)]),hasFails=(self)=>self.reasons.some(isFailReason);var hasDies=(self)=>self.reasons.some(isDieReason),causeElectDefects=(self)=>hasDies(self)&&hasFails(self)?causeFromReasons(self.reasons.map((reason)=>reason._tag==="Fail"&&!isDone(reason.error)?new Die(reason.error,reason.annotations):reason)):self;var hasInterrupts=(self)=>self.reasons.some(isInterruptReason);var causeMap=dual(2,(self,f)=>{let hasFail=!1,failures=self.reasons.map((failure)=>{if(isFailReason(failure))return hasFail=!0,new Fail(f(failure.error),failure.annotations);return failure});return hasFail?causeFromReasons(failures):self});var FiberTypeId="~effect/Fiber",fiberVariance={_A:identity,_E:identity},fiberIdStore={id:0},AsyncResource=(()=>{try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource}catch{return}})(),captureAsyncContext=()=>AsyncResource===void 0?void 0:new AsyncResource("effect/Fiber"),getCurrentFiber=()=>globalThis[currentFiberTypeId];class FiberImpl{constructor(context,interruptible=!0){this.setContext(context),this.id=++fiberIdStore.id,this.currentOpCount=0,this.interruptible=interruptible,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[FiberTypeId](){return fiberVariance}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(ref){return get(this.context,ref)}addObserver(cb){if(this._exit)return cb(this._exit),constVoid;if(this._observers===void 0)this._observers=[cb];else this._observers.push(cb);return()=>this.removeObserver(cb)}removeObserver(cb){if(this._exit||this._observers===void 0)return;let index=this._observers.indexOf(cb);if(index>=0)this._observers.splice(index,1)}interruptUnsafe(fiberId,annotations){if(this._exit)return;let cause=causeInterrupt(fiberId);if(this.cache.stackFrame)cause=causeAnnotate(cause,make2(StackTraceKey,this.cache.stackFrame));if(annotations)cause=causeAnnotate(cause,annotations);if(this._interruptedCause=this._interruptedCause?causeAddInterrupts(this._interruptedCause,cause):cause,this.interruptible)if(this._running)this._deferredInterrupt=!0;else this.evaluate(failCause(this._interruptedCause))}pollUnsafe(){return this._exit}evaluate(effect){if(this._exit)return;else if(this._asyncContext!==void 0){let asyncContext=this._asyncContext;this._asyncContext=void 0;try{return asyncContext.runInAsyncScope(this.evaluate,this,effect)}finally{asyncContext.emitDestroy()}}else if(this._yielded!==void 0){let yielded=this._yielded;this._yielded=void 0,yielded()}let exit=this.runLoop(effect);if(exit===Yield){this._asyncContext=captureAsyncContext();return}let interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==void 0)return this.evaluate(flatMap(interruptChildren,()=>exit));if(this._exit=exit,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent)this._parent._children?.delete(this),this._parent=void 0;if(this._observers!==void 0){let observers=this._observers;this._observers=void 0;for(let i=0;i<observers.length;i++)observers[i](exit)}this._stack.length=0,this._children=void 0,this.context=empty();let cache=this.cache;if(cache.span!==void 0||cache.stackFrame!==void 0)this.cache={...cache,span:void 0,stackFrame:void 0}}runLoop(effect){let prevFiber=globalThis[currentFiberTypeId];globalThis[currentFiberTypeId]=this;let prevRunning=this._running;this._running=!0;let yielding=!1,current=effect;this.currentOpCount=0;try{while(!0)try{if(this._deferredInterrupt)this._deferredInterrupt=!1,current=failCause(this._interruptedCause);this.currentOpCount++;let cache=this.cache;if(!yielding&&!cache.preventYield&&cache.scheduler.shouldYield(this)){yielding=!0;let prev=current;current=flatMap(yieldNow,()=>prev)}if(current=cache.tracerContext?cache.tracerContext(current,this):current[evaluate](this),current===Yield){let yielded=this._yielded;if(ExitTypeId in yielded)return this._deferredInterrupt=!1,this._yielded=void 0,yielded;else if(this._deferredInterrupt){this._yielded=void 0,yielded();continue}return Yield}}catch(error){if(!hasProperty(current,evaluate))return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`);current=exitDie(error)}}finally{this._running=prevRunning,globalThis[currentFiberTypeId]=prevFiber}}getCont(symbol){if(this._deferredInterrupt)return this._deferredInterrupt=!1,deferredInterruptCont;while(!0){let op=this._stack.pop();if(!op)return;let all=op[contAll];if(all!==void 0){let cont=all.call(op,this);if(cont)return cont[symbol]=cont,cont}if(op[symbol])return op}}succeedWith(value){if((++this.currentOpCount&maxInlineSteps-1)===0)return exitSucceed(value);let cont=this.getCont(contA);return cont?cont[contA](value,this):this.yieldWith(exitSucceed(value))}yieldWith(value){return this._yielded=value,Yield}children(){return this._children??=new Set}pipe(){return pipeArguments(this,arguments)}setContext(context){let previous=this.context;if(this.context=context,previous!==void 0&&hasSameCache(previous,context))return;let root=context.cacheRoot,cache=root._fiberCache??=makeFiberContextCache(context);if(this.cache?.scheduler!==cache.scheduler)this._dispatcher=void 0;this.cache=cache}get currentSpanLocal(){let span=this.cache.span;return span?._tag==="Span"?span:void 0}}var makeFiberContextCache=(context)=>{let currentTracer=getOrUndefinedUnsafe(context,TracerKey);return{scheduler:get(context,Scheduler),tracer:currentTracer,tracerContext:currentTracer?currentTracer.context:void 0,tracerEnabled:get(context,TracerEnabled),span:getOrUndefinedUnsafe(context,ParentSpanKey),logLevel:get(context,CurrentLogLevel),minimumLogLevel:get(context,MinimumLogLevel),stackFrame:get(context,CurrentStackFrame),runtimeMetrics:getOrUndefinedUnsafe(context,FiberRuntimeMetricsKey),maxOpsBeforeYield:get(context,MaxOpsBeforeYield),preventYield:get(context,PreventSchedulerYield)}},deferredInterruptCont={[contA](_value,fiber){return failCause(fiber._interruptedCause)},[contE](_cause,fiber){return failCause(fiber._interruptedCause)}},maxInlineSteps=32,fiberMiddleware={interruptChildren:void 0},fiberStackAnnotations=(fiber)=>{if(!fiber.cache.stackFrame)return;let annotations=new Map;return annotations.set(InterruptorStackTrace.key,fiber.cache.stackFrame),makeUnsafe(annotations)};var fiberAwaitAll=(self)=>callback((resume)=>{let iter=self[Symbol.iterator](),exits=[],cancel=void 0;function loop(){let result=iter.next();while(!result.done){if(result.value._exit){exits.push(result.value._exit),result=iter.next();continue}cancel=result.value.addObserver((exit)=>{exits.push(exit),loop()});return}resume(succeed3(exits))}return loop(),sync(()=>cancel?.())});var fiberInterruptAll=(fibers)=>withFiber((parent)=>{let annotations=fiberStackAnnotations(parent),fiberArr=empty2();for(let fiber of fibers)fiber.interruptUnsafe(parent.id,annotations),fiberArr.push(fiber);return asVoid(fiberAwaitAll(fiberArr))});var succeed3=exitSucceed,failCause=exitFailCause,fail3=exitFail,sync=makePrimitive({op:"Sync",[evaluate](fiber){let thunk=this[args],value=thunk(),cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}}),suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){let thunk=this[args];return thunk()}});var fromResult=match({onFailure:fail3,onSuccess:succeed3});var yieldNowWith=makePrimitive({op:"Yield",[evaluate](fiber){let resumed=!1;return fiber.currentDispatcher.scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid)},this[args]??0),fiber.yieldWith(()=>{resumed=!0})}}),yieldNow=yieldNowWith(0);var failCauseSync=(evaluate)=>suspend(()=>failCause(evaluate())),die=(defect)=>exitDie(defect);var void_=succeed3(void 0);var try_=(options)=>{let evaluate=typeof options==="function"?options:options.try,catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.try"):options.catch;return suspend(()=>{try{return succeed3(evaluate())}catch(err){return fail3(catcher(err))}})};var tryPromise=(options)=>{let f=typeof options==="function"?options:options.try,catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.tryPromise"):options.catch;return callbackOptions(function(resume,signal){let failWithCatch=(cause)=>suspend(()=>{try{return fail3(internalCall(()=>catcher(cause)))}catch(err){return die(err)}});try{f(signal).then((a)=>resume(succeed3(a)),(e)=>resume(failWithCatch(e)))}catch(err){resume(failWithCatch(err))}},f.length!==0)};var callbackOptions=function(){let Proto=makePrimitiveProto({op:"Async",[evaluate](fiber){let resumed=!1,yielded=!1,controller=this.withSignal?new AbortController:void 0,onCancel=this.register.call(fiber.cache.scheduler,(effect)=>{if(resumed)return;if(resumed=!0,yielded)fiber.evaluate(effect);else yielded=effect},controller?.signal);if(yielded!==!1)return yielded;if(yielded=!0,fiber.yieldWith(()=>{resumed=!0}),controller===void 0&&onCancel===void 0)return Yield;return fiber._stack.push(asyncFinalizer(()=>(resumed=!0,controller?.abort(),onCancel??exitVoid))),Yield}}),AsyncImpl=function(register,withSignal){this.register=register,this.withSignal=withSignal};return AsyncImpl.prototype=Proto,function(register,withSignal){return new AsyncImpl(register,withSignal)}}(),asyncFinalizer=makePrimitive({op:"AsyncFinalizer",[contAll](fiber){if(fiber.interruptible)fiber.interruptible=!1,fiber._stack.push(setInterruptibleTrue)},[contE](cause,_fiber){return hasInterrupts(cause)?flatMap(combineFinalizerCause(exitFailCause(cause),this[args]()),()=>failCause(cause)):failCause(cause)}}),callback=(register)=>callbackOptions(register,register.length>=2);var fnBody=(bodyOrOptions,pipeables)=>typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.shift().bind(bodyOrOptions.self);var defineFunctionLength=(length,fn)=>Object.defineProperty(fn,"length",{value:length,configurable:!0});var fnUntracedEager=(bodyOrOptions,...pipeables)=>{let body=fnBody(bodyOrOptions,pipeables);return defineFunctionLength(body.length,pipeables.length===0?function(){return fromIteratorEagerUnsafe(()=>body.apply(this,arguments))}:function(){let effect=fromIteratorEagerUnsafe(()=>body.apply(this,arguments));for(let pipeable of pipeables)effect=pipeable(effect,...arguments);return effect})},fromIteratorEagerUnsafe=(evaluate)=>{try{let iterator=evaluate(),value=void 0;while(!0){let state=iterator.next(value);if(state.done)return succeed3(state.value);let primitive=state.value;if(primitive&&primitive._tag==="Success"){value=primitive.value;continue}else if(primitive&&primitive._tag==="Failure")return state.value;else{let isFirstExecution=!0;return suspend(()=>{if(isFirstExecution)return isFirstExecution=!1,flatMap(state.value,(value)=>fromIteratorUnsafe(iterator,value));else return suspend(()=>fromIteratorUnsafe(evaluate()))})}}}catch(error){return die(error)}},fromIteratorUnsafe=function(){let Proto=makePrimitiveProto({op:"Iterator",[contA](value,fiber){let iter=this.iterator;while(!0){let state=iter.next(value);if(state.done)return succeed3(state.value);if(!effectIsExit(state.value))return fiber._stack.push(this),state.value;else if(state.value._tag==="Failure")return state.value;value=state.value.value}},[evaluate](fiber){return this[contA](this.initial,fiber)}}),IteratorImpl=function(iterator,initial){this.iterator=iterator,this.initial=initial};return IteratorImpl.prototype=Proto,function(iterator,initial){return new IteratorImpl(iterator,initial)}}();var evaluateCont=function(fiber){return fiber._stack.push(this),this[args]},OnSuccessProto=makePrimitiveProto({op:"OnSuccess",[evaluate]:evaluateCont}),ContImpl=function(self,cont,payload){this[args]=self,this[contA]=cont,this.payload=payload};ContImpl.prototype=OnSuccessProto;var returnPayload=function(){return this.payload};var continuationMarksStack=(()=>{let limit=getStackTraceLimit();if(limit===0)return!1;let marker="~effect/Effect/stackProbe",probe={[marker]:function(){return Error()}};setStackTraceLimit(1);let error=probe[marker]();return setStackTraceLimit(limit),error.stack?.includes("[as "+marker+"]")===!0})(),mapCont=function(value,fiber){let f=this.payload;return fiber.succeedWith(continuationMarksStack?f(value):internalCall(()=>f(value)))},andThenCont=function(value){let f=this.payload;return f(value)};var asVoid=(self)=>new ContImpl(self,returnPayload,exitVoid);var flatMap=dual(2,(self,f)=>new ContImpl(self,andThenCont,f));var effectIsExit=(effect)=>effect[ExitTypeId]!==void 0,flatMapEager=dual(2,(self,f)=>{if(effectIsExit(self))return self._tag==="Success"?f(self.value):self;return flatMap(self,f)});var map2=dual(2,(self,f)=>new ContImpl(self,mapCont,f)),mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map2(self,f)),mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError(self,f));var exitIsSuccess=(self)=>self._tag==="Success";var exitVoid=exitSucceed(void 0),exitMap=dual(2,(self,f)=>self._tag==="Success"?exitSucceed(f(self.value)):self),exitMapError=dual(2,(self,f)=>{if(self._tag==="Success")return self;return exitFailCause(causeMap(self.cause,f))});var catchCause=dual(2,(self,f)=>new OnFailureImpl(self,f.length!==1?(cause)=>f(cause):f)),OnFailureProto=makePrimitiveProto({op:"OnFailure",[evaluate]:evaluateCont}),OnFailureImpl=function(self,f){this[args]=self,this[contE]=f};OnFailureImpl.prototype=OnFailureProto;var mapError=dual(2,(self,f)=>catchCause(self,(cause)=>failCause(causeMap(cause,f))));var OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",[evaluate]:evaluateCont}),OnSuccessAndFailureImpl=function(self,onSuccess,onFailure){this[args]=self,this[contA]=onSuccess,this[contE]=onFailure};OnSuccessAndFailureImpl.prototype=OnSuccessAndFailureProto;var exit=(self)=>effectIsExit(self)?exitSucceed(self):exitPrimitive(self),exitPrimitive=makePrimitive({op:"Exit",[evaluate](fiber){return fiber._stack.push(this),this[args]},[contA](value,fiber,exit){return fiber.succeedWith(exit??exitSucceed(value))},[contE](cause,fiber,exit){return fiber.succeedWith(exit??exitFailCause(cause))}});var combineFinalizerCause=(exit_,finalizer)=>exitIsSuccess(exit_)?finalizer:catchCause(finalizer,(cause)=>failCause(causeElectDefects(causeCombine(exit_.cause,cause))));var uninterruptible=(self)=>withFiber((fiber)=>{if(!fiber.interruptible)return self;return fiber.interruptible=!1,fiber._stack.push(setInterruptibleTrue),self}),setInterruptible=makePrimitive({op:"SetInterruptible",[contAll](fiber){if(fiber.interruptible=this[args],fiber._interruptedCause&&fiber.interruptible)return()=>failCause(fiber._interruptedCause)}}),setInterruptibleTrue=setInterruptible(!0);var whileLoop=makePrimitive({op:"While",[contA](value,fiber){if(this[args].step(value),this[args].while())return fiber._stack.push(this),this[args].body();return exitVoid},[evaluate](fiber){if(this[args].while())return fiber._stack.push(this),this[args].body();return exitVoid}});var resolveConcurrency=(concurrency)=>concurrency==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,concurrency??1),iterateEager=()=>(options)=>{let{onItem,step}=options,resumeSequential=(state,items,index,end,effect)=>flatMap(exit(effect),(itemExit)=>step(state,items[index],itemExit,index)??runSequential(state,items,index+1,end)??void_),runSequential=(state,items,index=0,end=items.length)=>{for(;index<end;index++){let item=items[index],effect=onItem(state,item,index);if(!effectIsExit(effect))return resumeSequential(state,items,index,end,effect);let terminal=step(state,item,effect,index);if(terminal)return terminal._tag==="Failure"?terminal:void 0}};return runSequential},iterateConcurrentImpl=(options)=>{let{onItem,step}=options;return(state,items,opts)=>{let index=0,end=opts.end??items.length,concurrency=opts.concurrency,done=!1,parentFiber,fibers,resume,terminal,effect,failDefect=(error)=>{let defect=exitDie(error);return terminal=defect,done=!0,fibers&&fibers.size>0?flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))),()=>terminal??defect):defect},go=()=>{let paused=!1;for(;!terminal&&index<end;index++){let item=items[index],eff=effect??onItem(state,item,index);if(effectIsExit(eff)){if(terminal=step(state,item,eff,index),terminal)break}else if(!parentFiber)return callback((cb)=>{parentFiber=getCurrentFiber(),fibers=new Set,effect=eff,resume=cb;let result;try{result=go()}catch(error){return cb(failDefect(error))}if(result)return cb(result);return suspend(()=>(terminal??=exitVoid,flatMap(fibers?fiberInterruptAll(fibers):void_,()=>terminal?._tag==="Failure"?terminal:void_)))});else{effect=void 0;let fiber=forkUnsafe(parentFiber,eff,!0,!0,"inherit");if(fiber._exit){if(terminal=step(state,item,fiber._exit,index),terminal)break;continue}fibers.add(fiber);let currentIndex=index;if(fiber.addObserver((exit)=>{fibers.delete(fiber);try{if(terminal){if(exit._tag==="Failure"){let reasons=exit.cause.reasons.filter((reason)=>reason._tag!=="Interrupt");if(reasons.length>0){let cause=causeFromReasons(reasons);terminal=exitFailCause(terminal._tag==="Failure"?causeElectDefects(causeCombine(terminal.cause,cause)):cause)}}}else{let result=step(state,item,exit,currentIndex);if(result)terminal=result,go()}if(paused){let eff=go();if(eff)resume(eff)}else if(done&&fibers.size===0)resume(terminal??void_)}catch(error){resume(failDefect(error))}}),fibers.size<concurrency)continue;paused=!0,index++;return}}if(done=!0,terminal){if(fibers&&fibers.size>0){let annotations=fiberStackAnnotations(parentFiber);fibers.forEach((f)=>f.interruptUnsafe(parentFiber.id,annotations));return}if(resume||terminal._tag==="Failure")return terminal}else if(resume){if(!fibers)return exitVoid;else if(fibers.size===0)resume(void_)}};return go()}},iterateConcurrent=()=>(options)=>iterateConcurrentImpl(options);var forkUnsafe=(parent,effect,immediate=!1,daemon=!1,uninterruptible=!1)=>{let parentRuntime=parent,interruptible=uninterruptible==="inherit"?parentRuntime.interruptible:!uninterruptible,child=new FiberImpl(parentRuntime.context,interruptible);if(!daemon)parentRuntime.children().add(child),child._parent=parentRuntime;if(immediate)child.evaluate(effect);else child._asyncContext=captureAsyncContext(),parentRuntime.currentDispatcher.scheduleTask(()=>child.evaluate(effect),0);return child};var runForkWith=(context)=>(effect,options)=>{let fiber=new FiberImpl(options?.scheduler?add(context,Scheduler,options.scheduler):context,options?.uninterruptible!==!0);if(fiber.evaluate(effect),fiber._exit)return fiber;if(options?.signal)if(options.signal.aborted)fiber.interruptUnsafe();else{let abort=()=>fiber.interruptUnsafe();options.signal.addEventListener("abort",abort,{once:!0}),fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}if(options?.onFiberStart)options.onFiberStart(fiber);return fiber};var runSyncExitWith=(context)=>{let runFork=runForkWith(context);return(effect)=>{if(effectIsExit(effect))return effect;let scheduler=new MixedScheduler("sync"),fiber=runFork(effect,{scheduler});return fiber._dispatcher?.flush(),fiber._exit??exitDie(new AsyncFiberError(fiber))}},runSyncExit=runSyncExitWith(empty());var AsyncFiberErrorTypeId="~effect/Cause/AsyncFiberError";class AsyncFiberError extends TaggedError("AsyncFiberError"){[AsyncFiberErrorTypeId]=AsyncFiberErrorTypeId;constructor(fiber){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber})}}var UnknownErrorTypeId="~effect/Cause/UnknownError";class UnknownError extends TaggedError("UnknownError"){[UnknownErrorTypeId]=UnknownErrorTypeId;constructor(cause,message){super({message,cause})}}var LoggerTypeId="~effect/Logger",LoggerProto={[LoggerTypeId]:{_Message:identity,_Output:identity},pipe(){return pipeArguments(this,arguments)}};var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warn:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var isFailReason2=isFailReason;var die2=causeDie;var map3=causeMap;var succeed4=exitSucceed,failCause2=exitFailCause,fail4=exitFail;var void_2=exitVoid;var isSuccess3=exitIsSuccess;var tryPromise2=tryPromise,succeed5=succeed3;var suspend2=suspend;var fail5=fail3;var failCauseSync2=failCauseSync,die3=die,try_2=try_;var fromResult2=fromResult;var flatMap2=flatMap;var exit2=exit;var catchCause2=catchCause;var runSyncExit2=runSyncExit;var mapEager2=mapEager,mapErrorEager2=mapErrorEager;var flatMapEager2=flatMapEager;var fnUntracedEager2=fnUntracedEager;var encode=(input)=>encodeBytes(typeof input==="string"?encoder.encode(input):input),decode=(str)=>{let stripped=stripCrlf(str),length=stripped.length;if(length%4!==0)return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:`Length must be a multiple of 4, but is ${length}`}));let index=stripped.indexOf("=");if(index!==-1&&(index<length-2||index===length-2&&stripped[length-1]!=="="))return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:"Found a '=' character, but it is not at the end"}));try{let missingOctets=stripped.endsWith("==")?2:stripped.endsWith("=")?1:0,result=new Uint8Array(3*(length/4)-missingOctets);for(let i=0,j=0;i<length;i+=4,j+=3){let buffer=getCode(stripped.charCodeAt(i))<<18|getCode(stripped.charCodeAt(i+1))<<12|getCode(stripped.charCodeAt(i+2))<<6|getCode(stripped.charCodeAt(i+3));result[j]=buffer>>16,result[j+1]=buffer>>8&255,result[j+2]=buffer&255}return succeed2(result)}catch(cause){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:cause instanceof Error?cause.message:"Invalid input"}))}};var encodeBytes=(bytes)=>{let length=bytes.length,toBase64=Uint8Array.prototype.toBase64;if(length>=32&&typeof toBase64==="function")return toBase64.call(bytes);return length<128?encodeShort(bytes):encodeLong(bytes)},encodeShort=(bytes)=>{let length=bytes.length,result="",i;for(i=2;i<length;i+=3)result+=alphabet[bytes[i-2]>>2],result+=alphabet[(bytes[i-2]&3)<<4|bytes[i-1]>>4],result+=alphabet[(bytes[i-1]&15)<<2|bytes[i]>>6],result+=alphabet[bytes[i]&63];if(i===length+1)result+=alphabet[bytes[i-2]>>2],result+=alphabet[(bytes[i-2]&3)<<4],result+="==";if(i===length)result+=alphabet[bytes[i-2]>>2],result+=alphabet[(bytes[i-2]&3)<<4|bytes[i-1]>>4],result+=alphabet[(bytes[i-1]&15)<<2],result+="=";return result},encodeLong=(bytes)=>{let length=bytes.length,result=new Uint8Array(Math.ceil(length/3)*4),i,j=0;for(i=2;i<length;i+=3,j+=4)result[j]=alphabetCodes[bytes[i-2]>>2],result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4|bytes[i-1]>>4],result[j+2]=alphabetCodes[(bytes[i-1]&15)<<2|bytes[i]>>6],result[j+3]=alphabetCodes[bytes[i]&63];if(i===length+1)result[j]=alphabetCodes[bytes[i-2]>>2],result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4],result[j+2]=paddingCode,result[j+3]=paddingCode;if(i===length)result[j]=alphabetCodes[bytes[i-2]>>2],result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4|bytes[i-1]>>4],result[j+2]=alphabetCodes[(bytes[i-1]&15)<<2],result[j+3]=paddingCode;return decoder.decode(result)},encoder=new TextEncoder,decoder=new TextDecoder,stripCrlf=(str)=>str.replace(/[\n\r]/g,""),alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",alphabetCodes=encoder.encode(alphabet),paddingCode=61,codes=new Uint8Array(123).fill(255);for(let i=0;i<alphabet.length;i++)codes[alphabet.charCodeAt(i)]=i;codes[61]=0;var getCode=(charCode)=>{if(charCode>=codes.length||codes[charCode]===255)throw TypeError(`Invalid character ${String.fromCharCode(charCode)}`);return codes[charCode]};function resolve(ast){return ast.checks?ast.checks[ast.checks.length-1].annotations:ast.annotations}var STRUCTURAL_ANNOTATION_KEY="~structural";var SENTINELS_ANNOTATION_KEY="~sentinels",CONSTRUCTOR_ANNOTATION_KEY="~constructor";var getExpected=memoize((ast)=>{let identifier=resolve(ast)?.identifier;if(typeof identifier==="string")return identifier;return ast.getExpected(getExpected)});var missing=Symbol();var succeed6=succeed4,missingExit=succeed6(missing),sameExit=succeed6(missing),toOption=(value)=>value===missing?none2():some2(value),fromOptionExit=(option)=>option._tag==="None"?missingExit:succeed6(option.value);var TypeId4="~effect/SchemaIssue/Issue";function isIssue(u){return hasProperty(u,TypeId4)&&u[TypeId4]===TypeId4}function hasInput(issue){return Object.hasOwn(issue,"input")}class IssueNodeImpl{[TypeId4]=TypeId4;constructor(input,options){if(options?.reportInput===!0&&input!==missing)this.input=input}}var Filter=class extends IssueNodeImpl{_tag="Filter";filter;issue;constructor(filter,issue,input,options){super(input,options);this.filter=filter,this.issue=issue}},Encoding=class extends IssueNodeImpl{_tag="Encoding";ast;issue;constructor(ast,issue,input,options){super(input,options);this.ast=ast,this.issue=issue}},Pointer=class extends IssueNodeImpl{_tag="Pointer";path;issue;constructor(path,issue){super();this.path=path,this.issue=issue}},MissingKey=class extends IssueNodeImpl{_tag="MissingKey";annotations;constructor(annotations){super();this.annotations=annotations}},UnexpectedKey=class extends IssueNodeImpl{_tag="UnexpectedKey";ast;constructor(ast,input,options){super(input,options);this.ast=ast}},Composite=class extends IssueNodeImpl{_tag="Composite";ast;issues;constructor(ast,issues,input,options){super(input,options);this.ast=ast,this.issues=issues}},InvalidType=class extends IssueNodeImpl{_tag="InvalidType";ast;constructor(ast,input,options){super(input,options);this.ast=ast}},InvalidValue=class extends IssueNodeImpl{_tag="InvalidValue";annotations;constructor(annotations,input,options){super(input,options);this.annotations=annotations}};var AnyOf=class extends IssueNodeImpl{_tag="AnyOf";ast;issues;constructor(ast,issues,input,options){super(input,options);this.ast=ast,this.issues=issues}},OneOf=class extends IssueNodeImpl{_tag="OneOf";ast;successes;constructor(ast,successes,input,options){super(input,options);this.ast=ast,this.successes=successes}};function makeFilterIssue(entry,input,options){if(isIssue(entry))return entry;if(typeof entry==="string")return new InvalidValue({message:entry},input,options);let inner=typeof entry.issue==="string"?new InvalidValue({message:entry.issue},input,options):entry.issue;return new Pointer(entry.path,inner)}function makeSingle(out,input,options){if(out===void 0)return;if(typeof out==="boolean")return out?void 0:new InvalidValue(void 0,input,options);return makeFilterIssue(out,input,options)}function normalizeFilterOutput(ast,out,input,options){if(Array.isArray(out)){if(!isReadonlyArrayNonEmpty(out))return;return out.length===1?makeFilterIssue(out[0],input,options):new Composite(ast,map(out,(entry)=>makeFilterIssue(entry,input,options)),input,options)}return makeSingle(out,input,options)}var defaultLeafHook=(issue)=>{let message=findMessage(issue);if(message!==void 0)return message;switch(issue._tag){case"InvalidType":return getExpectedMessage(getExpected(issue.ast),issue);case"InvalidValue":{let expected=findExpected(issue);if(expected!==void 0)return getExpectedMessage(expected,issue);let input=formatInput(issue);return input===void 0?"Expected a valid value":`Invalid data ${input}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{let input=formatInput(issue);return input===void 0?"Expected no excess property":`Unexpected key with value ${input}`}case"Forbidden":return"Forbidden operation";case"OneOf":{let input=formatInput(issue);return input===void 0?"Expected exactly one member to match":`Expected exactly one member to match the input ${input}`}}},defaultCheckHook=(issue)=>findMessage(issue)??findMessage(issue.issue);function formatInput(issue){return hasInput(issue)?format(issue.input):void 0}function findExpected(issue){let expected=issue.annotations?.expected;return typeof expected==="string"?expected:void 0}function getExpectedMessage(expected,issue){let input=formatInput(issue);return input===void 0?`Expected ${expected}`:`Expected ${expected}, got ${input}`}function getFilterMessage(issue,checkHook){let message=checkHook(issue);if(message!==void 0||issue.issue._tag!=="InvalidValue")return message;let expected=findExpected(issue.issue);return expected===void 0?getExpectedMessage(formatCheck(issue.filter),issue):getExpectedMessage(expected,issue.issue)}function formatCheck(check){let expected=check.annotations?.expected;if(typeof expected==="string")return expected;switch(check._tag){case"Filter":return"<filter>";case"FilterGroup":return check.checks.map((check)=>formatCheck(check)).join(" & ")}}function makeFormatterDefault(){return(issue)=>formatIssue(issue,"")}var defaultFormatter=makeFormatterDefault();function formatIssue(issue,path,messageOverride){let message;switch(issue._tag){case"Filter":return formatIssue(issue.issue,path,messageOverride??getFilterMessage(issue,defaultCheckHook));case"Encoding":return formatIssue(issue.issue,path,messageOverride);case"Pointer":return formatIssue(issue.issue,path+formatPath(issue.path),messageOverride);case"Composite":case"AnyOf":{if(issue._tag==="Composite"||issue.issues.length>0)return issue.issues.map((issue)=>formatIssue(issue,path,messageOverride)).join(`
|
|
18
18
|
`);message=messageOverride??findMessage(issue)??getExpectedMessage(getExpected(issue.ast),issue);break}default:message=messageOverride??defaultLeafHook(issue);break}return path?`${message}
|
|
19
|
-
at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer"||issue._tag==="Composite")return;if(issue._tag==="Encoding")return findMessage(issue.issue);let message=(issue._tag==="Filter"?issue.filter.annotations:("annotations"in issue)?issue.annotations:issue.ast.annotations)?.[issue._tag==="MissingKey"?"messageMissingKey":issue._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof message==="string")return message}function getSchemaIssue(cause){let issue;for(let reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error))return;issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){let issue=getSchemaIssue(cause);if(issue===void 0)throw Error(message,{cause});return issue}var makeGetter=(fields)=>Object.assign(Object.create(Prototype),fields);var passthrough_=makeGetter({_tag:"Passthrough"});function passthrough(){return passthrough_}function transform(f){return makeGetter({_tag:"Transform",transform:f})}function transformEffect(f){return makeGetter({_tag:"TransformEffect",transform:f})}function transformOptional(f){return makeGetter({_tag:"TransformOptional",transform:f})}function transformOptionalEffect(f){return makeGetter({_tag:"TransformOptionalEffect",transform:f})}function omit(){return transformOptional(()=>none2())}function withDefault(defaultValue){return transformOptionalEffect((o)=>{let filtered=filter(o,isNotUndefined);return isSome2(filtered)?succeed5(filtered):mapEager2(defaultValue,some2)})}function String2(){return transform(globalThis.String)}function Number3(){return transform(globalThis.Number)}function parseJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>{let output=JSON.stringify(input,options?.replacer,options?.space);if(output===void 0)throw TypeError("Value cannot be represented as JSON");return output},catch:()=>new InvalidValue({expected:"a JSON-serializable value"},input,parseOptions)}))}function encodeBase64(){return transform(encode)}function decodeBase64(){return transformEffect((input,options)=>mapErrorEager2(fromResult2(decode(input)),()=>new InvalidValue({expected:"a valid Base64 string"},input,options)))}var ContentTypeId=Symbol.for("~effect/Schema/content");function setContent(operation,content){return Object.defineProperty(operation,ContentTypeId,{value:content}),operation}var TypeId5="~effect/SchemaTransformation/Transformation",Transformation=class extends Class{[TypeId5]=TypeId5;_tag="Transformation";decode;encode;constructor(decode,encode){super();this.decode=decode,this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}};function isTransformation(u){return hasProperty(u,TypeId5)&&u[TypeId5]===TypeId5}var makeTransformation=(options)=>{if(isTransformation(options))return options;return new Transformation(options.decode,options.encode)};function transformEffect2(options){return new Transformation(transformEffect(options.decode),transformEffect(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough(),passthrough());function passthrough2(){return passthrough_2}var numberFromString=new Transformation(Number3(),String2());var urlFromString=transformEffect2({decode:(s,options)=>URL.canParse(s)?succeed5(new URL(s)):fail5(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed5(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase64(),encodeBase64());function fromJsonString(options){return new Transformation(parseJson(options??{}),setContent(stringifyJson(options),{mediaType:"application/json",preserveSchema:options?.reviver===void 0&&options?.replacer===void 0}))}function makeGuard(tag){return(ast)=>ast._tag===tag}var isDeclaration=makeGuard("Declaration");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal"),isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays"),isObjects=makeGuard("Objects");var isSuspend=makeGuard("Suspend"),Link=class{to;transformation;constructor(to,transformation){this.to=to,this.transformation=transformation}},defaultParseOptions={},Context=class{isOptional;isMutable;constructorDefault;annotations;constructor(isOptional,isMutable,constructorDefault=void 0,annotations=void 0){this.isOptional=isOptional,this.isMutable=isMutable,this.constructorDefault=constructorDefault,this.annotations=annotations}},TypeId6="~effect/Schema";class ASTNodeImpl{[TypeId6]=TypeId6;annotations;checks;encoding;context;constructor(annotations=void 0,checks=void 0,encoding=void 0,context=void 0){this.annotations=annotations,this.checks=checks,this.encoding=encoding,this.context=context}toString(){return`<${this._tag}>`}}var Declaration=class extends ASTNodeImpl{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(typeParameters,run,annotations,checks,encoding,context,encodingChecks,encodingRun){super(annotations,checks,encoding,context);this.typeParameters=typeParameters,this.run=run,this.encodingChecks=encodingChecks,this.encodingRun=encodingRun}getParser(){let run;return(input,options)=>{if(input===missing)return missingExit;run??=this.run(this.typeParameters);try{return run(input,this,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks,run,encodingRun){let tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks&&run===this.run&&encodingRun===this.encodingRun?this:new Declaration(tps,run,this.annotations,checks,void 0,this.context,encodingChecks,encodingRun)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}},Null=class extends ASTNodeImpl{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}},null_=new Null;var Undefined=class extends ASTNodeImpl{_tag="Undefined";getParser(){return fromConst(this,void 0)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}},undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null))),undefined_2=new Undefined;var Unknown=class extends ASTNodeImpl{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}},unknown=new Unknown;var Literal=class extends ASTNodeImpl{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context){super(annotations,checks,encoding,context);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal))throw Error(`A numeric literal must be finite, got ${format(literal)}`);this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function literalToString(ast){let literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}var String3=class extends ASTNodeImpl{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){let checks=this.checks;return checks&&!options.disableChecks&&collectIssues(checks,s,void 0,this,options)?void 0:s}getExpected(){return"string"}},string2=new String3,Number4=class extends ASTNodeImpl{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){if(!regexp.test(s))return;let value=globalThis.Number(s);if(options.disableChecks||!this.checks)return value;return collectIssues(this.checks,value,void 0,this,options)?void 0:value}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"effect/schema/isFinite")||hasCheck(this.checks,"effect/schema/isInt")))return this;return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.toCodecJson()===this)return replaceEncoding(this,[finiteToString]);return replaceEncoding(this,[numberToString])}getExpected(){return"number"}};function hasCheck(checks,id){return checks.some((check)=>check.annotations?.representation?.id===id||check._tag==="FilterGroup"&&hasCheck(check.checks,id))}var number2=new Number4,Boolean2=class extends ASTNodeImpl{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}},boolean=new Boolean2;var Arrays=class extends ASTNodeImpl{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.isMutable=isMutable,this.elements=elements,this.rest=rest,this.encodingChecks=encodingChecks;let hasOptional=!1;for(let i=0;i<elements.length;i++)if(isOptional(elements[i]))hasOptional=!0;else if(hasOptional)throw Error("A required element cannot follow an optional element. ts(1257)");if(hasOptional&&rest.length>1)throw Error("A required element cannot follow an optional element. ts(1257)");for(let i=1;i<rest.length;i++)if(isOptional(rest[i]))throw Error("An optional element cannot follow a rest element. ts(1266)")}getParser(compile,compileField=compile){let ast=this,elements,rest,elementLen=ast.elements.length,tailLen=Math.max(0,ast.rest.length-1);function getParser(tailThreshold,index){if(index<elementLen)return elements[index];else if(index>=tailThreshold)return rest[index-tailThreshold+1];return rest[0]}let finish=(state)=>{let{input,len,options}=state;if(ast.rest.length===0&&len>elementLen)for(let i=elementLen;i<len;i++){let unexpected=new UnexpectedKey(ast,input[i],options),issue=new Pointer([i],unexpected);if(options.errors==="all")if(state.issues)state.issues.push(issue);else state.issues=[issue];else return fail5(new Composite(ast,[issue],input,options))}if(state.issues)return fail5(new Composite(ast,state.issues,input,options));return succeed6(state.output)},parse=(input,options)=>{let len=input.length,state={ast,getParser,input,len,tailThreshold:Math.max(elementLen,len-tailLen),output:[],issues:void 0,options},end=ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen),concurrency=options.concurrency===void 0?1:resolveConcurrency(options.concurrency),eff=concurrency===1?parseArray(state,input,0,end):parseArrayConcurrent(state,input,{concurrency,end});if(!eff)return finish(state);if(effectIsExit(eff))return flatMapEager2(eff,()=>finish(state));let first=!0;return suspend2(()=>{if(!first)return parse(input,options);return first=!1,flatMap2(eff,()=>finish(state))})};return(input,options)=>{if(input===missing)return missingExit;try{if(!Array.isArray(input))return fail5(new InvalidType(ast,input,options));if(!elements)elements=ast.elements.map((ast)=>({ast,parser:compileField(ast)})),rest=ast.rest.map((ast)=>({ast,parser:compileField(ast)}));return parse(input,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks){let elements=mapOrSame(this.elements,recur),rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,void 0,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}};function stepArray(s,item,exit,i){if(exit._tag==="Failure")return wrapPropertyKeyIssue(s,s.ast,i,exit);let value=exit===sameExit?item:exit[args];if(value!==missing)s.output[i]=value;else{let p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;let issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all")if(s.issues)s.issues.push(issue);else s.issues=[issue];else return fail4(new Composite(s.ast,[issue],s.input,s.options))}}var parseArrayOptions={onItem(s,item,i){let value=i<s.len?item:missing;return s.getParser(s.tailThreshold,i).parser(value,s.options)},step:stepArray},parseArray=iterateEager()(parseArrayOptions),parseArrayConcurrent=iterateConcurrent()(parseArrayOptions),wrapPropertyKeyIssue=(s,ast,key,exit)=>{if(exit.cause.reasons.length===0)return exit;let issue=getSchemaIssue(exit.cause);if(issue===void 0)return failCause2(map3(exit.cause,(issue)=>new Composite(ast,[new Pointer([key],issue)],s.input,s.options)));let pointer=new Pointer([key],issue);if(s.options.errors==="all")if(s.issues)s.issues.push(pointer);else s.issues=[pointer];else return fail4(new Composite(ast,[pointer],s.input,s.options))},FINITE_PATTERN="[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys,symbolKeys;function go(parameter){switch(parameter._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchPart(k,options)!==void 0);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchKey(k,options)!==void 0);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>Object.prototype.propertyIsEnumerable.call(input,k)&¶meter.matchKey(k,options)!==void 0);case"Union":return[...new Set(parameter.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}var PropertySignature=class{name;type;constructor(name,type){this.name=name,this.type=type}};function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return!1}}function isIndexSignatureParameterEncodedSide(ast){let encoded=getLastEncoding(ast);switch(encoded._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return encoded.types.every(isIndexSignatureParameterEncodedSide);default:return!1}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterEncodedSide(ast)}var IndexSignature=class{parameter;type;constructor(parameter,type){if(!isIndexSignatureParameter(parameter))throw Error(`Invalid index signature parameter ${parameter._tag}`);if(this.parameter=parameter,this.type=type,isOptional(type)||type.encoding!==void 0&&isOptional(toEncoded(type)))throw Error("Cannot use `Schema.optionalKey` or `Schema.optional` with index signatures. Index signatures already allow keys to be absent; use `Schema.UndefinedOr` to allow `undefined` values.")}},Objects=class extends ASTNodeImpl{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.propertySignatures=propertySignatures,this.indexSignatures=indexSignatures,this.encodingChecks=encodingChecks}getParser(compile,compileField=compile){let ast=this,hasProperties=ast.propertySignatures.length,indexCount=ast.indexSignatures.length;if(!hasProperties&&!indexCount)return fromRefinement(ast,isNotNullish);let properties,indexes,compileMembers=()=>{if(!properties)properties=ast.propertySignatures.map((ps)=>({parser:compileField(ps.type),name:ps.name,type:ps.type})),indexes=indexCount?ast.indexSignatures.map((is)=>({is,parserKey:compile(parameterFromPropertyKey(is.parameter)),parserValue:compileField(is.type)})):void 0;return properties},makeFallback=()=>{let expectedKeys=new Set(ast.propertySignatures.map((ps)=>typeof ps.name==="number"?globalThis.String(ps.name):ps.name)),finishIndex=(s,key,k2,inputValue,exitValue)=>{if(exitValue._tag==="Failure")return wrapPropertyKeyIssue(s,ast,key,exitValue)??void_2;let value=exitValue===sameExit?inputValue:exitValue[args];if(k2!==missing&&value!==missing){if(hasProperties&&(expectedKeys.has(key)||expectedKeys.has(typeof k2==="number"?globalThis.String(k2):k2)))return void_2;assignProperty(s.out,k2,value)}return void_2},parseIndex=(s,key,index,exitKey)=>{if(!exitKey){let eff=index.parserKey(key,s.options);if(!effectIsExit(eff))return flatMap2(exit2(eff),(exit)=>parseIndex(s,key,index,exit));exitKey=eff}if(exitKey._tag==="Failure")return wrapPropertyKeyIssue(s,ast,key,exitKey)??void_2;let k2=exitKey===sameExit?key:exitKey[args],inputValue=s.input[key],result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,k2,inputValue,result):flatMap2(exit2(result),(exit)=>finishIndex(s,key,k2,inputValue,exit))},parseStringIndex=(s,key,index)=>{let inputValue=s.input[key],result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,key,inputValue,result):flatMap2(exit2(result),(exit)=>finishIndex(s,key,key,inputValue,exit))},parseIndexes=indexCount?iterateConcurrent()({onItem:(s,[key,index])=>index.is.parameter===string2?parseStringIndex(s,key,index):parseIndex(s,key,index),step:(_s,_item,exit)=>exit._tag==="Failure"?exit:void 0}):void 0;return fnUntracedEager2(function*(input,options){if(input===missing)return missing;if(!(typeof input==="object"&&input!==null&&!Array.isArray(input)))return yield*fail5(new InvalidType(ast,input,options));compileMembers();let record=input,out={},state={ast,input:record,out,issues:void 0,options},errorsAllOption=options.errors==="all",onExcessPropertyError=options.onExcessProperty==="error",concurrency=options.concurrency===void 0?1:resolveConcurrency(options.concurrency),indexKeys=indexCount&&onExcessPropertyError?ast.indexSignatures.map((index)=>getIndexSignatureKeys(record,index.parameter,options)):void 0;if(onExcessPropertyError){let coveredKeys=indexKeys?new Set(expectedKeys):expectedKeys;if(indexKeys)for(let keys of indexKeys)for(let key of keys)coveredKeys.add(key);let inputKeys=Reflect.ownKeys(record);for(let i=0;i<inputKeys.length;i++){let key=inputKeys[i];if(!coveredKeys.has(key)&&Object.prototype.propertyIsEnumerable.call(record,key)){let unexpected=new UnexpectedKey(ast,record[key],options),issue=new Pointer([key],unexpected);if(errorsAllOption){if(state.issues)state.issues.push(issue);else state.issues=[issue];continue}else return yield*fail5(new Composite(ast,[issue],input,options))}}}if(hasProperties){let eff=concurrency===1?parseProperties(state,properties):parsePropertiesConcurrent(state,properties,{concurrency});if(eff)yield*eff}if(indexCount&&concurrency===1)for(let i=0;i<indexCount;i++){let index=indexes[i],parse=index.is.parameter===string2?parseStringIndex:parseIndex,keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){let eff=parse(state,keys[j],index);if(!effectIsExit(eff))yield*eff;else if(eff._tag==="Failure")return yield*eff}}else if(parseIndexes){let keyPairs=empty2();for(let i=0;i<indexCount;i++){let index=indexes[i],keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++)keyPairs.push([keys[j],index])}let eff=parseIndexes(state,keyPairs,{concurrency});if(eff)yield*eff}if(state.issues)return yield*fail5(new Composite(ast,state.issues,input,options));return out})};if(indexCount)return makeFallback();let fallback,resume=(snapshot,index,pending)=>{let property=properties[index];return flatMap2(exit2(pending),(exit)=>{let state={...snapshot,out:{...snapshot.out}},terminal=stepProperty(state,property,exit);if(terminal)return terminal;let done=()=>succeed6(state.out),eff=parseProperties(state,properties.slice(index+1));return eff?flatMapEager2(eff,done):done()})};return(input,options)=>{if(input===missing)return missingExit;if(options.errors==="all"||options.onExcessProperty!==void 0||options.concurrency!==void 0&&resolveConcurrency(options.concurrency)!==1)return(fallback??=makeFallback())(input,options);if(!(typeof input==="object"&&input!==null&&!Array.isArray(input)))return fail5(new InvalidType(ast,input,options));let props=compileMembers(),record=input,out={},state={ast,input:record,out,issues:void 0,options};try{for(let index=0;index<props.length;index++){let property=props[index],name=property.name,hasKey=hasPropertySignature(record,name),value=hasKey?record[name]:missing,exit=property.parser(value,options);if(!effectIsExit(exit))return resume(state,index,exit);if(exit===sameExit){if(hasKey)assignProperty(out,name,value);continue}let terminal=stepProperty(state,property,exit);if(terminal)return terminal}}catch(error){return die3(error)}return succeed6(out)}}_rebuild(recur,recurParameter,checks,encodingChecks){let props=mapOrSame(this.propertySignatures,(ps)=>{let t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)}),indexes=mapOrSame(this.indexSignatures,(is)=>{let p=recurParameter(is.parameter),t=recur(is.type);return p===is.parameter&&t===is.type?is:new IndexSignature(p,t)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,void 0,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function stepProperty(s,p,exit){if(exit._tag==="Failure")return wrapPropertyKeyIssue(s,s.ast,p.name,exit);if(exit===sameExit)return;let value=exit[args];if(value!==missing){assignProperty(s.out,p.name,value);return}if(delete s.out[p.name],!isOptional(p.type)){let issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else return fail4(new Composite(s.ast,[issue],s.input,s.options))}}var parsePropertiesOptions={onItem(s,p){if(!hasPropertySignature(s.input,p.name))return p.parser(missing,s.options);let value=s.input[p.name];return assignProperty(s.out,p.name,value),p.parser(value,s.options)},step:stepProperty},parseProperties=iterateEager()(parsePropertiesOptions),parsePropertiesConcurrent=iterateConcurrent()(parsePropertiesOptions);function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>new PropertySignature(key,fields[key].ast)),[],annotations,checks)}function getAST(self){return self.ast}function tuple(elements,checks=void 0){return new Arrays(!1,elements.map((e)=>e.ast),[],void 0,checks)}function union(members,options,checks){return new Union(members.map(getAST),options,void 0,checks)}var toCandidate=memoizeIdempotent((ast)=>{while(!0){if(isSuspend(ast))return unknown;let encoding=ast.encoding;if(!encoding)return ast.recur?.(toCandidate,identity)??ast;if(encoding.some((link)=>link.transformation._tag==="Middleware"&&link.transformation.decode!==identity))return unknown;ast=encoding[encoding.length-1].to}});function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{let s=ast.annotations?.[SENTINELS_ANNOTATION_KEY];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{let type=ps.type;if(!isOptional(type)){if(isLiteral(type))return[{key:ps.name,literal:type.literal}];if(isUniqueSymbol(type))return[{key:ps.name,literal:type.symbol}]}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{if(!isOptional(e)){if(isLiteral(e))return[{key:i,literal:e.literal}];if(isUniqueSymbol(e))return[{key:i,literal:e.symbol}]}return[]});case"Union":{if(ast.types.length===0)return[];let members=ast.types.map((type)=>collectSentinels(toCandidate(type)));return members[0].filter((s)=>members.every((sentinels)=>sentinels.some((o)=>o.key===s.key&&o.literal===s.literal)))}case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap,emptyCandidates=Object.freeze([]),getRuntimeType=(input)=>input===null?"null":Array.isArray(input)?"array":typeof input,hasPropertySignature=(input,key)=>key==="__proto__"?Object.hasOwn(input,key):(key in input);function getCandidateIndex(types){let index=candidateIndexCache.get(types);if(index)return index;let bySentinel,sentinelCandidateCount=0,otherwise,literalCandidates,onlyLiterals=!0,literalOf=[];for(let i=0;i<types.length;i++){let a=types[i],encoded=toCandidate(a);if(isNever2(encoded))continue;if(isLiteral(encoded)||isUniqueSymbol(encoded)){literalCandidates??=new Map;let literal=isLiteral(encoded)?encoded.literal:encoded.symbol;literalOf[i]=literal;let arr=literalCandidates.get(literal);if(!arr)literalCandidates.set(literal,arr=[]);arr.push(i)}else onlyLiterals=!1;let sentinels=collectSentinels(encoded);if(sentinels.length){bySentinel??=new Map,sentinelCandidateCount++;for(let{key,literal}of sentinels){let entry=bySentinel.get(key);if(!entry)bySentinel.set(key,entry=[new Map,new Set]);entry[1].add(i);let indexes=entry[0].get(literal);if(!indexes)entry[0].set(literal,indexes=new Set);indexes.add(i)}}else{otherwise??={};let candidateTypes=getCandidateTypes(encoded);for(let t of candidateTypes)(otherwise[t]??=[]).push(i)}}let fallbacks={},getFallback=(type)=>fallbacks[type]??=Object.freeze(otherwise?.[type]??emptyCandidates);if(onlyLiterals&&literalCandidates)literalCandidates.forEach(Object.freeze),index=(input)=>literalCandidates.get(input)??emptyCandidates;else if(bySentinel?.size===1&&!otherwise){let[key,[byValue]]=bySentinel.entries().next().value,candidates=new Map;for(let[literal,indexes]of byValue)candidates.set(literal,Object.freeze(Array.from(indexes)));let all=Object.freeze(types.map((_,i)=>i));index=(input,isConstructor)=>{if(isObjectKeyword(input)){let value=hasPropertySignature(input,key)?input[key]:void 0;if(value!==void 0)return candidates.get(value)??emptyCandidates;if(isConstructor)return all}return emptyCandidates}}else if(bySentinel){let commonSentinel;for(let entry of bySentinel)if((!commonSentinel||entry[1][0].size>commonSentinel[1][0].size)&&entry[1][1].size===sentinelCandidateCount)commonSentinel=entry;index=(input,isConstructor)=>{let runtimeType=getRuntimeType(input);if(!isObjectKeyword(input))return getFallback(runtimeType);let selected=new Set(otherwise?.[runtimeType]),directKey;if(commonSentinel){let[key,[byValue]]=commonSentinel,hasKey=hasPropertySignature(input,key),value=hasKey?input[key]:void 0;if(hasKey&&(!isConstructor||value!==void 0)){let match=byValue.get(value);if(!match)return getFallback(runtimeType);for(let i of match)selected.add(i);directKey=key}}if(directKey===void 0)for(let[key,[byValue,all]]of bySentinel){let hasKey=hasPropertySignature(input,key),value=hasKey?input[key]:void 0;if(hasKey&&(!isConstructor||value!==void 0)){let match=byValue.get(value);if(match)for(let i of match)selected.add(i)}else if(isConstructor)for(let i of all)selected.add(i)}for(let[key,[byValue,all]]of bySentinel){if(key===directKey)continue;let hasKey=hasPropertySignature(input,key),value=hasKey?input[key]:void 0;if(hasKey&&(!isConstructor||value!==void 0)){let match=byValue.get(value);for(let i of selected)if(all.has(i)&&!match?.has(i))selected.delete(i)}}return Array.from(selected).sort((a,b)=>a-b)}}else index=(input)=>{let fallback=getFallback(getRuntimeType(input));return literalCandidates?fallback.filter((i)=>literalOf[i]===void 0||literalOf[i]===input):fallback};return candidateIndexCache.set(types,index),index}var Union=class extends ASTNodeImpl{_tag="Union";types;options;encodingChecks;constructor(types,options,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.types=types,this.options=options,this.encodingChecks=encodingChecks}getParser(compile,compileField){let ast=this,isConstructor=compileField!==void 0,parsers=[],parser=(i)=>parsers[i]??=compile(ast.types[i]),index;return(input,options)=>{if(input===missing)return missingExit;let candidates=(index??=getCandidateIndex(ast.types))(input,isConstructor);if(candidates.length===0)return fail5(new AnyOf(ast,[],input,options));if(candidates.length===1){let result=parser(candidates[0])(input,options);if(result._tag==="Success")return result;return effectIsExit(result)?failSingleUnionCandidate(ast,result.cause,input,options):catchSingleUnionCandidate(ast,result,input,options)}return parseUnionCandidates(ast,parser,candidates,input,options)}}_rebuild(recur,checks,encodingChecks){let types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.options,this.annotations,checks,void 0,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(let type of this.types){let out=type.matchPart(s,options);if(out!==void 0)return out}return}getExpected(getExpected){let expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";let types=this.types.map((type)=>{let encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{let literals=encoded.elements.filter(isLiteral);if(literals.length>0)return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`;break}case"Objects":{let literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0)return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`;break}}return getExpected(encoded)});return Array.from(new Set(types)).join(" | ")}};function failSingleUnionCandidate(ast,cause,input,options){let issue=getSchemaIssue(cause);if(!issue)return failCause2(cause);return fail4(new AnyOf(ast,[issue],input,options))}function catchSingleUnionCandidate(ast,result,input,options){return catchCause2(result,(cause)=>failSingleUnionCandidate(ast,cause,input,options))}function parseUnionCandidates(ast,parser,candidates,input,options){let state={ast,parser,input,out:void 0,successes:ast.options?.mode==="oneOf"?[]:void 0,issues:void 0,options},eff=parseUnion(state,candidates);if(!eff){if(state.out)return state.out;return fail5(new AnyOf(ast,state.issues??[],input,options))}if(effectIsExit(eff))return resumeUnion(eff,state);let first=!0;return suspend2(()=>{if(!first)return parseUnionCandidates(ast,parser,candidates,input,options);return first=!1,resumeUnion(eff,state)})}function resumeUnion(eff,state){return flatMapEager2(eff,(_)=>{if(state.out===sameExit)return succeed5(state.input);if(state.out)return state.out;return fail5(new AnyOf(state.ast,state.issues??[],state.input,state.options))})}var parseUnion=iterateEager()({onItem(s,i){return s.parser(i)(s.input,s.options)},step(s,i,exit){if(exit._tag==="Failure"){let issue=getSchemaIssue(exit.cause);if(issue===void 0)return exit;if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.successes)return s.successes.push(s.ast.types[i]),fail4(new OneOf(s.ast,s.successes,s.input,s.options));if(s.out=exit,s.successes)s.successes.push(s.ast.types[i]);else return void_2}}}),nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")]);function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}var Filter2=class extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=void 0,aborted=!1){super();this.run=run,this.annotations=annotations,this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,!0)}and(other,annotations){return new FilterGroup([this,other],annotations)}},FilterGroup=class extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=void 0){super();this.checks=checks,this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}};function makeFilter(filter,annotations,aborted=!1){return new Filter2((input,ast,options)=>normalizeFilterOutput(ast,filter(input,ast,options),input,options),annotations,aborted)}function isFinite(annotations){return makeFilter((n)=>globalThis.Number.isFinite(n),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...annotations})}var finite=appendChecks(number2,[isFinite()]),numberToJson=new Link(new Union([finite,nonFiniteLiterals]),new Transformation(Number3(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function isPattern(regExp,annotations){let copy=new globalThis.RegExp(regExp),payload={source:copy.source,flags:copy.flags};return makeFilter((s)=>(copy.lastIndex=0,copy.test(s)),{expected:`a string matching the RegExp ${payload.source}`,representation:{id:"effect/schema/isPattern",payload},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[payload]},...annotations})}var bodyOwners=new WeakMap;function copy(ast,changes){let out=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,changes);if(Reflect.ownKeys(changes).every((key)=>key==="context"||key==="encoding"))bodyOwners.set(out,getContextOwner(ast));return out}function getContextOwner(ast){let existing=bodyOwners.get(ast);if(existing!==void 0)return existing;if(ast.encoding===void 0)return ast;let owner=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,{encoding:void 0});return bodyOwners.set(ast,owner),owner}function replaceEncoding(ast,encoding){return ast.encoding===encoding?ast:copy(ast,{encoding})}function replaceContext(ast,context){if(ast.context===context)return ast;let owner=getContextOwner(ast);if(owner.context===context&&owner.encoding===ast.encoding)return owner;return copy(ast,{context})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){let last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return copy(ast,{annotations:{...ast.annotations,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks)throw Error("Cannot add checks to Suspend");if(ast.checks===checks)return ast;return copy(ast,{checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function mapLink(link,f){let to=f(link.to);return to===link.to?link:new Link(to,link.transformation)}function updateLastLink(encoding,f){let links=encoding,last=links[links.length-1],out=mapLink(last,f);return out===last?encoding:append(encoding.slice(0,encoding.length-1),out)}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function applyToSelfOrLastLinkEncodingIdempotent(f,options){function out(ast){if(ast.encoding){let last=ast.encoding[ast.encoding.length-1];return options?.stopAt?.(last)?ast:replaceEncoding(ast,updateLastLink(ast.encoding,out))}return f(ast)}return memoizeIdempotent(out)}function appendTransformation(from,transformation,to){let link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function mapOrSame(as,f){let out;for(let i=0;i<as.length;i++){let a=as[i],fa=f(a);if(out)out[i]=fa;else if(fa!==a){out=Array(as.length);for(let j=0;j<i;j++)out[j]=as[j];out[i]=fa}}return out??as}function annotateKey(ast,annotations){let context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.constructorDefault,{...ast.context.annotations,...annotations}):new Context(!1,!1,void 0,annotations);return replaceContext(ast,context)}var optionalKey=memoizeIdempotent((ast)=>{let context=ast.context?ast.context.isOptional===!1?new Context(!0,ast.context.isMutable,ast.context.constructorDefault,ast.context.annotations):ast.context:new Context(!0,!1);return optionalKeyLastLink(replaceContext(ast,context))}),optionalKeyLastLink=applyToLastLink(optionalKey),optional=memoize((ast)=>optionalKey(new Union([ast,undefined_2])));function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function isOptional(ast){return ast.context?.isOptional??!1}function isStructuralCheck(check){return check.annotations?.[STRUCTURAL_ANNOTATION_KEY]===!0||check._tag==="FilterGroup"&&check.checks.every(isStructuralCheck)}function extractStructuralChecks(checks){function extract(check){if(isStructuralCheck(check))return[check];return check._tag==="FilterGroup"?check.checks.flatMap(extract):[]}let out=checks.flatMap(extract);return isArrayNonEmpty2(out)?out:void 0}function canPreserveEncodingChecks(ast){let preserve=!0;function visit(child){if(preserve=preserve&&!child.encoding&&!isSuspend(child),preserve&&"recur"in child)child.recur(visit);return child}if("recur"in ast)ast.recur(visit);return preserve}var toType=memoizeIdempotent((ast)=>{let owner=getContextOwner(ast);if(owner!==ast){let type=toType(owner);return type===owner&&ast.encoding===void 0?ast:replaceContext(type,ast.context)}let type="recur"in ast?ast.recur(toType):ast;if("encodingChecks"in type&&type.encodingChecks){let checks=canPreserveEncodingChecks(ast)?type.encodingChecks:isArrays(type)||isObjects(type)||isDeclaration(type)&&type.typeParameters.length>0?extractStructuralChecks(type.encodingChecks):void 0;return copy(type,{encodingChecks:void 0,checks:combineChecks(type.checks,checks)})}return type}),toEncoded=memoizeIdempotent((ast)=>toType(flip2(ast)));function flipEncoding(ast,encoding){let links=encoding,len=links.length,last=links[len-1],ls=[new Link(flip2(replaceEncoding(ast,void 0)),links[0].transformation.flip())];for(let i=1;i<len;i++)ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()));let to=flip2(last.to);if(to.encoding)return replaceEncoding(to,[...to.encoding,...ls]);else return replaceEncoding(to,ls)}var flip2=memoize((ast)=>{if(ast.encoding)return flipEncoding(ast,ast.encoding);let owner=getContextOwner(ast);if(owner!==ast){let flipped=flip2(owner);return flipped===owner?ast:replaceContext(flipped,ast.context)}return"flip"in ast?ast.flip(flip2):("recur"in ast)?ast.recur(flip2):ast});function fromConst(ast,value){let succeed=value===0?sameExit:succeed6(value);return(input,options)=>{if(input===missing)return missingExit;if(input===value)return succeed;return fail5(new InvalidType(ast,input,options))}}function fromRefinement(ast,refinement){return(input,options)=>{if(input===missing)return missingExit;if(refinement(input))return sameExit;return fail5(new InvalidType(ast,input,options))}}var parameterFromPropertyKey=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`),isStringNumberRegExp=new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:isStringFiniteRegExp.source}),...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]),finiteToString=new Link(finiteString,numberFromString),numberToString=new Link(new Union([finiteString,nonFiniteLiterals]),numberFromString),BIGINT_PATTERN="-?\\d+",isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\(([\\s\\S]*)\\)",isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value,issues,ast,options){for(let i=0;i<checks.length;i++){let check=checks[i];if(check._tag==="FilterGroup"){if(issues=collectIssues(check.checks,value,issues,ast,options),issues&&(options.errors!=="all"||issues[issues.length-1].filter.aborted))return issues}else{let issue=check.run(value,ast,options);if(issue){let filter=new Filter(check,issue,value,options);if(issues)issues.push(filter);else issues=[filter];if(options.errors!=="all"||check.aborted)return issues}}}return issues}function getConstructorDescriptor(ast){if(!isDeclaration(ast))return;let getDescriptor=ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];return isFunction(getDescriptor)?getDescriptor(ast.typeParameters):void 0}var flatMapTransformation=(result,current,f)=>result===sameExit?f(current):flatMapEager2(result,f);function compileTransformation(transformation){let apply=compileTransformationUnsafe(transformation);return(result,current,options)=>{try{return apply(result,current,options)}catch(error){return die3(error)}}}function compileTransformationUnsafe(transformation){if(transformation._tag==="Middleware")return(result,current,options)=>{let transformed=result===sameExit?transformation.decode(succeed6(toOption(current)),options):transformation.decode(mapEager2(result,toOption),options);return fromOptionalEffect(transformed)};let getter=transformation.decode;switch(getter._tag){case"Passthrough":return(result,current)=>result===sameExit?succeed6(current):result;case"Transform":{let transform=(value)=>value===missing?missingExit:succeed6(getter.transform(value));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformOptional":{let transform=(value)=>fromOptionExit(getter.transform(toOption(value)));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>value===missing?missingExit:getter.transform(value,options));case"TransformOptionalEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>fromOptionalEffect(getter.transform(toOption(value),options)))}}var fromOptionalEffect=(effect)=>flatMapEager2(effect,fromOptionExit),wrapEncoding=(ast,input,options,effect)=>catchCause2(effect,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new Encoding(ast,issue,input,options))));function makeConstructorParser(descriptor,compile){let transform=compileTransformation(descriptor.link.transformation),sourceParser;return(input,options)=>{if(input===missing)return missingExit;if(descriptor.isConstructed(input))return sameExit;let result=(sourceParser??=compile(descriptor.link.to))(input,options);return transform(result,input,options)}}function withDefault2(ast,parser){let defaultValue=ast.context.constructorDefault;return(input,options)=>{if(input!==missing&&input!==void 0)return parser(input,options);let result=defaultValue;if(effectIsExit(result)&&result._tag==="Success"){let local=parser(result[args],options);return local===sameExit?result:local}return flatMapEager2(wrapEncoding(ast,input,options,result),(value)=>{let local=parser(value,options);return local===sameExit?succeed6(value):local})}}function compileField(ast,compile){let parser=compile(ast);return ast.context?.constructorDefault===void 0?parser:withDefault2(ast,parser)}function compile(ast,compile,compileField,base,specialize){if(ast._tag==="Declaration")for(let parameter of ast.typeParameters)compile(parameter);let descriptor=compileField?getConstructorDescriptor(ast):void 0,parser=descriptor?makeConstructorParser(descriptor,compile):base??ast.getParser(compile,compileField),{checks,encoding:links}=ast,transformations=links?.map((link)=>compileTransformation(link.transformation)),encodingChecks=ast.encodingChecks;if(!links&&!checks&&!encodingChecks)return parser;let encodingParsers,parseChecks=(input,options)=>{let result=parser(input,options);try{if(encodingChecks&&!options.disableChecks)if(effectIsExit(result)){if(result._tag==="Success"){let output=result===sameExit?input:result[args];if(input!==missing&&output!==missing){let issues=collectIssues(encodingChecks,input,void 0,ast,options);if(issues)result=fail5(new Composite(ast,issues,input,options))}}}else result=flatMap2(result,(value)=>{if(input!==missing&&value!==missing){let issues=collectIssues(encodingChecks,input,void 0,ast,options);if(issues)return fail5(new Composite(ast,issues,input,options))}return succeed5(value)});if(checks&&!options.disableChecks)if(effectIsExit(result)){if(result._tag==="Success"){let value=result===sameExit?input:result[args];if(value===missing)return result;let issues=collectIssues(checks,value,void 0,ast,options);if(issues)result=fail5(new Composite(ast,issues,value,options))}}else result=flatMap2(result,(value)=>{if(value!==missing){let issues=collectIssues(checks,value,void 0,ast,options);if(issues)return fail5(new Composite(ast,issues,value,options))}return succeed5(value)});return result}catch(error){return die3(error)}},parseLocal=specialize===void 0?parseChecks:specialize(parseChecks);if(!links)return parseLocal;return(input,options)=>{let parsers=encodingParsers??=links.map((link)=>compile(link.to)),current=input,result=parsers[parsers.length-1](input,options);for(let i=links.length-1;i>=0;i--)if(result=transformations[i](result,current,options),i!==0){let next=parsers[i-1];if(result._tag==="Success")current=result[args],result=next(current,options);else result=flatMapEager2(result,(value)=>{let nextResult=next(value,options);return nextResult===sameExit?succeed6(value):nextResult})}if(result._tag==="Success"){let value=result[args],local=parseLocal(value,options);return local===sameExit?result:local}return result=wrapEncoding(ast,input,options,result),flatMapEager2(result,(value)=>{let local=parseLocal(value,options);return local===sameExit?succeed6(value):local})}}var invalid=Symbol(),cache=new WeakMap,compiler,compilerAdaptersEnabled=!1;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve2,ast,"parser"):resolve2(ast).parser,makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve2,ast,"makeEffect"):resolve2(ast).makeEffect,makeField=(ast)=>compileField(ast,makeChild);class InterpretedEntry{ast;constructor(ast){this.ast=ast}get decodeEffect(){return this.cachedDecodeEffect??=compile(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile(this.ast,makeChild,makeField)}}class CompilerEntry extends InterpretedEntry{compiled;resolve;constructor(ast,compiled,resolve){super(ast);this.compiled=compiled,this.resolve=resolve}save(key,value){return Object.defineProperty(this,key,{value}),value}operation(key){let compiled=this.compiled;return typeof compiled==="function"?compiled(this.ast,this.resolve,key):compiled?.[key]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get compiledMakeEffect(){return this.save("compiledMakeEffect",this.operation("makeEffect"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile(this.ast,(ast)=>lazyParser(this.resolve,ast,"parser")))}get parser(){let decode=this.decode;return decode===void 0?this.decodeEffect:this.save("parser",withDecode(decode,()=>this.decodeEffect))}get makeEffect(){let makeEffect=this.compiledMakeEffect;if(makeEffect!==void 0)return this.save("makeEffect",makeEffect);let child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile(this.ast,child,(ast)=>compileField(ast,child)))}}function withDecode(fastDecode,decodeEffect){let detailed;return(input,options)=>{if(input!==missing)try{let value=fastDecode(input,options);if(value!==invalid)return value===input?sameExit:succeed6(value)}catch(error){return die3(error)}return(detailed??=decodeEffect())(input,options)}}function lazyParser(resolve,ast,operation){let entry=resolve(ast);if(entry.compiled===void 0||Object.hasOwn(entry,operation))return entry[operation];let parser;return(input,options)=>(parser??=entry[operation])(input,options)}function resolve2(ast){let cached=cache.get(ast);if(cached!==void 0)return cached;let entry=compiler===void 0?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve2),resolve2);return cache.set(ast,entry),entry}function makeEffect(schema){let ast=schema.ast,parser;return(input,options)=>(parser??=runWithCompiler(constructorCompiler,toType(ast)))(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:!0}:{disableChecks:!0}:options?.parseOptions)}function makeOption(schema){let parser=makeEffect(schema);return(input,options)=>{let exit=runSyncExit2(parser(input,options));if(isSuccess3(exit))return some2(exit.value);return getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues"),none2()}}function make3(schema){return makeConstructorSync(toType(schema.ast))}function decodeUnknownEffect(schema,options){let parser=run(schema.ast);return options===void 0?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function decodeUnknownOption(schema,options){return asOption(decodeUnknownEffect(schema,options))}function encodeUnknownEffect(schema,options){let parser=run(flip2(schema.ast));return options===void 0?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var mergeParseOptions=(options,overrideOptions)=>overrideOptions?{...options,...overrideOptions}:options,getValue=(value)=>{if(value===missing)return fail5(new InvalidValue);return succeed5(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit)return succeed5(input);if(!effectIsExit(result))return flatMapEager2(result,getValue);return result[args]===missing?getValue(missing):result}function runWithCompiler(compiler,ast){let parser;return(input,options)=>{let result=(parser??=compiler(ast))(input,options??defaultParseOptions);if(result===sameExit)return succeed5(input);if(!effectIsExit(result))return flatMapEager2(result,getValue);return result[args]===missing?getValue(missing):result}}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function asOption(parser){let parserExit=asExit(parser);return(input,options)=>{let exit=parserExit(input,options);if(isSuccess3(exit))return some2(exit.value);return getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues"),none2()}}function runSync2(effect,message){let exit=runSyncExit2(effect);if(isSuccess3(exit))return exit.value;let issue=getSchemaIssueOrThrow(exit.cause,message);throw Error("Schema validation failed",{cause:issue})}var constructorDefectMessage="Constructor adapter can only throw schema issues";function throwConstructorDefect(error){throw Error(constructorDefectMessage,{cause:die2(error)})}function makeConstructorSync(ast){let entry;return(input,options)=>constructSync(entry??=resolve2(ast),input,options)}function constructSync(entry,input,options){let parseOptions=options?.disableChecks?options.parseOptions?{...options.parseOptions,disableChecks:!0}:{disableChecks:!0}:options?.parseOptions??defaultParseOptions,make=entry.make;if(make!==void 0&&input!==missing){let output;try{output=make(input,parseOptions)}catch(error){throwConstructorDefect(error)}if(output!==invalid&&output!==missing)return output}return runSync2(parserResult(entry.makeEffect(input,parseOptions),input),constructorDefectMessage)}var normalCompiler=(ast)=>resolve2(ast).parser,constructorCompiler=(ast)=>resolve2(ast).makeEffect;var TypeId7="~effect/Schema/Schema",RebuildOptions=Symbol(),SchemaProto={[TypeId7]:TypeId7,get make(){let value=make3(this);return Object.defineProperty(this,"make",{value,enumerable:!0}),value},get makeEffect(){let value=makeEffect(this);return Object.defineProperty(this,"makeEffect",{value,enumerable:!0}),value},get makeOption(){let value=makeOption(this);return Object.defineProperty(this,"makeOption",{value,enumerable:!0}),value},pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))},rebuild(ast){return make4(ast,this[RebuildOptions])}};function make4(ast,options){function Schema(){}let self=Object.setPrototypeOf(Schema,SchemaProto);if(options&&(Object.hasOwn(options,"name")||Object.hasOwn(options,"length")||Object.hasOwn(options,"__proto__")))Object.defineProperties(self,Object.getOwnPropertyDescriptors({...options}));else Object.assign(self,options);return self[RebuildOptions]=options,self.ast=ast,self}var lambda=(f)=>f;var SchemaErrorTypeId="~effect/Schema/SchemaError";function isSchemaError(u){return hasProperty(u,SchemaErrorTypeId)&&u[SchemaErrorTypeId]===SchemaErrorTypeId}function declareConstructor(){return(typeParameters,run,annotations)=>make5(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make5(ast))),annotations))}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed5(input):fail5(new InvalidType(ast,input,options)),annotations)}class SchemaError extends TaggedError2("SchemaError"){[SchemaErrorTypeId]=SchemaErrorTypeId;constructor(issue){let stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);try{super({issue})}finally{setStackTraceLimit(stackTraceLimit)}}get message(){return defaultFormatter(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[NodeInspectSymbol](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}}function isSchemaError2(u){return isSchemaError(u)}function fromIssueEffect(self){if(effectIsExit(self))return fromIssueExit(self);return catchCause2(self,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map3(exit.cause,(issue)=>new SchemaError(issue)))}function getSchemaErrorOrThrow(cause,message){let schemaError;for(let reason of cause.reasons){if(!isFailReason2(reason)||!isSchemaError2(reason.error))throw new globalThis.Error(message,{cause});schemaError??=reason.error}if(schemaError===void 0)throw new globalThis.Error(message,{cause});return schemaError}function runSchemaErrorSync(self){let exit=runSyncExit2(self);if(isSuccess3(exit))return exit.value;throw getSchemaErrorOrThrow(exit.cause,"Sync adapter can only throw schema errors")}function decodeUnknownEffect2(schema,options){let parser=decodeUnknownEffect(schema,options);return(input,options)=>fromIssueEffect(parser(input,options))}var decodeUnknownOption2=decodeUnknownOption;function decodeUnknownSync(schema,options){let parser=decodeUnknownEffect2(schema,options);return(input,options)=>runSchemaErrorSync(parser(input,options))}function encodeUnknownEffect2(schema,options){let parser=encodeUnknownEffect(schema,options);return(input,options)=>fromIssueEffect(parser(input,options))}function encodeUnknownSync(schema,options){let parser=encodeUnknownEffect2(schema,options);return(input,options)=>runSchemaErrorSync(parser(input,options))}var encodeSync=encodeUnknownSync,make5=make4;var optionalKey2=lambda((schema)=>make5(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{let schema=UndefinedOr(self);return make5(optional(self.ast),{schema})});var toEncoded2=lambda((schema)=>make5(toEncoded(schema.ast),{schema}));function Literal2(literal){let out=make5(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Null2=make5(null_),Undefined2=make5(undefined_2),String4=make5(string2);var Number5=make5(number2),Boolean3=make5(boolean);function makeStruct(ast,fields){return make5(ast,{fields,mapFields(f,options){let fields=f(this.fields);return makeStruct(struct(fields,options?.unsafePreserveChecks?this.ast.checks:void 0),fields)}})}function Struct(fields){return makeStruct(struct(fields,void 0),fields)}function makeTuple(ast,elements){return make5(ast,{elements,mapElements(f,options){let elements=f(this.elements);return makeTuple(tuple(elements,options?.unsafePreserveChecks?this.ast.checks:void 0),elements)}})}function Tuple(elements){return makeTuple(tuple(elements),elements)}var ArraySchema=lambda((schema)=>make5(new Arrays(!1,[],[schema.ast]),{value:schema}));var NonEmptyArray=lambda((schema)=>make5(new Arrays(!1,[schema.ast],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make5(ast,{members,mapMembers(f,options){let members=f(this.members);return makeUnion(union(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:void 0),members)}})}function Union2(members,options){return makeUnion(union(members,options,void 0),members)}function Literals(literals){let members=literals.map(Literal2);return make5(union(members,void 0,void 0),{literals,members,mapMembers(f){return Union2(f(this.members))},pick(literals){return Literals(literals)},transform(to){return Union2(members.map((member,index)=>member.transform(to[index])))}})}var NullOr=lambda((self)=>Union2([self,Null2])),UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function brand(identifier){return(schema)=>make5(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>make5(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}function toIssueEffect(self){if(effectIsExit(self)&&self._tag==="Success")return self;return catchCause2(self,(cause)=>failCauseSync2(()=>map3(cause,(error)=>error.issue)))}function withDecodingDefaultKey(defaultValue,options){let encode=options?.encodingStrategy==="omit"?omit():passthrough();return(self)=>optionalKey2(toEncoded2(self)).pipe(decodeTo2(self,{decode:withDefault(toIssueEffect(defaultValue)),encode}))}function instanceOf(constructor,annotations){return declare((u)=>u instanceof constructor,annotations)}function link(){return(encodeTo,transformation)=>new Link(encodeTo.ast,makeTransformation(transformation))}var makeFilter2=makeFilter;function isPattern2(regExp,annotations){let{source,flags}=regExp,canExport=/^[dg]*uy?$/.test(flags),runtimeRegExp=flags===""?`new globalThis.RegExp(${format(source)})`:`new globalThis.RegExp(${format(source)}, ${format(flags)})`;return isPattern(regExp,{toJsonSchema:()=>canExport?{pattern:flags.endsWith("y")?`^(?:${source})`:source}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${runtimeRegExp})`}),...annotations})}function isBase64(annotations){let regExp=/^[0-9a-zA-Z+/]*={0,2}$/;return makeFilter2((s)=>s.length%4===0&®Exp.test(s),{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:"^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"}),arbitraryConstraint:{patterns:[{source:"^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$",flags:""}]},toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make5(finite),isFinite2=isFinite;function makeIsGreaterThan(options){let gt=isGreaterThan(options.order),formatter=options.formatter??format;return(exclusiveMinimum,annotations)=>makeFilter2((input)=>gt(input,exclusiveMinimum),{expected:`a value greater than ${formatter(exclusiveMinimum)}`,arbitraryConstraint:{order:options.order,minimum:exclusiveMinimum,exclusiveMinimum:!0},...options.annotate?.(exclusiveMinimum),...annotations})}function makeIsGreaterThanOrEqualTo(options){let gte=isGreaterThanOrEqualTo(options.order),formatter=options.formatter??format;return(minimum,annotations)=>makeFilter2((input)=>gte(input,minimum),{expected:`a value greater than or equal to ${formatter(minimum)}`,arbitraryConstraint:{order:options.order,minimum},...options.annotate?.(minimum),...annotations})}function makeIsLessThanOrEqualTo(options){let lte=isLessThanOrEqualTo(options.order),formatter=options.formatter??format;return(maximum,annotations)=>makeFilter2((input)=>lte(input,maximum),{expected:`a value less than or equal to ${formatter(maximum)}`,arbitraryConstraint:{order:options.order,maximum},...options.annotate?.(maximum),...annotations})}function makeIsBetween(deriveOptions){let greaterThanOrEqualTo=isGreaterThanOrEqualTo(deriveOptions.order),greaterThan=isGreaterThan(deriveOptions.order),lessThanOrEqualTo=isLessThanOrEqualTo(deriveOptions.order),lessThan=isLessThan(deriveOptions.order),formatter=deriveOptions.formatter??format;return(options,annotations)=>{let gte=options.exclusiveMinimum?greaterThan:greaterThanOrEqualTo,lte=options.exclusiveMaximum?lessThan:lessThanOrEqualTo;return makeFilter2((input)=>gte(input,options.minimum)&<e(input,options.maximum),{expected:`a value between ${formatter(options.minimum)}${options.exclusiveMinimum?" (excluded)":""} and ${formatter(options.maximum)}${options.exclusiveMaximum?" (excluded)":""}`,arbitraryConstraint:{order:deriveOptions.order,minimum:options.minimum,maximum:options.maximum,...options.exclusiveMinimum&&{exclusiveMinimum:!0},...options.exclusiveMaximum&&{exclusiveMaximum:!0}},...deriveOptions.annotate?.(options),...annotations})}}function encodeNumberPayload(number){if(!globalThis.Number.isFinite(number))throw new globalThis.RangeError(`Expected a finite number, got ${format(number)}`);return number}var isGreaterThan2=makeIsGreaterThan({order:Number2,annotate:(exclusiveMinimum)=>({representation:{id:"effect/schema/isGreaterThan",payload:{exclusiveMinimum:encodeNumberPayload(exclusiveMinimum)}},toJsonSchema:()=>({exclusiveMinimum}),toCode:()=>({runtime:`Schema.isGreaterThan(${format(exclusiveMinimum)})`})})}),isGreaterThanOrEqualTo2=makeIsGreaterThanOrEqualTo({order:Number2,annotate:(minimum)=>({representation:{id:"effect/schema/isGreaterThanOrEqualTo",payload:{minimum:encodeNumberPayload(minimum)}},toJsonSchema:()=>({minimum}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${format(minimum)})`})})});var isLessThanOrEqualTo2=makeIsLessThanOrEqualTo({order:Number2,annotate:(maximum)=>({representation:{id:"effect/schema/isLessThanOrEqualTo",payload:{maximum:encodeNumberPayload(maximum)}},toJsonSchema:()=>({maximum}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${format(maximum)})`})})}),isBetween=makeIsBetween({order:Number2,annotate:(options)=>{let exclusiveMinimum=options.exclusiveMinimum?!0:void 0,exclusiveMaximum=options.exclusiveMaximum?!0:void 0;return{representation:{id:"effect/schema/isBetween",payload:{minimum:encodeNumberPayload(options.minimum),maximum:encodeNumberPayload(options.maximum),...exclusiveMinimum&&{exclusiveMinimum},...exclusiveMaximum&&{exclusiveMaximum}}},toJsonSchema:()=>({[exclusiveMinimum?"exclusiveMinimum":"minimum"]:options.minimum,[exclusiveMaximum?"exclusiveMaximum":"maximum"]:options.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${format(options.minimum)}, maximum: ${format(options.maximum)}, exclusiveMinimum: ${format(exclusiveMinimum)}, exclusiveMaximum: ${format(exclusiveMaximum)} })`})}}});function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>({type:"integer",minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...annotations})}var Int=Number5.check(isInt());function isMinLength(minLength,annotations){return minLength=normalizeCardinality(minLength),makeIsMinLength(minLength,Math.ceil(minLength/2),annotations)}function makeIsMinLength(minLength,minCodePoints,annotations){return makeFilter2((input)=>input.length>=minLength,{expected:`a value with a length of at least ${minLength}`,representation:{id:"effect/schema/isMinLength",payload:{minLength}},toJsonSchema:({type})=>type==="string"?minLength<=1?{minLength:minCodePoints}:[{minLength:minCodePoints},!0]:type==="array"?{minItems:minLength}:type===void 0?[{minLength:minCodePoints,minItems:minLength},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${minLength})`}),[STRUCTURAL_ANNOTATION_KEY]:!0,arbitraryConstraint:{minLength},...annotations})}function isNonEmpty(annotations){return makeIsMinLength(1,1,annotations)}function isMaxLength(maxLength,annotations){return maxLength=normalizeCardinality(maxLength),makeFilter2((input)=>input.length<=maxLength,{expected:`a value with a length of at most ${maxLength}`,representation:{id:"effect/schema/isMaxLength",payload:{maxLength}},toJsonSchema:({type})=>type==="string"?maxLength===0?{maxLength}:[{maxLength},!0]:type==="array"?{maxItems:maxLength}:type===void 0?[{maxLength,maxItems:maxLength},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${maxLength})`}),[STRUCTURAL_ANNOTATION_KEY]:!0,arbitraryConstraint:{maxLength},...annotations})}function normalizeCardinality(value){if(!globalThis.Number.isFinite(value))throw new globalThis.RangeError(`Expected a finite number, got ${value}`);return Math.max(0,Math.floor(value))}var NonEmptyString=String4.check(isNonEmpty());var RegExp2=instanceOf(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:"Schema.RegExp",Type:"globalThis.RegExp"}),expected:"RegExp",toCodecJson:()=>link()(Struct({source:String4,flags:String4}),transformEffect2({decode:(e,options)=>try_2({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed5({source:regExp.source,flags:regExp.flags})}))}),URLString=String4.annotate({expected:"a string that will be decoded as a URL"}),URL2=instanceOf(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:"Schema.URL",Type:"globalThis.URL"}),expected:"URL",toCodecJson:()=>link()(URLString,urlFromString)});var JsonString=String4.annotate({expected:"a string that will be decoded as JSON"});function fromJsonString2(schema,options){return JsonString.pipe(decodeTo2(schema,fromJsonString(options)))}var File2=instanceOf(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:"Schema.File",Type:"globalThis.File"}),expected:"File",toCodecJson:()=>link()(Struct({data:String4.check(isBase64()),type:String4,name:String4,lastModified:Int}),transformEffect2({decode:(e,options)=>match(decode(e.data),{onFailure:()=>fail5(new InvalidValue({expected:"a valid Base64 string"},e.data,options)),onSuccess:(bytes)=>{let buffer=new globalThis.Uint8Array(bytes);return succeed5(new globalThis.File([buffer],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(file,options)=>tryPromise2({try:async()=>{let bytes=new globalThis.Uint8Array(await file.arrayBuffer());return{data:encode(bytes),type:file.type,name:file.name,lastModified:file.lastModified}},catch:()=>new InvalidValue({expected:"a readable File"},file,options)})}))});var URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:"Schema.URLSearchParams",Type:"globalThis.URLSearchParams"}),expected:"URLSearchParams",toCodecJson:()=>link()(String4.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var FiniteFromString=String4.annotate({expected:"a string that will be decoded as a finite number"}).pipe(decodeTo2(Finite,numberFromString));var Base64String=String4.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"}),Uint8Array2=instanceOf(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:"Schema.Uint8Array",Type:"globalThis.Uint8Array"}),expected:"Uint8Array",toCodecJson:()=>link()(Base64String,uint8ArrayFromBase64String)});var arbitraryMinimumDateTimestamp=-8640000000000000,arbitraryMaximumDateTimestamp=8640000000000000,arbitraryMinimumZonedDateTimeTimestamp=arbitraryMinimumDateTimestamp+50400000,arbitraryMaximumZonedDateTimeTimestamp=arbitraryMaximumDateTimestamp-50400000;var OrganizationId=String4.check(isPattern2(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/)).pipe(brand("OrganizationId")),OrganizationSummary=Struct({id:OrganizationId,name:NonEmptyString,slug:NonEmptyString,personal:Boolean3}),WorkspaceAccount=Struct({user:Struct({name:String4,email:String4,emailVerified:Boolean3,image:NullOr(String4),signedInWith:Literals(["github","password"])}),active:OrganizationSummary,organizations:ArraySchema(OrganizationSummary),members:ArraySchema(Struct({id:String4,name:String4,email:String4,role:String4})),role:String4});var Identity=String4.check(isPattern2(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/)),Natural=Number5.check(isInt(),isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)),RepositoryId=String4.check(isPattern2(/^(?:github:[1-9][0-9]{0,15}|local:[a-z0-9][a-z0-9._-]{0,127})$/)).pipe(brand("RepositoryId")),GitHubRepositoryNumber=Natural.check(isGreaterThanOrEqualTo2(1)).pipe(brand("GitHubRepositoryNumber")),LocalRepositoryName=String4.check(isPattern2(/^[a-z0-9][a-z0-9._-]{0,127}$/)).pipe(brand("LocalRepositoryName"));var SnapshotId=Identity.pipe(brand("SnapshotId")),FileId=Identity.pipe(brand("FileId")),OccurrenceId=Identity.pipe(brand("OccurrenceId")),GroupId=Identity.pipe(brand("GroupId")),AccountUserId=String4.check(isPattern2(/^[A-Za-z0-9_-]{1,200}$/)).pipe(brand("AccountUserId")),ReviewerId=String4.check(isPattern2(/^account:[A-Za-z0-9_-]{1,200}$/)).pipe(brand("ReviewerId"));var DecisionId=Identity.pipe(brand("DecisionId")),CommandId=Identity.pipe(brand("CommandId")),CommentId=Identity.pipe(brand("CommentId")),PublicationId=Identity.pipe(brand("PublicationId")),Fingerprint=String4.check(isPattern2(/^[a-f0-9]{64}$/)).pipe(brand("Fingerprint")),GitRevision=String4.check(isPattern2(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)).pipe(brand("GitRevision")),RepoPath=String4.check(makeFilter2((path)=>path.length>0&&path.length<=4096&&!path.startsWith("/")&&!path.includes("\\")&&!/[\u0000-\u001f\u007f]/u.test(path)&&path.split("/").every((part)=>part!==""&&part!=="."&&part!==".."))).pipe(brand("RepoPath")),ByteOffset=Natural.pipe(brand("ByteOffset")),ByteLength=Natural.pipe(brand("ByteLength")),LineNumber=Natural.check(isGreaterThanOrEqualTo2(1)).pipe(brand("LineNumber")),Version=Natural.pipe(brand("Version")),Timestamp=String4.check(makeFilter2((text)=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(text)&&Number.isFinite(Date.parse(text))&&new Date(text).toISOString()===text)).pipe(brand("Timestamp")),CommentBody=String4.check(isMinLength(1),isMaxLength(65536),makeFilter2((text)=>text.trim().length>0)).pipe(brand("CommentBody")),EntityId=Identity.pipe(brand("EntityId")),Similarity=Number5.check(isFinite2(),isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(1)).pipe(brand("Similarity")),CommentVersion=Natural.pipe(brand("CommentVersion")),RemotePositiveId=Natural.check(isGreaterThanOrEqualTo2(1)),GitHubReviewCommentId=RemotePositiveId.pipe(brand("GitHubReviewCommentId")),GitHubIssueCommentId=RemotePositiveId.pipe(brand("GitHubIssueCommentId")),GitHubReviewId=RemotePositiveId.pipe(brand("GitHubReviewId"));var AgentName=String4.check(isPattern2(/^[A-Za-z0-9][A-Za-z0-9 ._:/@()+-]{0,63}$/),makeFilter2((text)=>text.trimEnd()===text)).pipe(brand("AgentName")),Actor=Union2([Struct({kind:Literal2("human"),suggestedBy:optional2(AgentName)}),Struct({kind:Literal2("agent"),agent:AgentName})]);var CatalogEntry=Struct({id:OccurrenceId,fingerprint:Fingerprint}),OccurrenceIndex=Int.check(isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("OccurrenceIndex")),Position=Int.check(isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)),Count=Int.check(isGreaterThanOrEqualTo2(1)),Runs=NonEmptyArray(Tuple([Position,Count])).check(makeFilter2((runs)=>runs.every(([start],index)=>{let previous=runs[index-1];return previous===void 0||start>previous[0]+previous[1]}))),expand=([start,count])=>Array.from({length:count},(_,offset)=>start+offset),runsOf=(positions)=>{let runs=[];for(let position of[...positions].sort((left,right)=>left-right)){let last=runs.at(-1);if(last!==void 0&&position===last[0]+last[1])last[1]++;else if(last===void 0||position>last[0]+last[1])runs.push([position,1])}let[head=[positions[0],1],...tail]=runs;return[head,...tail]},OccurrencePositions=Runs.pipe(decodeTo2(NonEmptyArray(OccurrenceIndex),transform2({decode:([head,...tail])=>[head[0],...expand([head[0]+1,head[1]-1]),...tail.flatMap(expand)],encode:runsOf})));var Disposition=Literals(["inspected","no-further-inspection","not-reviewed"]);var CarriedFrom=Struct({snapshotId:SnapshotId,decisionId:DecisionId}),HistorySubject=String4.check(isMinLength(1),isMaxLength(160),makeFilter2((text)=>text.trim()===text&&!/[\u0000-\u001f\u007f]/u.test(text))).pipe(brand("HistorySubject")),provenanceFields={actor:Actor,carriedFrom:optional2(CarriedFrom),subject:optional2(HistorySubject),redoOf:optional2(DecisionId)},ReviewDecision=Struct({id:DecisionId,snapshotId:SnapshotId,occurrenceIds:NonEmptyArray(OccurrenceId),disposition:Disposition,recordedAt:Timestamp,...provenanceFields}),RevisitAction=Literals(["mark","clear"]),RevisitDecision=Struct({id:DecisionId,snapshotId:SnapshotId,occurrenceIds:NonEmptyArray(OccurrenceId),action:RevisitAction,recordedAt:Timestamp,...provenanceFields}),PositionedReviewDecision=Struct({id:DecisionId,occurrences:OccurrencePositions,disposition:Disposition,recordedAt:Timestamp,...provenanceFields}),PositionedRevisitDecision=Struct({id:DecisionId,occurrences:OccurrencePositions,action:RevisitAction,recordedAt:Timestamp,...provenanceFields}),Count2=Int.check(isGreaterThanOrEqualTo2(0)),PositiveCount=Int.check(isGreaterThanOrEqualTo2(1)),HistoryEntryKind=Literals(["review","revisit","clear-revisit"]),ChangedStep=Struct({decisionId:DecisionId,changedEdits:PositiveCount,lapsed:optional2(Struct({kind:HistoryEntryKind,disposition:NullOr(Disposition),subject:optional2(HistorySubject),actor:Actor,recordedAt:Timestamp}))}),HistoryEvent=Union2([Struct({kind:Literal2("recorded"),decisionId:DecisionId}),Struct({kind:Literal2("undone"),decisionId:DecisionId,actor:Actor}),Struct({kind:Literal2("redone"),decisionId:DecisionId,redoDecisionId:DecisionId}),Struct({kind:Literal2("carried"),from:SnapshotId,changed:ArraySchema(ChangedStep)})]),commandFields={commandId:CommandId,snapshotId:SnapshotId,reviewerId:ReviewerId,expectedVersion:Version,actor:optional2(Actor)},selectionFields={decisionId:DecisionId,occurrenceIds:NonEmptyArray(OccurrenceId),recordedAt:Timestamp,subject:optional2(HistorySubject)},ReviewCommand=Union2([Struct({...commandFields,...selectionFields,kind:Literal2("review-edits"),disposition:Disposition}),Struct({...commandFields,kind:Literal2("undo-review"),decisionId:DecisionId}),Struct({...commandFields,...selectionFields,kind:Literal2("mark-revisit")}),Struct({...commandFields,...selectionFields,kind:Literal2("clear-revisit")}),Struct({...commandFields,kind:Literal2("redo-review"),decisionId:DecisionId,redoDecisionId:DecisionId,recordedAt:Timestamp})]),CatalogSelection=Struct({catalogDigest:Fingerprint,occurrences:OccurrencePositions}),positionedSelectionFields={decisionId:DecisionId,selection:CatalogSelection,recordedAt:Timestamp,subject:optional2(HistorySubject)},PositionedReviewCommand=Union2([Struct({...commandFields,...positionedSelectionFields,kind:Literal2("review-edits"),disposition:Disposition}),Struct({...commandFields,kind:Literal2("undo-review"),decisionId:DecisionId}),Struct({...commandFields,...positionedSelectionFields,kind:Literal2("mark-revisit")}),Struct({...commandFields,...positionedSelectionFields,kind:Literal2("clear-revisit")}),Struct({...commandFields,kind:Literal2("redo-review"),decisionId:DecisionId,redoDecisionId:DecisionId,recordedAt:Timestamp})]);var ReviewReceipt=Struct({commandId:CommandId,version:Version,snapshotId:SnapshotId}),CommandRecord=Struct({commandId:CommandId,fingerprint:Fingerprint,receipt:ReviewReceipt}),ReviewState=Struct({snapshotId:SnapshotId,reviewerId:ReviewerId,version:Version,catalog:ArraySchema(CatalogEntry),decisions:ArraySchema(ReviewDecision),revisits:ArraySchema(RevisitDecision),undoneDecisionIds:ArraySchema(DecisionId),history:ArraySchema(HistoryEvent),commands:ArraySchema(CommandRecord)}),PositionedReviewState=Struct({snapshotId:SnapshotId,reviewerId:ReviewerId,version:Version,catalogDigest:Fingerprint,occurrences:Int.check(isGreaterThanOrEqualTo2(0)),decisions:ArraySchema(PositionedReviewDecision),revisits:ArraySchema(PositionedRevisitDecision),undoneDecisionIds:ArraySchema(DecisionId),history:ArraySchema(HistoryEvent)}),ReviewError=Union2([Struct({kind:Literal2("stale-snapshot"),expected:SnapshotId,received:SnapshotId}),Struct({kind:Literal2("stale-version"),expected:Version,received:Version}),Struct({kind:Literal2("wrong-reviewer")}),Struct({kind:Literal2("command-conflict"),commandId:CommandId}),Struct({kind:Literal2("unknown-occurrences"),occurrenceIds:NonEmptyArray(OccurrenceId)}),Struct({kind:Literal2("duplicate-occurrences")}),Struct({kind:Literal2("decision-conflict"),decisionId:DecisionId}),Struct({kind:Literal2("unknown-decision"),decisionId:DecisionId}),Struct({kind:Literal2("already-undone"),decisionId:DecisionId}),Struct({kind:Literal2("not-undone"),decisionId:DecisionId}),Struct({kind:Literal2("already-redone"),decisionId:DecisionId,redoDecisionId:DecisionId}),Struct({kind:Literal2("nothing-to-redo"),decisionId:DecisionId}),Struct({kind:Literal2("revisit-not-applicable"),action:RevisitAction,occurrenceIds:NonEmptyArray(OccurrenceId)}),Struct({kind:Literal2("version-exhausted")})]),ReviewResult=Union2([Struct({kind:Literal2("accepted"),state:ReviewState,receipt:ReviewReceipt,replayed:Boolean3}),Struct({kind:Literal2("rejected"),error:ReviewError})]),PositionedReviewResult=Union2([Struct({kind:Literal2("accepted"),progress:PositionedReviewState,receipt:ReviewReceipt,replayed:Boolean3}),Struct({kind:Literal2("rejected"),error:ReviewError})]);var OccurrenceStatus=Literals(["pending","reviewed","revisit"]);var StatusCounts=Struct({total:Count2,reviewed:Count2,revisit:Count2,pending:Count2,remaining:Count2});var HistoryEntry=Struct({decisionId:DecisionId,kind:HistoryEntryKind,disposition:NullOr(Disposition),subject:NullOr(HistorySubject),editCount:PositiveCount,changedEdits:Count2,lapsed:Boolean3,earlierRevision:Boolean3,actor:Actor,recordedAt:Timestamp,label:NonEmptyString});var ScopeState=Literals(["empty","pending","partial","reviewed","revisit"]);var CommentAnchor=Union2([Struct({kind:Literal2("line"),snapshotId:SnapshotId,fileId:FileId,path:RepoPath,commit:GitRevision,side:Literals(["base","head"]),line:LineNumber,startLine:optional2(LineNumber)}).check(makeFilter2((anchor)=>anchor.startLine===void 0||anchor.startLine<anchor.line)),Struct({kind:Literal2("review"),snapshotId:SnapshotId}),Struct({kind:Literal2("github-thread"),snapshotId:SnapshotId,rootCommentId:GitHubReviewCommentId})]),HttpsUrl=String4.check(makeFilter2((input)=>{try{let url=new URL(input);return url.protocol==="https:"&&!url.username&&!url.password}catch{return!1}})).pipe(brand("HttpsUrl")),GitHubCommentId=Number5.check(isInt(),isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("GitHubCommentId")),fields={id:CommentId,reviewerId:ReviewerId,anchor:CommentAnchor,body:CommentBody,createdAt:Timestamp,updatedAt:Timestamp,version:CommentVersion,writtenBy:optional2(Actor)},DraftComment=Struct({...fields,kind:Literal2("draft")}),PublishingComment=Struct({...fields,kind:Literal2("publishing"),publicationId:PublicationId}),UncertainComment=Struct({...fields,kind:Literal2("uncertain"),publicationId:PublicationId,reason:NonEmptyString}),PublishedComment=Struct({...fields,kind:Literal2("published"),publicationId:PublicationId,remoteId:GitHubCommentId,url:HttpsUrl}),Comment=Union2([DraftComment,PublishingComment,UncertainComment,PublishedComment]),CommentError=Union2([Struct({kind:Literal2("stale-comment"),expected:CommentVersion,received:CommentVersion}),Struct({kind:Literal2("comment-version-exhausted")}),Struct({kind:Literal2("comment-locked"),state:Literals(["publishing","uncertain","published"])}),Struct({kind:Literal2("stale-anchor"),expected:SnapshotId,received:SnapshotId}),Struct({kind:Literal2("wrong-publication"),expected:PublicationId,received:PublicationId}),Struct({kind:Literal2("not-publishing")}),Struct({kind:Literal2("proposal-stale"),baseVersion:CommentVersion,current:CommentVersion})]),CommentResult=Union2([Struct({kind:Literal2("accepted"),comment:Comment}),Struct({kind:Literal2("rejected"),error:CommentError})]);var PublicationOutcome=Union2([Struct({kind:Literal2("confirmed"),remoteId:GitHubCommentId,url:HttpsUrl}),Struct({kind:Literal2("uncertain"),reason:NonEmptyString}),Struct({kind:Literal2("confirmed-not-published")})]);var ProposalReason=String4.check(isMinLength(1),isMaxLength(2000)),CommentEditProposal=Struct({id:CommandId,commentId:CommentId,baseVersion:CommentVersion,baseBody:CommentBody,body:CommentBody,proposedBy:AgentName,reason:optional2(ProposalReason),createdAt:Timestamp});var ExactCorrespondence=Struct({previousSnapshotId:SnapshotId,nextSnapshotId:SnapshotId,matches:ArraySchema(Struct({previousOccurrenceId:OccurrenceId,nextOccurrenceId:OccurrenceId,fingerprint:Fingerprint,basis:Literal2("exact-file-context")}))}),CarryResult=Union2([Struct({kind:Literal2("accepted"),state:ReviewState}),Struct({kind:Literal2("rejected"),reason:Literals(["wrong-snapshot","duplicate-catalog","invalid-correspondence","ambiguous-fingerprint"])})]);var FindingSeverity=Literals(["critical","high","medium","low"]),FindingConfidence=Literals(["high","medium","low"]),FindingId=String4.check(isPattern2(/^finding_[a-f0-9]{32}$/)).pipe(brand("FindingId")),NonBlank=(max)=>String4.check(isMinLength(1),isMaxLength(max),makeFilter2((text)=>text.trim().length>0)),FindingTitle=NonBlank(200).pipe(brand("FindingTitle")),FindingDetail=NonBlank(4000).pipe(brand("FindingDetail")),MAX_FINDING_EDITS=50,MAX_REPORTED_FINDINGS=50;var FindingInput=Struct({occurrenceIds:ArraySchema(OccurrenceId).check(isMinLength(1),isMaxLength(MAX_FINDING_EDITS),makeFilter2((ids)=>new Set(ids).size===ids.length)),severity:FindingSeverity,confidence:FindingConfidence,title:FindingTitle,detail:FindingDetail}),FindingInputs=ArraySchema(FindingInput).check(isMinLength(1),isMaxLength(MAX_REPORTED_FINDINGS)),FindingState=Union2([Struct({kind:Literal2("open")}),Struct({kind:Literal2("drafted"),commentId:CommentId,at:Timestamp}),Struct({kind:Literal2("dismissed"),at:Timestamp})]),Finding=Struct({id:FindingId,reportId:CommandId,snapshotId:SnapshotId,...FindingInput.fields,reportedBy:AgentName,reportedAt:Timestamp,state:FindingState});var GitHubOwner=String4.check(isPattern2(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/)).pipe(brand("GitHubOwner")),GitHubRepository=String4.check(isPattern2(/^[A-Za-z0-9_.-]{1,100}$/),makeFilter2((name)=>name!=="."&&name!=="..")).pipe(brand("GitHubRepository")),PullRequestNumber=Number5.check(isInt(),isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("PullRequestNumber")),GitHubReference=Struct({owner:GitHubOwner,repository:GitHubRepository,number:PullRequestNumber});var MergeMethod=Literals(["merge","squash","rebase"]),CommitTitle=String4.check(isMinLength(1),isMaxLength(1024)),CommitBody=String4.check(isMaxLength(65536)),MergeCommitMessage=Struct({title:CommitTitle,body:CommitBody}),GitHubMergeBox=Struct({methods:ArraySchema(MergeMethod).check(isMaxLength(3)),defaultMethod:NullOr(MergeMethod),mergeable:Literals(["mergeable","conflicting","unknown"]),state:Literals(["clean","behind","blocked","dirty","unstable","has_hooks","draft","unknown"]),canUpdateBranch:Boolean3,messages:Struct({merge:NullOr(MergeCommitMessage),squash:NullOr(MergeCommitMessage)})}),MergePullRequest=Struct({method:MergeMethod,expectedHead:GitRevision,message:NullOr(MergeCommitMessage)}),MergeRefusal=Literals(["head-moved","not-mergeable","method-not-allowed","app-permission","no-permission","conflicts","not-found","invalid"]),MergeResponse=Union2([Struct({kind:Literal2("merged"),sha:GitRevision,method:MergeMethod}),Struct({kind:Literal2("refused"),refusal:MergeRefusal,message:NonEmptyString}),Struct({kind:Literal2("uncertain"),message:NonEmptyString})]),UpdatePullBranch=Struct({expectedHead:GitRevision}),UpdateBranchResponse=Union2([Struct({kind:Literal2("started"),message:NonEmptyString}),Struct({kind:Literal2("refused"),refusal:MergeRefusal,message:NonEmptyString}),Struct({kind:Literal2("uncertain"),message:NonEmptyString})]);var RemoteText=String4.check(isMaxLength(262144)),GitHubBodyHtml=String4.check(isMaxLength(524288)).pipe(brand("GitHubBodyHtml")),BodyHtml=optional2(GitHubBodyHtml),Count3=Int.check(isGreaterThanOrEqualTo2(0)),GitHubAuthor=Struct({login:String4.check(isMinLength(1),isMaxLength(100)),url:HttpsUrl}),GitHubCollectionCoverage=Union2([Struct({kind:Literal2("complete"),fetched:Count3}),Struct({kind:Literal2("partial"),fetched:Count3,reason:Literals(["page-limit","byte-limit","rate-limit","access-denied","not-found","upstream-error","invalid-response"]),message:NonEmptyString,retryAt:NullOr(Timestamp)})]),Name=String4.check(isMinLength(1),isMaxLength(256)),GitHubPullStats=Struct({additions:Count3,deletions:Count3,changedFiles:Count3,commits:Count3}),GitHubMergeability=Struct({mergeable:Literals(["mergeable","conflicting","unknown"]),mergeState:Literals(["clean","behind","blocked","dirty","unstable","has_hooks","draft","unknown"])}),GitHubLabel=Struct({name:Name,color:String4.check(isMaxLength(16))}),GitHubRequestedReviewer=Struct({kind:Literals(["user","team"]),name:Name}),GitHubPullFacts=Struct({stats:GitHubPullStats,mergeability:GitHubMergeability,requestedReviewers:ArraySchema(GitHubRequestedReviewer).check(isMaxLength(100)),assignees:ArraySchema(Name).check(isMaxLength(100)),labels:ArraySchema(GitHubLabel).check(isMaxLength(100)),milestone:NullOr(Struct({title:RemoteText,url:HttpsUrl}))}),GitHubPullMetadata=Struct({reference:GitHubReference,url:HttpsUrl,title:RemoteText,body:RemoteText,bodyHtml:BodyHtml,author:NullOr(GitHubAuthor),state:Literals(["open","closed","merged"]),draft:Boolean3,comparisonBaseRevision:NullOr(GitRevision),baseRevision:GitRevision,headRevision:GitRevision,baseRef:String4,headRef:String4,createdAt:Timestamp,updatedAt:Timestamp,facts:optional2(GitHubPullFacts)}),GitHubChecks=Union2([Struct({kind:Literal2("none")}),Struct({kind:Literal2("forbidden")}),Struct({kind:Literal2("rolled-up"),state:Literals(["success","failure","pending"]),passed:Count3,failed:Count3,pending:Count3,skipped:Count3})]),GitHubLinkedIssue=Struct({number:PullRequestNumber,title:RemoteText,url:HttpsUrl,state:Literals(["open","closed"])}),GitHubPullStatus=Union2([Struct({kind:Literal2("available"),headRevision:GitRevision,checks:GitHubChecks,isStale:optional2(Boolean3),reviewDecision:NullOr(Literals(["approved","changes-requested","review-required"])),linkedIssues:NullOr(ArraySchema(GitHubLinkedIssue).check(isMaxLength(10))),merge:optional2(GitHubMergeBox)}),Struct({kind:Literal2("unavailable")})]),GitHubIssueComment=Struct({id:GitHubIssueCommentId,author:NullOr(GitHubAuthor),body:RemoteText,bodyHtml:BodyHtml,url:HttpsUrl,createdAt:Timestamp,updatedAt:Timestamp}),GitHubReview=Struct({id:GitHubReviewId,author:NullOr(GitHubAuthor),body:RemoteText,bodyHtml:BodyHtml,url:HttpsUrl,state:Literals(["PENDING","APPROVED","CHANGES_REQUESTED","COMMENTED","DISMISSED"]),commit:GitRevision,submittedAt:NullOr(Timestamp)}),GitHubLineRange=Struct({side:Literals(["base","head"]),startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((range)=>range.endLine>=range.startLine)),GitHubReviewLocation=Union2([Struct({kind:Literal2("line"),path:RepoPath,commit:GitRevision,originalCommit:GitRevision,current:NullOr(GitHubLineRange),original:NullOr(GitHubLineRange),diffHunk:RemoteText}),Struct({kind:Literal2("file"),path:RepoPath,commit:GitRevision,originalCommit:GitRevision,diffHunk:RemoteText}),Struct({kind:Literal2("unavailable"),path:NullOr(RepoPath),reason:NonEmptyString,diffHunk:RemoteText})]),GitHubReviewComment=Struct({id:GitHubReviewCommentId,reviewId:NullOr(GitHubReviewId),inReplyTo:NullOr(GitHubReviewCommentId),author:NullOr(GitHubAuthor),body:RemoteText,bodyHtml:BodyHtml,url:HttpsUrl,createdAt:Timestamp,updatedAt:Timestamp,location:GitHubReviewLocation}),GitHubThreadResolution=Union2([Struct({kind:Literal2("resolved"),by:NullOr(GitHubAuthor)}),Struct({kind:Literal2("unresolved")})]),GitHubReviewThread=Union2([Struct({kind:Literal2("complete"),root:GitHubReviewComment,replies:ArraySchema(GitHubReviewComment),resolution:optional2(GitHubThreadResolution)}),Struct({kind:Literal2("missing-root"),rootId:GitHubReviewCommentId,comments:ArraySchema(GitHubReviewComment)})]),GitHubStackNumber=Int.check(isGreaterThan2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("GitHubStackNumber")),GitHubStackMember=Struct({number:PullRequestNumber,title:RemoteText,url:HttpsUrl,state:Literals(["open","closed","merged"]),draft:Boolean3,headRef:String4,headRevision:GitRevision}),GitHubStackStatus=Union2([Struct({kind:Literal2("none")}),Struct({kind:Literal2("available"),number:GitHubStackNumber,baseRef:String4,open:Boolean3,members:ArraySchema(GitHubStackMember).check(isMinLength(1),isMaxLength(100))}),Struct({kind:Literal2("unavailable"),message:NonEmptyString})]),GitHubDiscussion=Struct({pull:GitHubPullMetadata,fetchedAt:Timestamp,changedAt:optional2(Timestamp),stack:optional2(GitHubStackStatus),status:optional2(GitHubPullStatus),issueComments:ArraySchema(GitHubIssueComment),reviews:ArraySchema(GitHubReview),threads:ArraySchema(GitHubReviewThread),coverage:Struct({issueComments:GitHubCollectionCoverage,reviews:GitHubCollectionCoverage,reviewComments:GitHubCollectionCoverage})}),ResolveGitHubThread=Struct({rootCommentId:GitHubReviewCommentId,to:Literals(["resolved","unresolved"])}),GitHubThreadResolutionResponse=Union2([Struct({kind:Literal2("changed"),rootCommentId:GitHubReviewCommentId,resolution:GitHubThreadResolution}),Struct({kind:Literal2("refused"),refusal:Literals(["no-permission","app-permission","thread-gone"]),message:NonEmptyString})]);var Count4=Int.check(isGreaterThanOrEqualTo2(0)),Title=String4.check(isMaxLength(1024)),GitHubPushChange=Union2([Struct({kind:Literal2("added"),commits:Count4,files:Count4,filesCapped:Boolean3}),Struct({kind:Literal2("rewritten")}),Struct({kind:Literal2("unknown")})]),GitHubPushStatus=Union2([Struct({kind:Literal2("current"),updatedAt:optional2(Timestamp),isClosed:optional2(Boolean3)}),Struct({kind:Literal2("moved"),headRevision:GitRevision,change:GitHubPushChange,updatedAt:optional2(Timestamp),isClosed:optional2(Boolean3)})]),MyGitHubReview=Literals(["approved","approved-earlier","changes-requested","commented","none"]),PullRequestLabel=Struct({name:String4.check(isMinLength(1),isMaxLength(100)),color:String4.check(isPattern2(/^[0-9a-fA-F]{6}$/))}),BranchName=String4.check(isMinLength(1),isMaxLength(255)),PullRequestChecks=Literals(["success","failure","pending"]),PullRequestListItem=Struct({reference:GitHubReference,url:HttpsUrl,title:Title,author:NullOr(GitHubAuthor),isMine:Boolean3,draft:Boolean3,headRevision:GitRevision,updatedAt:Timestamp,myReview:MyGitHubReview,reviewRequested:Boolean3,additions:Count4,deletions:Count4,changedFiles:Count4,labels:ArraySchema(PullRequestLabel).check(isMaxLength(20)),checks:optional2(PullRequestChecks),baseRef:BranchName,headRef:BranchName}),ConnectedRepository=Struct({owner:GitHubOwner,repository:GitHubRepository}),KnownRepository=Struct({repositoryId:RepositoryId,...ConnectedRepository.fields}),ConnectedRepositories=Union2([Struct({kind:Literal2("unavailable"),reason:Literals(["not-connected","no-repositories","github-error"]),message:NonEmptyString}),Struct({kind:Literal2("available"),repositories:ArraySchema(KnownRepository),isPartial:Boolean3})]),PullRequestListCoverage=Union2([Struct({kind:Literal2("complete")}),Struct({kind:Literal2("partial"),message:NonEmptyString})]),PullRequestAuthor=String4.check(isPattern2(/^[A-Za-z0-9][A-Za-z0-9_-]{0,38}(?:\[bot\])?$/)).pipe(brand("PullRequestAuthor"));var PullRequestLabelName=String4.check(isMinLength(1),isMaxLength(100),isPattern2(/^[^"\u0000-\u001f\u007f]+$/u)).pipe(brand("PullRequestLabelName")),MAX_LABEL_FILTERS=5;var PullRequestFilters=Struct({notMine:Boolean3,notApprovedByMe:Boolean3,author:NullOr(PullRequestAuthor).pipe(withDecodingDefaultKey(succeed5(null))),labels:ArraySchema(PullRequestLabelName).check(isMaxLength(MAX_LABEL_FILTERS)).pipe(withDecodingDefaultKey(succeed5([])))});var PullRequestCursor=String4.check(isMinLength(1),isMaxLength(200),isPattern2(/^[A-Za-z0-9+/=_-]+$/)).pipe(brand("PullRequestCursor"));var MAX_LISTED_PULL_REQUESTS=100,AvailablePullRequestList=Struct({kind:Literal2("available"),viewer:NonEmptyString,fetchedAt:Timestamp,repositoryId:RepositoryId,repository:ConnectedRepository,filters:PullRequestFilters,pullRequests:ArraySchema(PullRequestListItem).check(isMaxLength(MAX_LISTED_PULL_REQUESTS)),next:NullOr(PullRequestCursor),coverage:PullRequestListCoverage}),PullRequestList=Union2([Struct({kind:Literal2("unavailable"),reason:Literals(["not-connected","not-readable","github-error"]),message:NonEmptyString}),AvailablePullRequestList]),ProjectPullRequests=Struct({open:Count4,counted:Count4,waitingForMe:Count4,byOthers:Count4,fetchedAt:Timestamp});var WorkspaceProject=Struct({repositoryId:RepositoryId,...ConnectedRepository.fields,addedAt:Timestamp}),ProjectAccess=Literals(["readable","no-access","unknown"]),WorkspaceProjects=Struct({projects:ArraySchema(Struct({...WorkspaceProject.fields,access:ProjectAccess,pullRequests:NullOr(ProjectPullRequests)})),canManage:Boolean3});var PinnedProjects=Struct({pinned:ArraySchema(ConnectedRepository).check(isMaxLength(100))});var IndexOmissionReason=Literals(["excluded","oversized","file-budget","byte-budget","binary","symlink","submodule"]);var LANGUAGE=String.raw`[a-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*`,RAILS_LOCALE=/^config\/locales\/(?:[^/]+\/)*[^/]+\.ya?ml$/u,I18NEXT_LOCALE=new RegExp(String.raw`^((?:[^/]+/)*locales)/(${LANGUAGE})/([A-Za-z0-9_\-]+)\.json$`,"u"),NEXT_INTL_LOCALE=new RegExp(String.raw`^((?:[^/]+/)*messages)/(${LANGUAGE})\.json$`,"u"),TranslationLibrary=Literals(["rails","i18next","next-intl"]),localeFileOf=(path)=>{if(/(?:^|\/)node_modules\//u.test(path))return null;if(RAILS_LOCALE.test(path))return{library:"rails",root:"config/locales"};let i18next=I18NEXT_LOCALE.exec(path);if(i18next!==null)return{library:"i18next",root:i18next[1]??"",locale:i18next[2]??"",namespace:i18next[3]??""};let nextIntl=NEXT_INTL_LOCALE.exec(path);if(nextIntl!==null)return{library:"next-intl",root:nextIntl[1]??"",locale:nextIntl[2]??""};return null},isLocalePath=(path)=>localeFileOf(path)!==null,LocaleRoot=Struct({library:TranslationLibrary,path:String4,files:Int.check(isGreaterThanOrEqualTo2(0)),namespaces:ArraySchema(String4)});var TranslationFrame=Union2([Struct({library:Literal2("rails")}),Struct({library:Literal2("i18next"),namespace:NullOr(String4),keyPrefix:NullOr(String4)}),Struct({library:Literal2("next-intl"),namespace:NullOr(String4)})]);var KEY=String.raw`\.?[A-Za-z0-9_][A-Za-z0-9_\-/]*(?:\.[A-Za-z0-9_][A-Za-z0-9_\-/]*)*`,SCRIPT_PART=String.raw`[A-Za-z0-9_$][A-Za-z0-9_$\-]*`,SCRIPT_KEY=String.raw`(?:[A-Za-z0-9_][A-Za-z0-9_\-]*:)?${SCRIPT_PART}(?:\.${SCRIPT_PART})*`,CALL=new RegExp(String.raw`(?<![\w@$.:])(?:I18n\s*\.\s*(?:t|translate)|t|translate)(?:\s*\(\s*|[ \t]+)(['"])(${KEY})\1`,"gu");var QUOTED=String.raw`(?:'([^'\\\n]*)'|"([^"\\\n]*)"|\x60([^\x60\\$\n]*)\x60)`;var NAME=String.raw`[A-Za-z_$][\w$]*`,I18NEXT_MODULE=String.raw`['"](?:i18next|react-i18next|next-i18next)['"]`,NEXT_INTL_MODULE=String.raw`['"]next-intl(?:/server)?['"]`;var TranslationKey=String4.check(isMinLength(1),isMaxLength(500),isPattern2(new RegExp(`^(?:${KEY}|${SCRIPT_KEY})$`,"u")));var LocaleTarget=Union2([Struct({library:Literal2("rails")}),Struct({library:Literal2("i18next"),root:String4,namespace:String4,isDefaultNamespace:Boolean3}),Struct({library:Literal2("next-intl"),root:String4})]);var LocaleReading=Union2([Struct({kind:Literal2("read"),entries:ArraySchema(Tuple([String4,String4,Int,String4]))}),Struct({kind:Literal2("unreadable"),reason:String4})]),LocaleFileReading=Struct({fileId:FileId,reading:LocaleReading});var LocaleText=Struct({line:Int.check(isGreaterThanOrEqualTo2(1)),value:String4}),TranslationChange=Struct({locale:String4,key:String4,head:NullOr(LocaleText),base:NullOr(LocaleText)}),LocaleFileChanges=Union2([Struct({kind:Literal2("read"),path:RepoPath,previousPath:NullOr(RepoPath),changes:ArraySchema(TranslationChange)}),Struct({kind:Literal2("unread"),path:RepoPath,previousPath:NullOr(RepoPath),reason:Literals(["unreadable","too-many-changes"])})]),IndexedTranslation=Struct({path:RepoPath,locale:String4,key:String4,line:Int,value:String4}),OmittedLocaleFile=Struct({path:RepoPath,reason:IndexOmissionReason});var IndexedTranslations=Struct({localeFiles:Int,unread:Int,localeRoots:ArraySchema(LocaleRoot),entries:ArraySchema(IndexedTranslation),unparsed:ArraySchema(Struct({path:RepoPath,reason:String4})),held:ArraySchema(RepoPath),omitted:NullOr(ArraySchema(OmittedLocaleFile))});var RouteFramework=Literals(["next","expo-router","tanstack-start"]),RouterFolder=Literals(["app","pages","src/app","src/pages"]),unique=(values)=>new Set(values).size===values.length,PackageSide=Union2([Struct({kind:Literal2("unreadable")}),Struct({kind:Literal2("read"),frameworks:ArraySchema(RouteFramework).check(makeFilter2(unique)),routing:NullOr(Struct({folders:ArraySchema(RouterFolder).check(makeFilter2(unique)),customised:ArraySchema(RouteFramework).check(makeFilter2(unique))}))})]),PackageDirectory=String4.check(makeFilter2((directory)=>directory===""||directory.length<=4096&&!directory.includes("\\")&&!/[\u0000-\u001f\u007f]/u.test(directory)&&directory.split("/").every((part)=>part!==""&&part!=="."&&part!==".."))),ProjectPackage=Struct({directory:PackageDirectory,base:NullOr(PackageSide),head:NullOr(PackageSide)}),RouteKind=Literals(["page","api","route","layout","template","loading","error","not-found","fallback","document","middleware","metadata"]),RouteRouter=Literals(["next-app","next-pages","expo-router","tanstack-start"]),FileRoute=Struct({router:RouteRouter,kind:RouteKind,path:String4.check(isPattern2(/^\//)),interceptedFrom:optional2(String4.check(isPattern2(/^\//))),platform:optional2(Literals(["ios","android","web","native"]))}),ModuleDirective=Literals(["use client","use server"]),Sides=(schema)=>Struct({before:NullOr(schema),after:NullOr(schema)}),FileRoutes=Sides(FileRoute),FileDirectives=Sides(ModuleDirective);var DependencyEcosystem=Literals(["rubygems","npm"]),DependencyFormat=Literals(["gemfile-lock","package-json","package-lock","yarn-lock","pnpm-lock","bun-lock"]),DependencyName=String4.check(isPattern2(/^(?:@[A-Za-z0-9._~-]{1,100}\/)?[A-Za-z0-9._~-]{1,214}$/u)).pipe(brand("DependencyName")),DependencyVersion=String4.check(isPattern2(/^[0-9][0-9A-Za-z.+_-]{0,63}$/u)).pipe(brand("DependencyVersion")),WrittenVersion=String4.check(isMinLength(1),isMaxLength(128)),DependencyTarget=Struct({ecosystem:DependencyEcosystem,name:DependencyName,from:DependencyVersion,to:DependencyVersion});var DependencyLookup=Union2([Struct({kind:Literal2("public"),target:DependencyTarget,registry:Literals(["named","default"])}),Struct({kind:Literal2("none"),reason:Literals(["other-source","not-a-version","same-version"])})]),DependencyChange=Union2([Struct({kind:Literal2("changed"),name:DependencyName,before:WrittenVersion,after:WrittenVersion,lookup:DependencyLookup}),Struct({kind:Literal2("added"),name:DependencyName,after:WrittenVersion}),Struct({kind:Literal2("removed"),name:DependencyName,before:WrittenVersion})]);var DependencyFileChanges=Union2([Struct({kind:Literal2("read"),path:RepoPath,format:DependencyFormat,ecosystem:DependencyEcosystem,changes:ArraySchema(DependencyChange),omitted:Int.check(isGreaterThanOrEqualTo2(0))}),Struct({kind:Literal2("unread"),path:RepoPath,format:DependencyFormat,ecosystem:DependencyEcosystem,message:String4})]);var SourceSpan=Struct({startByte:ByteOffset,byteLength:ByteLength,startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((span)=>span.endLine>=span.startLine&&(span.byteLength>0||span.endLine===span.startLine)&&span.startByte+span.byteLength<=Number.MAX_SAFE_INTEGER)),SourcePosition=Struct({path:RepoPath,byteOffset:ByteOffset,line:LineNumber}),SourceSelection=Struct({path:RepoPath,span:SourceSpan,text:String4}).check(makeFilter2((selection)=>{let extraLines=(selection.text.match(/\n/g)??[]).length-(selection.text.endsWith(`
|
|
20
|
-
`)?1:0);return!/[\uD800-\uDFFF]/u.test(selection.text)&&new TextEncoder().encode(selection.text).length===selection.span.byteLength&&selection.span.endLine===selection.span.startLine+extraLines})),Language=Literals(["ruby","javascript","typescript","tsx","json","jsonc","yaml","erb","shell","markdown","python","go","rust","java","css","toml","html","unknown"]),FileRole=Literals(["business","infrastructure","tests","documentation","configuration","dependencies","generated"]),ChangeKind=Literals(["added","deleted","modified","renamed"]),sourceText=String4.check(makeFilter2((value)=>!/[\uD800-\uDFFF]/u.test(value))),binaryBlobs={beforeBlob:optional2(NullOr(GitRevision)),afterBlob:optional2(NullOr(GitRevision))},InputFile=Union2([Struct({kind:Literal2("added"),path:RepoPath,after:sourceText}),Struct({kind:Literal2("deleted"),path:RepoPath,before:sourceText}),Struct({kind:Literal2("modified"),path:RepoPath,before:sourceText,after:sourceText}),Struct({kind:Literal2("renamed"),path:RepoPath,beforePath:RepoPath,before:sourceText,after:sourceText}),Struct({kind:Literal2("binary"),path:RepoPath,beforePath:NullOr(RepoPath),change:ChangeKind,media:Literals(["binary","svg","symlink","submodule"]),beforeHash:NullOr(Fingerprint),afterHash:NullOr(Fingerprint),beforeBytes:ByteLength,afterBytes:ByteLength,...binaryBlobs}),Struct({kind:Literal2("metadata"),path:RepoPath,beforeMode:String4,afterMode:String4})]),packagesField={packages:optional2(ArraySchema(ProjectPackage))},AnalyzeInput=Struct({repositoryId:RepositoryId,baseRevision:GitRevision,headRevision:GitRevision,files:ArraySchema(InputFile),...packagesField}).check(makeFilter2((input)=>{let keys=input.files.map((file)=>`${file.kind==="metadata"?"metadata":"content"}:${file.path}`);return new Set(keys).size===keys.length})),Coverage=Union2([Struct({kind:Literal2("parsed"),language:Language}),Struct({kind:Literal2("fallback"),reason:String4})]),AnalyzedFile=Union2([Struct({kind:Literal2("text"),id:FileId,path:RepoPath,previousPath:NullOr(RepoPath),change:ChangeKind,before:NullOr(String4),after:NullOr(String4),language:Language,role:FileRole,coverage:Coverage,occurrenceIds:ArraySchema(OccurrenceId),routes:optional2(FileRoutes),directives:optional2(FileDirectives)}),Struct({kind:Literal2("binary"),id:FileId,path:RepoPath,previousPath:NullOr(RepoPath),change:ChangeKind,media:Literals(["binary","svg","symlink","submodule"]),beforeHash:NullOr(Fingerprint),afterHash:NullOr(Fingerprint),beforeBytes:ByteLength,afterBytes:ByteLength,...binaryBlobs,role:FileRole,occurrenceIds:ArraySchema(OccurrenceId)}),Struct({kind:Literal2("metadata"),id:FileId,path:RepoPath,beforeMode:String4,afterMode:String4,role:FileRole,occurrenceIds:ArraySchema(OccurrenceId)})]),EditCategory=Literals(["presentation","identifier","content","structure","comment","literal","metadata"]),occurrenceFields={id:OccurrenceId,snapshotId:SnapshotId,fileId:FileId,category:EditCategory,label:String4,fingerprint:Fingerprint},EditOccurrence=Union2([Struct({...occurrenceFields,kind:Literal2("added"),after:SourceSelection,beforePosition:SourcePosition}),Struct({...occurrenceFields,kind:Literal2("removed"),before:SourceSelection,afterPosition:SourcePosition}),Struct({...occurrenceFields,kind:Literal2("replaced"),before:SourceSelection,after:SourceSelection}),Struct({...occurrenceFields,kind:Literal2("metadata"),path:RepoPath,before:sourceText,after:sourceText})]),EditKind=Literals(["replacement","insertion","deletion","metadata"]);var TextOffset=Int.check(isGreaterThanOrEqualTo2(0)).pipe(brand("TextOffset")),TextRange=Struct({start:TextOffset,end:TextOffset}).check(makeFilter2((range)=>range.end>range.start)),ExampleExcerpt=Struct({source:SourceSelection,highlights:ArraySchema(TextRange)}).check(makeFilter2((excerpt)=>excerpt.highlights.every((range,index)=>range.end<=excerpt.source.text.length&&(index===0||(excerpt.highlights[index-1]?.end??0)<=range.start)))),ShapeExample=Struct({occurrenceId:OccurrenceId,before:ExampleExcerpt,after:ExampleExcerpt}),ShapeContext=Literals(["call","definition","parameter","property-key","import","type","variable","reference","code","string","symbol","comment","regex","documentation","data","template","text"]),NamingConvention=Literals(["snake","camel","pascal","screaming","lower","other"]),ShapeKey=String4.check(isPattern2(/^[a-z]+(?:-[a-z]+)*(?::[a-z]+)?$/)).pipe(brand("ShapeKey")),ReplacementVariant=Struct({beforeText:String4,afterText:String4,convention:NamingConvention}),ReplacementShape=Struct({key:ShapeKey,context:ShapeContext,convention:NamingConvention,label:String4,unusual:Boolean3,reason:NullOr(String4),occurrenceIds:NonEmptyArray(OccurrenceId),fileCount:Int.check(isGreaterThanOrEqualTo2(1)),example:ShapeExample}).check(makeFilter2((shape)=>shape.occurrenceIds.includes(shape.example.occurrenceId))),groupFields={id:GroupId,label:String4,occurrenceIds:ArraySchema(OccurrenceId),explanation:String4},ReplacementGroup=Struct({...groupFields,kind:Literal2("replacement"),beforeText:String4,afterText:String4,variants:NonEmptyArray(ReplacementVariant),shapes:NonEmptyArray(ReplacementShape)}).check(makeFilter2((group)=>{let members=new Set(group.occurrenceIds),shaped=group.shapes.flatMap((shape)=>shape.occurrenceIds);return members.size===group.occurrenceIds.length&&shaped.length===members.size&&new Set(shaped).size===shaped.length&&shaped.every((id)=>members.has(id))})),ReviewGroup=Union2([Struct({...groupFields,kind:Literal2("role"),role:FileRole}),Struct({...groupFields,kind:Literal2("feature"),feature:String4,within:optional2(String4)}),ReplacementGroup,Struct({...groupFields,kind:Literal2("move"),origin:SourceSelection,destination:SourceSelection,match:Literals(["exact","edited"]),similarity:Similarity}),Struct({...groupFields,kind:Literal2("copy"),origin:SourceSelection,destination:SourceSelection,match:Literal2("exact")}),Struct({...groupFields,kind:Literal2("addition"),text:String4,fileCount:Int.check(isGreaterThanOrEqualTo2(1))})]),SourceEntity=Struct({id:EntityId,fileId:FileId,side:Literals(["before","after"]),name:String4,kind:String4,source:SourceSelection,fingerprint:Fingerprint}),AnalysisLimitation=Struct({path:NullOr(RepoPath),code:Literals(["unsupported-language","parse-error","size-limit","diff-limit","binary","oversized-svg","ambiguous-move","work-limit"]),message:String4}),AnalyzerRevision=String4.check(isPattern2(/^tree-sitter-v[1-9][0-9]*$/)).pipe(brand("AnalyzerRevision")),AnalysisSnapshot=Struct({analyzerRevision:AnalyzerRevision,id:SnapshotId,repositoryId:RepositoryId,baseRevision:GitRevision,headRevision:GitRevision,files:ArraySchema(AnalyzedFile),occurrences:ArraySchema(EditOccurrence),groups:ArraySchema(ReviewGroup),entities:ArraySchema(SourceEntity),limitations:ArraySchema(AnalysisLimitation),localeChanges:optional2(ArraySchema(LocaleFileChanges)),...packagesField,dependencyChanges:optional2(ArraySchema(DependencyFileChanges))});var offset=decodeUnknownSync(ByteOffset),length=decodeUnknownSync(ByteLength),line=decodeUnknownSync(LineNumber);var QueryText=String4.check(isMinLength(1),isMaxLength(1000),makeFilter2((text)=>text.trim().length>0)).pipe(brand("EvidenceQueryText")),ResultLimit=Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(100)).pipe(brand("EvidenceResultLimit")),EvidenceQuery=Union2([Struct({kind:Literal2("search"),text:QueryText,limit:ResultLimit,side:optional2(Literals(["before","after"]))}),Struct({kind:Literal2("related"),occurrenceId:OccurrenceId,limit:ResultLimit})]),side=Literals(["before","after"]),EvidenceHit=Union2([Struct({kind:Literal2("declaration"),entityId:EntityId,name:String4,side,source:SourceSelection,reason:String4}),Struct({kind:Literal2("reference-candidate"),side,source:SourceSelection,matchedTerms:ArraySchema(String4),reason:String4})]),EvidenceTarget=Union2([Struct({kind:Literal2("indexed-file"),path:RepoPath}),Struct({kind:Literal2("unresolved"),name:String4}),Struct({kind:Literal2("route"),name:String4})]),EvidenceRelationship=Struct({kind:Literals(["import","test-pair","route","reference-candidate"]),basis:Literals(["syntax","lexical","convention"]),side,source:SourceSelection,target:EvidenceTarget,explanation:String4}),count=Int.check(isGreaterThanOrEqualTo2(0)),EvidenceResult=Struct({snapshotId:SnapshotId,query:EvidenceQuery,hits:ArraySchema(EvidenceHit),relationships:ArraySchema(EvidenceRelationship),coverage:Struct({scope:Literal2("changed-files"),parsedFiles:count,fallbackFiles:count,nonTextFiles:count,capped:Boolean3}),notes:ArraySchema(String4)});var PLACEHOLDER=/\{([a-z]+)\}/gu,placeholdersOf=(template)=>Array.from(template.matchAll(PLACEHOLDER),(match)=>match[1]??""),pairTemplateProblem=(template)=>{if(template.length===0)return"Write a path from the repository's root, such as src/{path}.ts.";if(template.length>256)return"Use at most 256 characters.";if(template.trim()!==template)return"Leave out spaces at either end.";if(template.startsWith("/"))return"Start from the repository's root, without a leading /.";if(/[\\\u0000-\u001f\u007f]/u.test(template))return"Use / between folders, and no control characters.";if(/[*?[\]]/u.test(template))return"Use {name} or {path} for the part both files share, not wildcards.";if(template.split("/").some((part)=>part===""||part==="."||part===".."))return"Name each folder: no empty, . or .. parts.";if(/[{}]/u.test(template.replace(PLACEHOLDER,"")))return"Write a placeholder as a lowercase word in braces, such as {name} or {path}.";let names=placeholdersOf(template);if(names.length===0)return"Use {name} or {path} for the part both files share.";if(new Set(names).size!==names.length)return"Use each placeholder once.";if(template.includes("}{"))return"Put some text between two placeholders.";return null},pairRuleProblem=(source,test)=>{let problem=pairTemplateProblem(source)??pairTemplateProblem(test);if(problem!==null)return problem;if(source===test)return"The file and its test need different paths.";let left=[...placeholdersOf(source)].sort().join(","),right=[...placeholdersOf(test)].sort().join(",");return left===right?null:"Use the same placeholders in both paths, so each file names the other."},TestPairRuleId=String4.check(isPattern2(/^[a-z][a-z0-9._-]{0,63}$/u)).pipe(brand("TestPairRuleId")),PairTemplate=String4.check(makeFilter2((template)=>pairTemplateProblem(template)===null)).pipe(brand("PairTemplate")),TestPairRule=Struct({id:TestPairRuleId,name:String4.check(isMinLength(1),isMaxLength(256)),source:PairTemplate,test:PairTemplate}).check(makeFilter2((rule)=>pairRuleProblem(rule.source,rule.test)===null));var JS_TEST_FOLDERS=["test","tests","__tests__","spec"],JS_HELPER_FOLDERS=new Set([...JS_TEST_FOLDERS,"__mocks__","__fixtures__","fixtures","node_modules"]);var CertainTestPair=Struct({path:RepoPath,kind:Literals(["test","source"]),target:RepoPath});var key=String4.check(isPattern2(/^[a-z][a-z0-9._-]{0,63}$/)),label=String4.check(isMinLength(1),isMaxLength(256)),ProfileId=key.pipe(brand("ProfileId")),ProfileRuleId=key.pipe(brand("ProfileRuleId")),ComponentId=key.pipe(brand("ComponentId")),FeatureName=String4.check(isMinLength(1),isMaxLength(4096)).pipe(brand("FeatureName")),Framework=Literals(["rails","next","expo","node"]),PathPattern=String4.check(isMinLength(1),isMaxLength(256),makeFilter2((pattern)=>!pattern.startsWith("/")&&!/[\\[\]{}()!\u0000-\u001f\u007f]/u.test(pattern)&&pattern.split("/").every((part)=>part!==""&&part!=="."&&part!==".."&&(!part.includes("**")||part==="**")))).pipe(brand("PathPattern")),matcher=Struct({include:ArraySchema(PathPattern).check(isMinLength(1),isMaxLength(100)),exclude:ArraySchema(PathPattern).check(isMaxLength(100))}),origin=Union2([Struct({kind:Literal2("human"),note:label}),Struct({kind:Literal2("agent-proposal"),note:label}),Struct({kind:Literal2("accepted-agent"),note:label})]),dependency=Struct({path:RepoPath,contentFingerprint:Fingerprint}),ruleFields={id:ProfileRuleId,name:label,priority:Int.check(isGreaterThanOrEqualTo2(-1000),isLessThanOrEqualTo2(1000)),match:matcher,origin,dependencies:ArraySchema(dependency).check(isMaxLength(100))},ProfileRule=Union2([Struct({...ruleFields,kind:Literal2("role"),role:FileRole}),Struct({...ruleFields,kind:Literal2("feature"),feature:FeatureName}),Struct({...ruleFields,kind:Literal2("component"),componentId:ComponentId})]),ProjectComponent=Struct({id:ComponentId,label,description:String4.check(isMaxLength(2000))}),BoundaryPolicy=Struct({from:ComponentId,to:ComponentId,policy:Literals(["allow","forbid"]),reason:label}),profileFields={id:ProfileId,name:label,frameworks:ArraySchema(Framework),components:ArraySchema(ProjectComponent).check(isMaxLength(100)),rules:ArraySchema(ProfileRule).check(isMaxLength(1000)),boundaries:ArraySchema(BoundaryPolicy).check(isMaxLength(1000)),testPairs:ArraySchema(TestPairRule).check(isMaxLength(100)).pipe(withDecodingDefaultKey(succeed5([])))},ProjectProfile=Struct(profileFields).check(makeFilter2((profile)=>{if(new Set(profile.frameworks).size!==profile.frameworks.length||new Set(profile.rules.map((rule)=>rule.id)).size!==profile.rules.length||new Set(profile.components.map((component)=>component.id)).size!==profile.components.length||new Set(profile.testPairs.map((rule)=>rule.id)).size!==profile.testPairs.length)return!1;if(profile.components.some((component)=>frameworkComponents(profile.frameworks).some((preset)=>preset.id===component.id)))return!1;let ids=new Set([...profile.components.map((component)=>String(component.id)),...frameworkComponents(profile.frameworks).map((component)=>String(component.id))]);return profile.rules.every((rule)=>rule.kind!=="component"||ids.has(rule.componentId))&&profile.boundaries.every((boundary)=>ids.has(boundary.from)&&ids.has(boundary.to))&&new Set(profile.boundaries.map((boundary)=>`${boundary.from}:${boundary.to}`)).size===profile.boundaries.length})),RuleEvaluation=Struct({ruleId:ProfileRuleId,state:Literals(["active","proposed","stale","unverified"]),explanation:String4}),InferredFeatureRef=Struct({feature:FeatureName,label:String4.check(isMinLength(1))}),ProfileFile=Struct({fileId:FileId,path:RepoPath,role:FileRole,feature:FeatureName,inferred:ArraySchema(InferredFeatureRef),components:ArraySchema(ComponentId),appliedRuleIds:ArraySchema(ProfileRuleId),conflicts:ArraySchema(String4),explanation:ArraySchema(String4)}),BoundaryObservation=Struct({from:ComponentId,to:ComponentId,declaredPolicy:Literals(["allow","forbid","unspecified"]),relationship:EvidenceRelationship,explanation:String4}),ProfileProjection=Struct({snapshotId:SnapshotId,profileFingerprint:Fingerprint,profile:ProjectProfile,files:ArraySchema(ProfileFile),components:ArraySchema(ProjectComponent),ruleEvaluations:ArraySchema(RuleEvaluation),boundaryObservations:ArraySchema(BoundaryObservation),notes:ArraySchema(String4)}),component=(id,title)=>decodeUnknownSync(ProjectComponent)({id,label:title,description:"Framework path convention; membership does not establish runtime behavior."}),frameworkRules=[...["models","controllers","services","jobs","policies","serializers","views"].map((name)=>({framework:"rails",patterns:[`**/app/${name}/**`],role:"business",component:component(`rails-${name}`,`Rails ${name}`)})),{framework:"rails",patterns:["**/db/migrate/**"],role:"infrastructure",component:component("rails-migrations","Rails migrations")},{framework:"rails",patterns:["**/config/routes.rb"],role:"business",component:component("rails-routes","Rails routes")},{framework:"next",patterns:["**/app/**/page.tsx","**/app/**/page.jsx","**/app/**/route.ts","**/app/**/route.js","**/pages/**"],role:"business",component:component("next-routes","Next.js route entries")},{framework:"next",patterns:["**/server/**","**/*.server.ts","**/*.server.tsx"],role:"business",component:component("next-server","Next.js server convention")},{framework:"next",patterns:["**/components/**","**/*.client.tsx"],role:"business",component:component("next-ui","Next.js UI convention")},{framework:"expo",patterns:["**/app/**/*.tsx","**/app/**/*.jsx"],role:"business",component:component("expo-routes","Expo Router entries")},{framework:"expo",patterns:["**/*.native.ts","**/*.native.tsx","**/*.ios.tsx","**/*.android.tsx"],role:"business",component:component("expo-platform","Expo platform code")},{framework:"node",patterns:["**/server/**","**/routes/**"],role:"business",component:component("node-server","Node.js server convention")}];function frameworkComponents(frameworks){return frameworkRules.filter((rule)=>frameworks.includes(rule.framework)).map((rule)=>rule.component)}var ProfileSuggestion=Struct({profile:ProjectProfile,evidence:ArraySchema(Struct({framework:Framework,path:RepoPath,reason:String4})),notes:ArraySchema(String4)});var RepositoryIndexId=String4.check(isPattern2(/^index_[a-f0-9]{64}$/)).pipe(brand("RepositoryIndexId")),count2=Int.check(isGreaterThanOrEqualTo2(0)),INDEX_POLICY_LIMITS={maxFiles:20000,maxFileBytes:2097152,maxTotalBytes:67108864},RepositoryIndexPolicy=Struct({maxFiles:Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxFiles)),maxFileBytes:ByteLength.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxFileBytes)),maxLocaleFileBytes:ByteLength.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxFileBytes)),maxTotalBytes:ByteLength.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxTotalBytes)),include:ArraySchema(PathPattern),exclude:ArraySchema(PathPattern)}),DEFAULT_INDEX_POLICY=decodeUnknownSync(RepositoryIndexPolicy)({maxFiles:1e4,maxFileBytes:262144,maxLocaleFileBytes:1048576,maxTotalBytes:33554432,include:[],exclude:["**/node_modules/**","**/vendor/**","**/dist/**","**/build/**","**/.next/**","**/coverage/**","**/*.min.js","**/*.lock","**/package-lock.json"]}),maxFileBytesFor=(policy,path)=>isLocalePath(path)?Math.max(policy.maxFileBytes,policy.maxLocaleFileBytes):policy.maxFileBytes;var GitBlobId=String4.check(isPattern2(/^[a-f0-9]{40}$/)).pipe(brand("GitBlobId")),IndexedSource=Struct({id:FileId,path:RepoPath,blob:GitBlobId,text:String4,contentFingerprint:Fingerprint,language:Language,role:FileRole,coverage:Coverage}),IndexedDeclaration=Struct({id:EntityId,fileId:FileId,name:String4,kind:String4,source:SourceSelection,fingerprint:Fingerprint}),IndexOmission=Struct({reason:IndexOmissionReason,count:count2,examples:ArraySchema(RepoPath).check(isMaxLength(10))}),RepositoryIndex=Struct({id:RepositoryIndexId,repositoryId:RepositoryId,revision:GitRevision,analyzerRevision:AnalyzerRevision,policy:RepositoryIndexPolicy,files:ArraySchema(IndexedSource),declarations:ArraySchema(IndexedDeclaration),omissions:ArraySchema(IndexOmission),coverage:Struct({treeFiles:count2,indexedFiles:count2,indexedBytes:ByteLength,parsedFiles:count2,fallbackFiles:count2,omittedFiles:count2})}),RepositoryOutline=Struct({indexId:RepositoryIndexId,repositoryId:RepositoryId,revision:GitRevision,files:ArraySchema(Struct({path:RepoPath,role:FileRole,contentFingerprint:Fingerprint})),manifests:ArraySchema(Struct({path:RepoPath,text:String4}))}),RepositoryIndexInput=Struct({repositoryId:RepositoryId,revision:GitRevision,policy:RepositoryIndexPolicy,treeFiles:count2,files:ArraySchema(Struct({path:RepoPath,text:String4,bytes:ByteLength})),omissions:ArraySchema(Struct({path:RepoPath,reason:IndexOmission.fields.reason}))}).check(makeFilter2((input)=>{if(input.files.length>input.policy.maxFiles||input.files.length+input.omissions.length!==input.treeFiles)return!1;let paths=[...input.files.map((file)=>file.path),...input.omissions.map((file)=>file.path)];if(new Set(paths).size!==paths.length)return!1;if(input.files.reduce((sum,file)=>sum+file.text.length,0)>input.policy.maxTotalBytes||input.files.reduce((sum,file)=>sum+file.bytes,0)>input.policy.maxTotalBytes)return!1;return input.files.every((file)=>file.bytes<=maxFileBytesFor(input.policy,file.path)&&file.text.length<=maxFileBytesFor(input.policy,file.path)&&!/[\uD800-\uDFFF]/u.test(file.text)&&new TextEncoder().encode(file.text).length===file.bytes)}));var RepositoryEvidenceQuery=Struct({text:String4.check(isMinLength(1),isMaxLength(1000),makeFilter2((text)=>text.trim().length>0)),limit:Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(100))}),RepositoryEvidenceResult=Struct({indexId:RepositoryIndexId,revision:GitRevision,query:RepositoryEvidenceQuery,hits:ArraySchema(EvidenceHit),relationships:ArraySchema(EvidenceRelationship),coverage:Struct({scope:Literal2("repository"),indexedFiles:Int,omittedFiles:Int,capped:Boolean3}),notes:ArraySchema(String4)});var count3=Int.check(isGreaterThanOrEqualTo2(0)),RepositorySummary=Struct({indexId:RepositoryIndexId,revision:GitRevision,languages:ArraySchema(Struct({language:Language,fileCount:count3})),roles:ArraySchema(Struct({role:FileRole,fileCount:count3})),declarationCount:count3,declarationExamples:ArraySchema(IndexedDeclaration).check(isMaxLength(20)),omissions:ArraySchema(IndexOmission),notes:ArraySchema(String4),localeFiles:optional2(count3),localeRoots:optional2(ArraySchema(LocaleRoot))});var GitHubViewedReason=Literals(["not-connected","needs-sign-in","earlier-head","app-permission","no-permission","pull-gone","unavailable"]),GitHubViewedSync=Union2([Struct({kind:Literal2("synced"),version:Version}),Struct({kind:Literal2("not-synced"),reason:GitHubViewedReason,message:NonEmptyString})]),GitHubViewedResponse=Struct({snapshotId:SnapshotId,sync:GitHubViewedSync});var GitHubReviewEvent=Literals(["COMMENT","APPROVE","REQUEST_CHANGES"]),ReviewSummaryBody=String4.check(isMaxLength(60000)),ReviewDraftSelection=Struct({commentId:CommentId,expectedVersion:CommentVersion}),maxReviewDrafts=100,SubmitGitHubReview=Struct({publicationId:PublicationId,expectedSnapshotId:SnapshotId,event:GitHubReviewEvent,body:ReviewSummaryBody,drafts:optional2(ArraySchema(ReviewDraftSelection).check(isMaxLength(maxReviewDrafts)))}).check(makeFilter2((value)=>value.event==="APPROVE"||value.body.trim().length>0||value.event==="COMMENT"&&(value.drafts?.length??0)>0),makeFilter2((value)=>new Set((value.drafts??[]).map((draft)=>draft.commentId)).size===(value.drafts??[]).length)),shared={publicationId:PublicationId,reviewerId:ReviewerId,event:GitHubReviewEvent,body:ReviewSummaryBody,createdAt:Timestamp,commentIds:optional2(ArraySchema(CommentId))},GitHubReviewSubmission=Union2([Struct({...shared,kind:Literal2("publishing")}),Struct({...shared,kind:Literal2("uncertain"),reason:NonEmptyString}),Struct({...shared,kind:Literal2("rejected"),reason:NonEmptyString}),Struct({...shared,kind:Literal2("published"),remoteId:GitHubReviewId,url:HttpsUrl}),Struct({...shared,kind:Literal2("abandoned"),reason:NonEmptyString,abandonedAt:Timestamp})]),GitHubReviewSubmissions=ArraySchema(GitHubReviewSubmission),PublishedReviewComment=Struct({commentId:CommentId,remoteId:GitHubCommentId,url:HttpsUrl}),GitHubReviewOutcome=Union2([Struct({kind:Literal2("confirmed"),remoteId:GitHubReviewId,url:HttpsUrl,comments:optional2(ArraySchema(PublishedReviewComment))}),Struct({kind:Literal2("uncertain"),reason:NonEmptyString}),Struct({kind:Literal2("confirmed-not-published")})]),AbandonGitHubReview=Struct({publicationId:PublicationId,expectedSnapshotId:SnapshotId}),AbandonPublication=Struct({commentId:CommentId,publicationId:PublicationId,expectedSnapshotId:SnapshotId});var ReviewRefusal=Union2([Struct({kind:Literal2("review-not-found")}),Struct({kind:Literal2("wrong-reviewer")}),Struct({kind:Literal2("command-id-reused")}),Struct({kind:Literal2("comment-id-taken")}),Struct({kind:Literal2("comment-not-found")}),Struct({kind:Literal2("proposal-not-found")}),Struct({kind:Literal2("finding-not-found")}),Struct({kind:Literal2("finding-settled"),state:Literals(["open","drafted","dismissed"])}),Struct({kind:Literal2("too-many-findings"),limit:Int}),Struct({kind:Literal2("wrong-snapshot")}),Struct({kind:Literal2("comment-rule"),error:CommentError}),Struct({kind:Literal2("submission-unsupported")}),Struct({kind:Literal2("publication-id-taken")}),Struct({kind:Literal2("unresolved-submission")}),Struct({kind:Literal2("selected-draft"),problem:Literals(["missing","publishing","not-a-line-comment","changed"])}),Struct({kind:Literal2("still-publishing"),subject:Literals(["submission","comment"])}),Struct({kind:Literal2("submission-not-abandonable")}),Struct({kind:Literal2("submission-not-found")}),Struct({kind:Literal2("comment-in-submission")}),Struct({kind:Literal2("inconsistent"),detail:String4})]);var COMPANION_DEFAULT_ORIGIN="https://diffclarity.com",companionCommand=(verb,origin)=>`npx @diffclarity/companion@latest ${verb}${origin===COMPANION_DEFAULT_ORIGIN?"":` --origin ${origin}`}`,COMPANION_CLIENT_NAME="DiffClarity companion",companionClientName=(machine)=>{let name=machine.trim().replace(/\.local$/u,"").replace(/[^\w .'-]/gu,"").slice(0,60).trim();return name.length===0?COMPANION_CLIENT_NAME:`${COMPANION_CLIENT_NAME} on ${name}`},GRANT_WORKSPACE_FIELD="diffclarity_workspace";var CompanionAgentKind=Literals(["claude","codex","opencode"]),COMPANION_AGENT_LABELS={claude:"Claude Code",codex:"Codex",opencode:"opencode"},ShortText=String4.check(isMaxLength(120)),AgentModelId=String4.check(isPattern2(/^[A-Za-z0-9][A-Za-z0-9._/:@+-]{0,159}$/)).pipe(brand("AgentModelId")),AgentEffort=String4.check(isPattern2(/^[a-z][a-z0-9-]{0,31}$/)).pipe(brand("AgentEffort")),Efforts=ArraySchema(AgentEffort).check(isMaxLength(12)),AgentModel=Struct({id:AgentModelId,label:ShortText,efforts:Efforts}),CompanionAgent=Struct({kind:CompanionAgentKind,version:ShortText,models:ArraySchema(AgentModel).check(isMaxLength(1000)),efforts:Efforts}),KeyProvider=Literals(["anthropic","openai"]);var AssistantAgentKind=Literals([...CompanionAgentKind.literals,...KeyProvider.literals]),ASSISTANT_AGENT_LABELS={...COMPANION_AGENT_LABELS,anthropic:"Claude API",openai:"OpenAI API"};var AssistantAgent=Struct({kind:AssistantAgentKind,version:ShortText,models:ArraySchema(AgentModel).check(isMaxLength(1000)),efforts:Efforts}),effortsFor=(agent,model)=>model===void 0?agent.efforts:agent.models.find((candidate)=>candidate.id===model)?.efforts??[],isOffered=(agent,model,effort)=>(model===void 0||agent.models.some((candidate)=>candidate.id===model))&&(effort===void 0||effortsFor(agent,model).includes(effort)),efforts=(...names)=>names.map((name)=>decodeUnknownSync(AgentEffort)(name)),keyModel=(id,label,effortNames)=>({id:decodeUnknownSync(AgentModelId)(id),label,efforts:efforts(...effortNames)}),ALL_EFFORTS=["low","medium","high","xhigh","max"],KEY_AGENTS={anthropic:{defaultModel:decodeUnknownSync(AgentModelId)("claude-opus-5-5"),defaultEffort:decodeUnknownSync(AgentEffort)("high"),models:[keyModel("claude-opus-5-5","Claude Opus 5.5",ALL_EFFORTS),keyModel("claude-sonnet-5-5","Claude Sonnet 5.5",ALL_EFFORTS),keyModel("claude-haiku-5-5","Claude Haiku 5.5",ALL_EFFORTS),keyModel("claude-fable-5-1","Claude Fable 5.1",ALL_EFFORTS)]},openai:{defaultModel:decodeUnknownSync(AgentModelId)("gpt-6-astra"),defaultEffort:decodeUnknownSync(AgentEffort)("high"),models:[keyModel("gpt-6-astra","GPT-6 Astra",ALL_EFFORTS),keyModel("gpt-6.1-sol","GPT-6.1 Sol",ALL_EFFORTS),keyModel("gpt-6.1-terra","GPT-6.1 Terra",ALL_EFFORTS),keyModel("gpt-6-luna","GPT-6 Luna",ALL_EFFORTS)]}};var CompanionHello=Struct({version:ShortText,agents:ArraySchema(CompanionAgent).check(isMaxLength(3))}),CompanionWorkspace=Struct({id:OrganizationId,name:NonEmptyString.check(isMaxLength(200)),personal:Boolean3}),CompanionElsewhere=Struct({workspace:CompanionWorkspace,agents:ArraySchema(CompanionAgent)}),CompanionStatus=Union2([Struct({kind:Literal2("connected"),agents:ArraySchema(CompanionAgent),connectedAt:Timestamp}),Struct({kind:Literal2("not-connected"),elsewhere:optional2(ArraySchema(CompanionElsewhere).check(isMaxLength(3)))})]),AgentSessionId=String4.check(isPattern2(/^[A-Za-z0-9._:-]{1,128}$/)).pipe(brand("AgentSessionId")),CompanionRunId=String4.check(isPattern2(/^run_[a-f0-9]{32}$/)).pipe(brand("CompanionRunId")),MAX_ASSISTANT_QUESTION=8000,AssistantQuestion=String4.check(isMinLength(1),isMaxLength(MAX_ASSISTANT_QUESTION)),AskedLines=Struct({startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((lines)=>lines.endLine>=lines.startLine)),AskedEdit=Struct({occurrenceId:OccurrenceId,base:optional2(AskedLines),head:optional2(AskedLines)}),MAX_ASKED_EDITS=100,AskedFile=Struct({path:RepoPath,fileId:FileId,editCount:Int.check(isGreaterThanOrEqualTo2(0)),edits:ArraySchema(AskedEdit).check(isMaxLength(MAX_ASKED_EDITS))}),MAX_MENTIONED_FILES=5,MAX_ASKED_EXACT_EDITS=200;var MAX_ASKED_EDIT_TEXT=1200,AskedEditText=Struct({text:String4.check(isMaxLength(MAX_ASKED_EDIT_TEXT)),isCut:Boolean3}),AskedExactEdit=Struct({...AskedEdit.fields,path:RepoPath,fileId:FileId,label:String4.check(isMaxLength(120)),before:optional2(AskedEditText),after:optional2(AskedEditText)}),AskSubject=Union2([Struct({kind:Literal2("edits"),label:String4.check(isMaxLength(256)),edits:ArraySchema(AskedExactEdit).check(isMinLength(1),isMaxLength(MAX_ASKED_EXACT_EDITS))}),Struct({kind:Literal2("selection"),path:RepoPath,side:Literals(["base","head"]),startLine:LineNumber,endLine:LineNumber,text:String4.check(isMinLength(1),isMaxLength(4000))}),Struct({kind:Literal2("file"),...AskedFile.fields})]),QuestionFields={model:optional2(AgentModelId),effort:optional2(AgentEffort),question:AssistantQuestion,subject:optional2(AskSubject),mentions:optional2(ArraySchema(AskedFile).check(isMaxLength(MAX_MENTIONED_FILES)))},CompanionQuestion=Struct({agent:CompanionAgentKind,...QuestionFields,resumeId:optional2(AgentSessionId)}),MAX_KEY_HISTORY=6,MAX_KEY_HISTORY_ANSWER=8000,AssistantHistoryTurn=Struct({question:AssistantQuestion,answer:String4.check(isMaxLength(MAX_KEY_HISTORY_ANSWER))}),KeyQuestion=Struct({agent:KeyProvider,...QuestionFields,history:optional2(ArraySchema(AssistantHistoryTurn).check(isMaxLength(MAX_KEY_HISTORY)))}),AssistantRequest=Union2([CompanionQuestion,KeyQuestion]),CompanionRun=Struct({runId:CompanionRunId,snapshotId:SnapshotId,agent:CompanionAgentKind,model:optional2(AgentModelId),effort:optional2(AgentEffort),prompt:String4.check(isMaxLength(32000)),resumeId:optional2(AgentSessionId)}),ReviewProposal=Struct({occurrenceIds:ArraySchema(OccurrenceId).check(isMinLength(1),isMaxLength(500)),reason:String4.check(isMinLength(1),isMaxLength(2000))}),ProposeReviewRequest=Struct({runId:CompanionRunId,...ReviewProposal.fields}),ProposeCommentEditRequest=Struct({commandId:CommandId,commentId:CommentId,baseVersion:CommentVersion,body:CommentBody,reason:optional2(ProposalReason),runId:optional2(CompanionRunId)}),CommentEditProposed=Struct({status:Literal2("awaiting-reviewer-approval"),proposalId:CommandId,commentId:CommentId,isInConversation:Boolean3,message:String4}),ReportFindingsRequest=Struct({commandId:CommandId,findings:FindingInputs,runId:optional2(CompanionRunId)}),FindingsReported=Struct({status:Literal2("awaiting-reviewer"),reportId:CommandId,findingIds:ArraySchema(FindingId),isInConversation:Boolean3,message:String4}),ReviewProposalEvent=Struct({kind:Literal2("proposal"),...ReviewProposal.fields}),CommentEditEvent=Struct({kind:Literal2("comment-edit"),proposalId:CommandId,commentId:CommentId}),FindingsEvent=Struct({kind:Literal2("findings"),reportId:CommandId,findingIds:ArraySchema(FindingId).check(isMaxLength(50))}),RunProposal=Union2([ReviewProposalEvent,CommentEditEvent,FindingsEvent]),AssistantEvent=Union2([Struct({kind:Literal2("session"),sessionId:AgentSessionId}),Struct({kind:Literal2("text"),text:String4}),Struct({kind:Literal2("tool"),name:String4.check(isMaxLength(200))}),Struct({kind:Literal2("answer"),text:String4}),ReviewProposalEvent,CommentEditEvent,FindingsEvent,Struct({kind:Literal2("failed"),message:NonEmptyString})]),AssistantStreamLine=Union2([Struct({kind:Literal2("started"),runId:CompanionRunId}),...AssistantEvent.members]),StopAssistantRequest=Struct({runId:CompanionRunId}),StopAssistantResponse=Struct({stopped:Boolean3}),CompanionReport=Struct({events:ArraySchema(AssistantEvent).check(isMaxLength(500)),isDone:Boolean3});var KeyHint=String4.check(isPattern2(/^[A-Za-z0-9_-]{4}$/)).pipe(brand("KeyHint")),SavedAssistantKey=Struct({provider:KeyProvider,hint:KeyHint,savedAt:Timestamp}),AssistantKeys=Union2([Struct({kind:Literal2("available"),keys:ArraySchema(SavedAssistantKey).check(isMaxLength(KeyProvider.literals.length))}),Struct({kind:Literal2("unavailable")})]);var ImportJobKey=String4.check(isPattern2(/^(?:sample(?::(?:media|folding|mechanical|routes|dependencies|translations|rails))?|pull:(?:github:[1-9][0-9]{0,15}|local:[a-z0-9][a-z0-9._-]{0,127}):[1-9][0-9]{0,15}|reanalysis:[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255})$/)).pipe(brand("ImportJobKey"));var SampleName=Literals(["media","folding","mechanical","routes","dependencies","translations","rails"]);var Count5=Int.check(isGreaterThanOrEqualTo2(0)),Message=String4,ImportFailure=Union2([Struct({reason:Literal2("sign-in-needed"),message:Message}),Struct({reason:Literal2("access-denied"),message:Message}),Struct({reason:Literal2("not-found"),message:Message}),Struct({reason:Literal2("rate-limited"),message:Message}),Struct({reason:Literal2("github-unavailable"),message:Message}),Struct({reason:Literal2("too-many-files"),message:Message,changedFiles:Count5,limit:Count5}),Struct({reason:Literal2("file-too-large"),message:Message,path:RepoPath,bytes:Count5,limit:Count5}),Struct({reason:Literal2("over-budget"),message:Message,bytes:Count5,limit:Count5}),Struct({reason:Literal2("listing-incomplete"),message:Message,listed:Count5,expected:Count5}),Struct({reason:Literal2("other-repository"),message:Message}),Struct({reason:Literal2("analysis-failed"),message:Message}),Struct({reason:Literal2("stalled"),message:Message}),Struct({reason:Literal2("expired"),message:Message}),Struct({reason:Literal2("error"),message:Message})]),ImportJobPhase=Literals(["reading-pull","listing-files","reading-files","reading-contents","analyzing"]),ImportJobState=Union2([Struct({kind:Literal2("running"),phase:ImportJobPhase,done:Count5,total:Count5,startedAt:Timestamp}),Struct({kind:Literal2("finished"),snapshotId:SnapshotId,finishedAt:Timestamp}),Struct({kind:Literal2("failed"),failure:ImportFailure,failedAt:Timestamp})]),ImportJobStatus=Struct({key:ImportJobKey,run:Count5,state:ImportJobState});var GitHubLocationMapping=Union2([Struct({kind:Literal2("mapped"),anchor:CommentAnchor.members[0],range:GitHubLineRange}),Struct({kind:Literal2("link-only"),reason:Literals(["file-level","location-unavailable","outdated","different-revision","unverified-context","base-unverified","renamed-file","file-unavailable","source-unavailable","hunk-mismatch"])})]);var RasterType=Literals(["image/png","image/jpeg","image/gif","image/webp"]);var PICTURE_FILE=/\.(?:png|jpe?g|gif|webp|svg)$/iu,UNSAFE_SEGMENT=/[\u0000-\u001f\u007f/\\]/u,MAX_FILE_SEGMENTS=64,MAX_FILE_LENGTH=1024,isRepositoryPictureFile=(segments)=>{let last=segments.at(-1);return segments.length>=2&&segments.length<=MAX_FILE_SEGMENTS&&last!==void 0&&PICTURE_FILE.test(last)&&segments.join("/").length<=MAX_FILE_LENGTH&&segments.every((segment)=>segment.length>0&&segment!=="."&&segment!==".."&&!UNSAFE_SEGMENT.test(segment))},RepositoryPictureFile=ArraySchema(String4).check(makeFilter2(isRepositoryPictureFile)).pipe(brand("RepositoryPictureFile"));var Count6=Int.check(isGreaterThanOrEqualTo2(0)),StackMemberProgress=Struct({snapshotId:SnapshotId,headRevision:GitRevision,upToDate:Boolean3,total:Count6,reviewed:Count6,revisit:Count6,pending:Count6}),ReviewStackMember=Struct({...GitHubStackMember.fields,baseRef:String4,isCurrent:Boolean3,review:NullOr(StackMemberProgress)}),ReviewStack=Union2([Struct({kind:Literal2("none")}),Struct({kind:Literal2("available"),number:GitHubStackNumber,baseRef:String4,open:Boolean3,members:ArraySchema(ReviewStackMember).check(isMinLength(1),isMaxLength(100))}),Struct({kind:Literal2("unavailable"),message:NonEmptyString})]);var count4=Int.check(isGreaterThanOrEqualTo2(0)),LeftoverSource=Struct({path:RepoPath,text:String4});var LeftoverRequest=Struct({groupId:GroupId,oldNames:ArraySchema(String4),headRevision:GitRevision,changedPaths:ArraySchema(RepoPath),changedFiles:ArraySchema(LeftoverSource),limit:optional2(Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(500)))}).check(makeFilter2((request)=>{let changed=new Set(request.changedPaths);return changed.size===request.changedPaths.length&&new Set(request.changedFiles.map((file)=>file.path)).size===request.changedFiles.length&&request.changedFiles.every((file)=>changed.has(file.path))})),LeftoverHit=Struct({path:RepoPath,line:LineNumber,name:String4,origin:Literals(["changed-file","repository-index"]),excerpt:ExampleExcerpt}),LeftoverIndexCoverage=Union2([Struct({kind:Literal2("absent")}),Struct({kind:Literal2("mismatched"),indexId:RepositoryIndexId,indexRevision:GitRevision}),Struct({kind:Literal2("searched"),indexId:RepositoryIndexId,revision:GitRevision,searchedFiles:count4,treeFiles:count4,omittedFiles:count4,omissions:ArraySchema(IndexOmission)})]),LeftoverCoverage=Struct({searchedNames:ArraySchema(String4),changedFiles:count4,index:LeftoverIndexCoverage,complete:Boolean3,capped:Boolean3,totalHits:count4,statement:String4}),LeftoverReport=Struct({groupId:GroupId,headRevision:GitRevision,hits:ArraySchema(LeftoverHit),coverage:LeftoverCoverage,notes:ArraySchema(String4)});var textOffset=decodeUnknownSync(TextOffset),lineNumber=decodeUnknownSync(LineNumber);var InstallationUrl=String4.check(isPattern2(/^https:\/\/github\.com\/apps\/[a-z0-9-]+\/installations\/new$/)),GitHubConnectionStatus=Union2([Struct({kind:Literal2("unconfigured"),message:String4}),Struct({kind:Literal2("disconnected"),installUrl:InstallationUrl}),Struct({kind:Literal2("connected"),login:NonEmptyString,installUrl:InstallationUrl}),Struct({kind:Literal2("reconnect"),login:NonEmptyString,installUrl:InstallationUrl,message:String4})]),GitHubInstallations=Struct({installations:ArraySchema(Struct({id:Number5.check(isInt(),isGreaterThan2(0)),account:NonEmptyString,repositories:Literals(["all","selected"]),canReview:Boolean3}))});var ConnectedAgentEntry=Struct({consentId:NonEmptyString,clientName:String4,referenceId:NullOr(String4),allowedAt:String4,lastUsedAt:NullOr(String4)});var McpGrant=Struct({kind:Literal2("granted"),userId:NonEmptyString,organizationId:OrganizationId,clientId:NonEmptyString,clientName:String4}),McpRefusal=Struct({kind:Literal2("refused"),reason:Literals(["invalid-token","wrong-resource","missing-scope","no-workspace","not-a-member","no-consent","unknown-client"])}),McpAccess=Union2([McpGrant,McpRefusal]);var LIVE_PING="ping",LIVE_PONG="pong";var COMPANION_SOCKET_PATH="/api/companion/socket",LiveEvent=Union2([Struct({kind:Literal2("import"),status:ImportJobStatus}),Struct({kind:Literal2("review-index"),snapshotId:SnapshotId}),Struct({kind:Literal2("project-index"),repositoryId:RepositoryId}),Struct({kind:Literal2("review-changed"),snapshotId:SnapshotId,what:Literals(["decisions","activity"]),version:Version}),Struct({kind:Literal2("companion"),status:CompanionStatus}),Struct({kind:Literal2("pull-head"),repositoryId:RepositoryId,number:PullRequestNumber,headRevision:GitRevision}),Struct({kind:Literal2("pull-checks"),repositoryId:RepositoryId,number:PullRequestNumber,headRevision:GitRevision}),Struct({kind:Literal2("pull-requests"),repositoryId:RepositoryId}),Struct({kind:Literal2("project-pull-requests")}),Struct({kind:Literal2("github-repositories")})]),PageFrame=Union2([Struct({kind:Literal2("event"),event:LiveEvent})]),CompanionFrame=Union2([Struct({kind:Literal2("hello"),hello:CompanionHello}),Struct({kind:Literal2("report"),runId:CompanionRunId,report:CompanionReport})]),HubFrame=Union2([Struct({kind:Literal2("welcome"),status:CompanionStatus,workspace:optional2(CompanionWorkspace)}),Struct({kind:Literal2("work"),run:CompanionRun}),Struct({kind:Literal2("cancel"),runId:CompanionRunId})]);var TranslationRequest=Struct({key:TranslationKey,path:RepoPath,frame:TranslationFrame,knownChanges:ArraySchema(RepoPath)}),Line=Int.check(isGreaterThanOrEqualTo2(1)),Count7=Int.check(isGreaterThanOrEqualTo2(0)),TranslationText=Struct({line:Line,value:String4}),TranslationValue=Struct({path:RepoPath,locale:String4,key:String4,head:NullOr(TranslationText),base:NullOr(TranslationText)}),ChangedLocaleFile=Struct({path:RepoPath,change:Literals(["added","modified","deleted","renamed"])}),TranslationLookup=Union2([Struct({kind:Literal2("unresolved"),requestedKey:String4,reason:String4}),Struct({kind:Literal2("looked-up"),requestedKey:String4,key:String4,scope:NullOr(String4),target:LocaleTarget,values:ArraySchema(TranslationValue),localeFiles:Count7,unread:Count7,changedLocaleFiles:ArraySchema(ChangedLocaleFile),unreadable:ArraySchema(Struct({path:RepoPath,side:Literals(["base","head"]),reason:String4})),omitted:NullOr(ArraySchema(OmittedLocaleFile)),searched:Literals(["index","changed-files"]),isCapped:Boolean3})]);var Line2=Int.check(isGreaterThanOrEqualTo2(1)),Offset=Int.check(isGreaterThanOrEqualTo2(0)),JumpPlace=Union2([Struct({kind:Literal2("at"),path:RepoPath,line:Line2,start:Offset}),Struct({kind:Literal2("usages"),path:RepoPath,line:Line2,name:String4.check(isPattern2(/^[A-Za-z_$][\w$]*[?!=]?$/u),isMaxLength(200))})]),JumpTargetKind=Literals(["controller","action","method","model","partial","template","route","test","tested","usage"]),JumpTarget=Struct({path:RepoPath,line:Line2,kind:JumpTargetKind,label:String4,note:NullOr(String4)}),JumpAnswer=Union2([Struct({kind:Literal2("found"),title:String4,certainty:Literals(["resolved","likely"]),how:String4,caveats:ArraySchema(String4),targets:ArraySchema(JumpTarget).check(isMinLength(1))}),Struct({kind:Literal2("not-found"),title:String4,reason:String4}),Struct({kind:Literal2("no-jump")})]);var JumpRequest=Struct({place:JumpPlace,side:Literals(["base","head"])}),JumpLookup=Struct({answer:JumpAnswer,side:Literals(["base","head"]),searched:Literals(["index","changed-files"])}),KnownTestPair=Struct({path:RepoPath,side:Literals(["base","head"]),kind:Literals(["test","source"]),target:RepoPath}),TestPairsLookup=Union2([Struct({kind:Literal2("known"),pairs:ArraySchema(KnownTestPair)}),Struct({kind:Literal2("index-not-ready")})]);var RubyConstantName=String4.check(isMinLength(1),isMaxLength(1024)).pipe(brand("RubyConstantName")),RubyConstantSpelling=String4.check(isPattern2(/^[A-Z][A-Za-z0-9_]*$/u),isMaxLength(256)).pipe(brand("RubyConstantSpelling")),Line3=Int.check(isGreaterThanOrEqualTo2(1)),Column=Int.check(isGreaterThanOrEqualTo2(0)),Count8=Int.check(isGreaterThanOrEqualTo2(0)),RubyPlace=Struct({path:RepoPath,line:Line3,column:Column}),AncestorsState=Literals(["complete","partial","cyclic"]),RubyDeclaration=Struct({name:RubyConstantName,kind:String4,definitions:ArraySchema(Struct({kind:String4,at:RubyPlace})),definitionCount:Count8,referenceCount:Count8,descendantCount:Count8,ancestors:NullOr(AncestorsState)}),RubyResolveAnswer=Union2([Struct({kind:Literal2("reference"),spelled:RubyConstantSpelling,at:RubyPlace,declaration:RubyDeclaration}),Struct({kind:Literal2("declared"),spelled:RubyConstantSpelling,declaration:RubyDeclaration}),Struct({kind:Literal2("unresolved"),spelled:RubyConstantSpelling,at:RubyPlace}),Struct({kind:Literal2("none")}),Struct({kind:Literal2("no-document")})]),RubyMethodSpelling=String4.check(isPattern2(/^[a-z_][A-Za-z0-9_]*[?!]?$/u),isMaxLength(256)).pipe(brand("RubyMethodSpelling")),MethodHow=Literals(["own","inherited","included","prepended","extended","concern"]),Overrider=Struct({name:RubyConstantName,at:NullOr(RubyPlace)}),MethodUnknownReason=Literals(["receiver","unresolved-receiver","top-level","unindexed-class","singleton-class-body","block-in-body"]),RubyMethodAnswer=Union2([Struct({kind:Literal2("method"),spelled:RubyMethodSpelling,at:RubyPlace,self:Literals(["class","instance"]),owner:RubyConstantName,ownerKind:String4,inBlock:Boolean3,found:NullOr(Struct({declaration:RubyDeclaration,in:RubyConstantName,how:MethodHow})),unindexed:ArraySchema(String4),tied:ArraySchema(RubyDeclaration),inBlocks:ArraySchema(RubyDeclaration),overriddenCount:Count8,overriddenIn:ArraySchema(Overrider)}),Struct({kind:Literal2("method-definition"),spelled:RubyMethodSpelling,declaration:RubyDeclaration,overrides:NullOr(RubyDeclaration),overriddenCount:Count8,overriddenIn:ArraySchema(Overrider)}),Struct({kind:Literal2("method-unknown"),spelled:RubyMethodSpelling,at:RubyPlace,reason:MethodUnknownReason}),Struct({kind:Literal2("local"),spelled:RubyMethodSpelling}),Struct({kind:Literal2("none")}),Struct({kind:Literal2("no-document")})]),NoDeclaration=Struct({kind:Literal2("no-declaration")}),RubyReferencesAnswer=Union2([Struct({kind:Literal2("references"),name:RubyConstantName,total:Count8,at:ArraySchema(RubyPlace)}),NoDeclaration]),RubyAncestorsAnswer=Union2([Struct({kind:Literal2("ancestors"),name:RubyConstantName,state:AncestorsState,ancestors:ArraySchema(Struct({name:String4,resolved:Boolean3}))}),NoDeclaration]),DescentKind=Literals(["inherits","includes","prepends","extends","indirectly"]),RubyDescendantsAnswer=Union2([Struct({kind:Literal2("descendants"),name:RubyConstantName,total:Count8,descendants:ArraySchema(Struct({name:RubyConstantName,kind:String4,how:DescentKind,at:NullOr(RubyPlace)}))}),NoDeclaration]),RubyStats=Struct({kind:Literal2("stats"),files:Count8,bytes:Count8,declarations:Count8,constantReferences:Count8,resolvedConstantReferences:Count8}),RubyQuery=Union2([Struct({kind:Literal2("resolve"),path:RepoPath,line:Line3,column:Column,spelled:RubyConstantSpelling}),Struct({kind:Literal2("method"),path:RepoPath,line:Line3,column:Column,spelled:RubyMethodSpelling}),Struct({kind:Literal2("references"),name:RubyConstantName,limit:Int.check(isBetween({minimum:1,maximum:500}))}),Struct({kind:Literal2("ancestors"),name:RubyConstantName}),Struct({kind:Literal2("descendants"),name:RubyConstantName,limit:Int.check(isBetween({minimum:1,maximum:500}))})]),RubyAnswer=Union2([RubyResolveAnswer,RubyMethodAnswer,RubyReferencesAnswer,RubyAncestorsAnswer,RubyDescendantsAnswer]);var Count9=Int.check(isGreaterThanOrEqualTo2(0)),RubyIndexFacts=Struct({revision:GitRevision,rubyFiles:Count9,rubyBytes:Count9,omittedFiles:Count9,leftOutTestFiles:Count9,declarations:Count9,constantReferences:Count9,resolvedConstantReferences:Count9,cache:Literals(["kept","built"]),buildMs:NullOr(Finite)}),RubyConstantLookup=Union2([Struct({kind:Literal2("answered"),answer:RubyAnswer,index:RubyIndexFacts}),Struct({kind:Literal2("too-large"),rubyBytes:Count9,limitBytes:Count9}),Struct({kind:Literal2("failed"),message:String4})]);var DependencyNotesRequest=Struct({target:DependencyTarget}),NotesSource=Literals(["rubygems","npm","github","osv"]),NotesFailure=Struct({source:NotesSource,reason:Literals(["not-found","refused","rate-limited","timed-out","unavailable","too-large","unreadable"]),message:String4}),NotesUrl=String4.check(isPattern2(/^https:\/\/[^\s"<>]{1,2040}$/u)),GitHubPart=String4.check(isPattern2(/^[A-Za-z0-9_.-]{1,100}$/u)),NotesRepository=Struct({owner:GitHubPart,name:GitHubPart,url:NotesUrl}),PackageNotes=Union2([Struct({kind:Literal2("found"),registryUrl:NotesUrl,repository:NullOr(NotesRepository),changelogUrl:NullOr(NotesUrl)}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),TagName=String4.check(isMinLength(1),isMaxLength(255)),MAX_RELEASE_NOTES=32000,NoneFromGitHub=Literals(["no-repository","not-on-github","no-tag","no-release"]),ReleaseNotes=Union2([Struct({kind:Literal2("found"),tag:TagName,title:NullOr(String4),url:NotesUrl,body:String4.check(isMaxLength(MAX_RELEASE_NOTES)),isCut:Boolean3,publishedAt:NullOr(String4)}),Struct({kind:Literal2("none"),reason:NoneFromGitHub}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),CompareLink=Union2([Struct({kind:Literal2("found"),url:NotesUrl,fromTag:TagName,toTag:TagName}),Struct({kind:Literal2("none"),reason:NoneFromGitHub}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),AdvisoryId=String4.check(isPattern2(/^[A-Za-z0-9._:-]{1,64}$/u)),AdvisorySeverity=Literals(["low","moderate","high","critical"]),Advisory=Struct({id:AdvisoryId,summary:NullOr(String4.check(isMaxLength(500))),aliases:ArraySchema(AdvisoryId),severity:NullOr(AdvisorySeverity),url:NotesUrl});var AdvisoryNotes=Union2([Struct({kind:Literal2("found"),fixed:ArraySchema(Advisory),remaining:ArraySchema(Advisory),introduced:ArraySchema(Advisory)}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),DependencyNotes=Struct({target:DependencyTarget,readAt:String4,package:PackageNotes,release:ReleaseNotes,compare:CompareLink,advisories:AdvisoryNotes});var Label=String4.check(isMinLength(1),isMaxLength(1024)),ReviewSource=Union2([Struct({kind:Literal2("fixture"),label:Label}),Struct({kind:Literal2("github"),reference:GitHubReference,url:HttpsUrl})]),ActivityVersion=Int.check(isGreaterThanOrEqualTo2(0)).pipe(brand("ActivityVersion")),ReviewDocument=Struct({analysis:AnalysisSnapshot,state:ReviewState,comments:ArraySchema(Comment),commentProposals:optional2(ArraySchema(CommentEditProposal)),findings:optional2(ArraySchema(Finding)),githubReviews:optional2(GitHubReviewSubmissions),activityVersion:optional2(ActivityVersion),source:ReviewSource,title:Label,createdAt:Timestamp}),SnapshotCount=Int.check(isGreaterThanOrEqualTo2(0)),ReviewSnapshot=Struct({id:SnapshotId,analyzerRevision:AnalyzerRevision,repositoryId:RepositoryId,baseRevision:GitRevision,headRevision:GitRevision,files:SnapshotCount,occurrences:SnapshotCount,catalogDigest:Fingerprint,source:ReviewSource,title:Label,createdAt:Timestamp}),ReviewActivity=Struct({comments:ArraySchema(Comment),githubReviews:GitHubReviewSubmissions,activityVersion:ActivityVersion}),ReviewOverview=Struct({snapshot:ReviewSnapshot,progress:PositionedReviewState,...ReviewActivity.fields,commentProposals:ArraySchema(CommentEditProposal),findings:ArraySchema(Finding)}),ReviewRead=Literals(["open","other"]);var GitHubReviewResponse=Union2([Struct({kind:Literal2("recorded"),...ReviewActivity.fields}),Struct({kind:Literal2("not-submitted"),message:NonEmptyString})]),Count10=Int.check(isGreaterThanOrEqualTo2(0)),ReviewStage=Literals(["in-progress","not-started","done"]),ReviewStanding=Literals(["started","commented","new-pushes","not-started","approved","changes-requested","newer-revision","closed"]);var ReviewSummary=Struct({id:SnapshotId,repositoryId:RepositoryId,title:Label,source:ReviewSource,createdAt:Timestamp,baseRevision:GitRevision,headRevision:GitRevision,files:Count10,occurrences:Count10,reviewed:Count10,pending:Count10,revisit:Count10,standing:ReviewStanding}),ReviewList=ArraySchema(ReviewSummary),ReviewCursor=Struct({stage:ReviewStage,createdAt:Timestamp,snapshotId:SnapshotId});var ReviewPage=Struct({reviews:ReviewList,next:NullOr(ReviewCursor)}),ReviewListScope=Union2([Struct({kind:Literal2("workspace")}),Struct({kind:Literal2("repository"),repositoryId:RepositoryId}),Struct({kind:Literal2("github-repository"),repository:ConnectedRepository}),Struct({kind:Literal2("pull-request"),reference:GitHubReference})]),ReviewListQuery=Struct({repository:optional2(RepositoryId),owner:optional2(GitHubOwner),name:optional2(GitHubRepository),pull:optional2(FiniteFromString.pipe(decodeTo2(PullRequestNumber))),beforeStage:optional2(ReviewStage),before:optional2(Timestamp),beforeId:optional2(SnapshotId)}),reviewListQueryKeys=new Set(Object.keys(ReviewListQuery.fields));var ImportRequest=Union2([Struct({kind:Literal2("reanalyze"),snapshotId:SnapshotId}),Struct({kind:Literal2("fixture"),sample:optional2(SampleName)}),Struct({kind:Literal2("github"),reference:GitHubReference}),Struct({kind:Literal2("public-github"),reference:GitHubReference})]);var DraftCommand=Union2([Struct({kind:Literal2("create"),commandId:CommandId,id:CommentId,reviewerId:ReviewerId,anchor:CommentAnchor,body:CommentBody}),Struct({kind:Literal2("edit"),commandId:CommandId,id:CommentId,reviewerId:ReviewerId,expectedVersion:CommentVersion,body:CommentBody}),Struct({kind:Literal2("delete"),commandId:CommandId,id:CommentId,reviewerId:ReviewerId,expectedVersion:CommentVersion})]),DraftResponse=Struct({comments:ArraySchema(Comment),activityVersion:ActivityVersion}),ProposeCommentEdit=Struct({commandId:CommandId,commentId:CommentId,reviewerId:ReviewerId,baseVersion:CommentVersion,body:CommentBody,reason:optional2(ProposalReason)}),CommentEditResolution=Union2([Struct({kind:Literal2("apply"),body:optional2(CommentBody)}),Struct({kind:Literal2("dismiss")})]),ResolveCommentEdit=Struct({commandId:CommandId,proposalId:CommandId,reviewerId:ReviewerId,resolution:CommentEditResolution}),FindingResolution=Union2([Struct({kind:Literal2("draft"),commentId:CommentId,body:optional2(CommentBody)}),Struct({kind:Literal2("dismiss")}),Struct({kind:Literal2("reopen")})]),ResolveFinding=Struct({commandId:CommandId,findingId:FindingId,reviewerId:ReviewerId,resolution:FindingResolution}),FindingsResponse=Struct({findings:ArraySchema(Finding),comments:ArraySchema(Comment),activityVersion:ActivityVersion}),CommentProposalsResponse=Struct({comments:ArraySchema(Comment),commentProposals:ArraySchema(CommentEditProposal),activityVersion:ActivityVersion}),PublishRequest=Struct({commandId:CommandId,commentId:CommentId,reviewerId:ReviewerId,publicationId:PublicationId,expectedSnapshotId:SnapshotId,expectedCommentVersion:CommentVersion}),ReadySession=Struct({kind:Literal2("ready"),reviewerId:ReviewerId,canPublish:Boolean3,organizationId:OrganizationId}),Session=Union2([ReadySession,Struct({kind:Literal2("anonymous"),signIn:Struct({github:Boolean3,password:Boolean3})})]),ReleasedReview=Struct({snapshotId:SnapshotId,state:Literals(["releasing","released"]),reason:Literals(["closed","unused"]),releasedAt:Timestamp,source:ReviewSource}),ApiError=Union2([Struct({kind:Literal2("invalid-request"),message:String4}),Struct({kind:Literal2("not-found"),message:String4}),Struct({kind:Literal2("forbidden"),message:String4}),Struct({kind:Literal2("conflict"),message:String4}),Struct({kind:Literal2("project-not-added"),message:String4,repository:ConnectedRepository}),Struct({kind:Literal2("refused"),message:String4,refusal:ReviewRefusal}),Struct({kind:Literal2("review-released"),message:String4,release:ReleasedReview}),Struct({kind:Literal2("dependency-unavailable"),message:String4}),Struct({kind:Literal2("too-large"),message:String4}),Struct({kind:Literal2("internal"),message:String4})]),ErrorResponse=Struct({error:ApiError}),ProfileVersion=Int.check(isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("ProfileVersion")),SavedProjectProfile=Struct({kind:Literal2("saved"),repositoryId:RepositoryId,version:ProfileVersion,profile:ProjectProfile,author:ReviewerId,updatedAt:Timestamp}),ProjectProfileRecord=Union2([Struct({kind:Literal2("absent"),repositoryId:RepositoryId,version:ProfileVersion}),SavedProjectProfile]),SaveProjectProfile=Struct({commandId:CommandId,expectedVersion:ProfileVersion,profile:ProjectProfile}),ReadyRepositoryIndex=Struct({kind:Literal2("ready"),repositoryId:RepositoryId,summary:RepositorySummary,coverage:RepositoryIndex.fields.coverage}),ReadyProjectIndex=Struct({...ReadyRepositoryIndex.fields,branch:NonEmptyString,builtAt:Timestamp}),ProjectIndexStatus=Union2([Struct({kind:Literal2("absent"),repositoryId:RepositoryId}),ReadyProjectIndex]),IndexFailureReason=Literals(["access-lost","parser-incomplete","stalled","expired","error"]),RepositoryIndexStatus=Union2([Struct({kind:Literal2("absent"),repositoryId:RepositoryId,revision:GitRevision}),Struct({kind:Literal2("preparing"),repositoryId:RepositoryId,revision:GitRevision,waitingFor:Literals(["project","revision"])}),Struct({kind:Literal2("failed"),repositoryId:RepositoryId,revision:GitRevision,reason:IndexFailureReason,of:Literals(["project","revision"]),message:String4}),ReadyRepositoryIndex]),ProjectStatus=Union2([Struct({kind:Literal2("not-imported")}),Struct({kind:Literal2("importing"),startedAt:Timestamp}),Struct({kind:Literal2("ready"),branch:NonEmptyString,revision:GitRevision,indexedFiles:Int.check(isGreaterThanOrEqualTo2(0)),builtAt:Timestamp}),Struct({kind:Literal2("failed"),reason:IndexFailureReason,message:String4})]),ImportProjectRequest=Struct({kind:Literals(["import","refresh"])}),SourceLineCount=Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(200)).pipe(brand("SourceLineCount")),RepositorySourceRequest=Struct({path:RepoPath,startLine:LineNumber,lineCount:SourceLineCount}),RepositorySourceExcerpt=Struct({indexId:RepositoryIndexId,revision:GitRevision,path:RepoPath,startLine:LineNumber,endLine:LineNumber,text:String4,utf8Bytes:ByteLength,truncated:Boolean3}),LeftoversRequest=Struct({groupId:GroupId,limit:optional2(Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(500)))});var AGENT_KINDS=["claude","codex","opencode"],COMMANDS={claude:"claude",codex:"codex",opencode:"opencode"},CODEX_FEATURES_OFF=["shell_tool","apps","plugins","remote_plugin","browser_use","browser_use_external","browser_use_full_cdp_access","computer_use","in_app_browser","in_app_local_automation","image_generation","memories","multi_agent","skill_search","skill_mcp_dependency_install","tool_suggest","hooks","goals","sleep_tool"],toml=(value)=>JSON.stringify(value),codexMcpConfig=(mcp)=>{let env=`{ ${Object.entries(mcp.env).map(([key,value])=>`${key} = ${toml(value)}`).join(", ")} }`;return["-c",`mcp_servers.diffclarity.command=${toml(mcp.command)}`,"-c",`mcp_servers.diffclarity.args=[${mcp.args.map(toml).join(", ")}]`,"-c",`mcp_servers.diffclarity.env=${env}`]};function agentCommand(run,directory,mcp,opencode){switch(run.agent){case"claude":return{cmd:[COMMANDS.claude,"-p","--output-format","stream-json","--verbose","--include-partial-messages","--tools","","--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{diffclarity:mcp}}),"--allowedTools","mcp__diffclarity",...run.model?["--model",run.model]:[],...run.effort?["--effort",run.effort]:[],...run.resumeId?["--resume",run.resumeId]:[]],env:{},stdin:run.prompt};case"codex":return{cmd:[COMMANDS.codex,"exec","--json","--skip-git-repo-check","--ignore-user-config","--sandbox","read-only","-C",directory,...CODEX_FEATURES_OFF.flatMap((feature)=>["--disable",feature]),"-c",'web_search="disabled"',"-c","suppress_unstable_features_warning=true",...codexMcpConfig(mcp),...run.model?["-m",run.model]:[],...run.effort?["-c",`model_reasoning_effort=${toml(run.effort)}`]:[],...run.resumeId?["resume",run.resumeId]:[],"-"],env:{},stdin:run.prompt};case"opencode":if(opencode===void 0)throw Error("opencode answers through its private server, which isn't running.");return{cmd:[COMMANDS.opencode,"run","--server",opencode.url,"--format","json",...run.model?["--model",run.model]:[],...run.resumeId?["--session",run.resumeId]:[]],env:opencode.env,stdin:run.prompt}}}var parse=(line)=>{try{return JSON.parse(line)}catch{return}},record2=(value)=>typeof value==="object"&&value!==null?Object.fromEntries(Object.entries(value)):{},text=(value)=>typeof value==="string"?value:void 0,sessionEvent=(value)=>{let decoded=decodeUnknownOption2(AgentSessionId)(value);return decoded._tag==="Some"?[{kind:"session",sessionId:decoded.value}]:[]},toolName=(name)=>name.replace(/^mcp__diffclarity__|^diffclarity[_.]/u,"").slice(0,200),failed=(message)=>({kind:"failed",message:message.length>0?message.slice(0,2000):"The agent stopped with an error."}),claudeEvents=()=>(line)=>{let event=record2(parse(line));if(event.type==="system"&&event.subtype==="init")return sessionEvent(event.session_id);if(event.type==="stream_event"){let delta=record2(record2(event.event).delta),chunk=delta.type==="text_delta"?text(delta.text):void 0;return chunk?[{kind:"text",text:chunk}]:[]}if(event.type==="assistant"){let content=record2(event.message).content;return Array.isArray(content)?content.flatMap((block)=>{let name=text(record2(block).name);return record2(block).type==="tool_use"&&name?[{kind:"tool",name:toolName(name)}]:[]}):[]}if(event.type==="result"){let result=text(event.result)??"";return event.is_error===!0?[failed(result)]:[{kind:"answer",text:result}]}return[]},codexEvents=()=>(line)=>{let event=record2(parse(line));if(event.type==="thread.started")return sessionEvent(event.thread_id);if(event.type==="item.started"||event.type==="item.completed"){let item=record2(event.item);if(event.type==="item.started"&&item.type==="mcp_tool_call")return[{kind:"tool",name:toolName(text(item.tool)??"tool")}];if(event.type==="item.started"&&item.type==="command_execution")return[{kind:"tool",name:"shell (read-only sandbox)"}];let answer=text(item.text);if(event.type==="item.completed"&&item.type==="agent_message"&&answer)return[{kind:"answer",text:answer}];return[]}if(event.type==="turn.failed"||event.type==="error")return[failed(text(record2(event.error).message)??text(event.message)??"")];return[]},opencodeEvents=()=>{let hasSession=!1,hasText=!1;return(line)=>{let event=record2(parse(line)),session=hasSession?[]:sessionEvent(event.sessionID);hasSession||=session.length>0;let part=record2(event.part);if(event.type==="text"){let chunk=text(part.text);if(!chunk)return session;let separated=hasText?`
|
|
19
|
+
at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer"||issue._tag==="Composite")return;if(issue._tag==="Encoding")return findMessage(issue.issue);let message=(issue._tag==="Filter"?issue.filter.annotations:("annotations"in issue)?issue.annotations:issue.ast.annotations)?.[issue._tag==="MissingKey"?"messageMissingKey":issue._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof message==="string")return message}function getSchemaIssue(cause){let issue;for(let reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error))return;issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){let issue=getSchemaIssue(cause);if(issue===void 0)throw Error(message,{cause});return issue}var makeGetter=(fields)=>Object.assign(Object.create(Prototype),fields);var passthrough_=makeGetter({_tag:"Passthrough"});function passthrough(){return passthrough_}function transform(f){return makeGetter({_tag:"Transform",transform:f})}function transformEffect(f){return makeGetter({_tag:"TransformEffect",transform:f})}function transformOptional(f){return makeGetter({_tag:"TransformOptional",transform:f})}function transformOptionalEffect(f){return makeGetter({_tag:"TransformOptionalEffect",transform:f})}function omit(){return transformOptional(()=>none2())}function withDefault(defaultValue){return transformOptionalEffect((o)=>{let filtered=filter(o,isNotUndefined);return isSome2(filtered)?succeed5(filtered):mapEager2(defaultValue,some2)})}function String2(){return transform(globalThis.String)}function Number3(){return transform(globalThis.Number)}function parseJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>{let output=JSON.stringify(input,options?.replacer,options?.space);if(output===void 0)throw TypeError("Value cannot be represented as JSON");return output},catch:()=>new InvalidValue({expected:"a JSON-serializable value"},input,parseOptions)}))}function encodeBase64(){return transform(encode)}function decodeBase64(){return transformEffect((input,options)=>mapErrorEager2(fromResult2(decode(input)),()=>new InvalidValue({expected:"a valid Base64 string"},input,options)))}var ContentTypeId=Symbol.for("~effect/Schema/content");function setContent(operation,content){return Object.defineProperty(operation,ContentTypeId,{value:content}),operation}var TypeId5="~effect/SchemaTransformation/Transformation",Transformation=class extends Class{[TypeId5]=TypeId5;_tag="Transformation";decode;encode;constructor(decode,encode){super();this.decode=decode,this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}};function isTransformation(u){return hasProperty(u,TypeId5)&&u[TypeId5]===TypeId5}var makeTransformation=(options)=>{if(isTransformation(options))return options;return new Transformation(options.decode,options.encode)};function transformEffect2(options){return new Transformation(transformEffect(options.decode),transformEffect(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough(),passthrough());function passthrough2(){return passthrough_2}var numberFromString=new Transformation(Number3(),String2());var urlFromString=transformEffect2({decode:(s,options)=>URL.canParse(s)?succeed5(new URL(s)):fail5(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed5(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase64(),encodeBase64());function fromJsonString(options){return new Transformation(parseJson(options??{}),setContent(stringifyJson(options),{mediaType:"application/json",preserveSchema:options?.reviver===void 0&&options?.replacer===void 0}))}function makeGuard(tag){return(ast)=>ast._tag===tag}var isDeclaration=makeGuard("Declaration");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal"),isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays"),isObjects=makeGuard("Objects");var isSuspend=makeGuard("Suspend"),Link=class{to;transformation;constructor(to,transformation){this.to=to,this.transformation=transformation}},defaultParseOptions={},Context=class{isOptional;isMutable;constructorDefault;annotations;constructor(isOptional,isMutable,constructorDefault=void 0,annotations=void 0){this.isOptional=isOptional,this.isMutable=isMutable,this.constructorDefault=constructorDefault,this.annotations=annotations}},TypeId6="~effect/Schema";class ASTNodeImpl{[TypeId6]=TypeId6;annotations;checks;encoding;context;constructor(annotations=void 0,checks=void 0,encoding=void 0,context=void 0){this.annotations=annotations,this.checks=checks,this.encoding=encoding,this.context=context}toString(){return`<${this._tag}>`}}var Declaration=class extends ASTNodeImpl{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(typeParameters,run,annotations,checks,encoding,context,encodingChecks,encodingRun){super(annotations,checks,encoding,context);this.typeParameters=typeParameters,this.run=run,this.encodingChecks=encodingChecks,this.encodingRun=encodingRun}getParser(){let run;return(input,options)=>{if(input===missing)return missingExit;run??=this.run(this.typeParameters);try{return run(input,this,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks,run,encodingRun){let tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks&&run===this.run&&encodingRun===this.encodingRun?this:new Declaration(tps,run,this.annotations,checks,void 0,this.context,encodingChecks,encodingRun)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}},Null=class extends ASTNodeImpl{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}},null_=new Null;var Undefined=class extends ASTNodeImpl{_tag="Undefined";getParser(){return fromConst(this,void 0)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}},undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null))),undefined_2=new Undefined;var Unknown=class extends ASTNodeImpl{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}},unknown=new Unknown;var Literal=class extends ASTNodeImpl{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context){super(annotations,checks,encoding,context);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal))throw Error(`A numeric literal must be finite, got ${format(literal)}`);this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function literalToString(ast){let literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}var String3=class extends ASTNodeImpl{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){let checks=this.checks;return checks&&!options.disableChecks&&collectIssues(checks,s,void 0,this,options)?void 0:s}getExpected(){return"string"}},string2=new String3,Number4=class extends ASTNodeImpl{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){if(!regexp.test(s))return;let value=globalThis.Number(s);if(options.disableChecks||!this.checks)return value;return collectIssues(this.checks,value,void 0,this,options)?void 0:value}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"effect/schema/isFinite")||hasCheck(this.checks,"effect/schema/isInt")))return this;return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.toCodecJson()===this)return replaceEncoding(this,[finiteToString]);return replaceEncoding(this,[numberToString])}getExpected(){return"number"}};function hasCheck(checks,id){return checks.some((check)=>check.annotations?.representation?.id===id||check._tag==="FilterGroup"&&hasCheck(check.checks,id))}var number2=new Number4,Boolean2=class extends ASTNodeImpl{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}},boolean=new Boolean2;var Arrays=class extends ASTNodeImpl{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.isMutable=isMutable,this.elements=elements,this.rest=rest,this.encodingChecks=encodingChecks;let hasOptional=!1;for(let i=0;i<elements.length;i++)if(isOptional(elements[i]))hasOptional=!0;else if(hasOptional)throw Error("A required element cannot follow an optional element. ts(1257)");if(hasOptional&&rest.length>1)throw Error("A required element cannot follow an optional element. ts(1257)");for(let i=1;i<rest.length;i++)if(isOptional(rest[i]))throw Error("An optional element cannot follow a rest element. ts(1266)")}getParser(compile,compileField=compile){let ast=this,elements,rest,elementLen=ast.elements.length,tailLen=Math.max(0,ast.rest.length-1);function getParser(tailThreshold,index){if(index<elementLen)return elements[index];else if(index>=tailThreshold)return rest[index-tailThreshold+1];return rest[0]}let finish=(state)=>{let{input,len,options}=state;if(ast.rest.length===0&&len>elementLen)for(let i=elementLen;i<len;i++){let unexpected=new UnexpectedKey(ast,input[i],options),issue=new Pointer([i],unexpected);if(options.errors==="all")if(state.issues)state.issues.push(issue);else state.issues=[issue];else return fail5(new Composite(ast,[issue],input,options))}if(state.issues)return fail5(new Composite(ast,state.issues,input,options));return succeed6(state.output)},parse=(input,options)=>{let len=input.length,state={ast,getParser,input,len,tailThreshold:Math.max(elementLen,len-tailLen),output:[],issues:void 0,options},end=ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen),concurrency=options.concurrency===void 0?1:resolveConcurrency(options.concurrency),eff=concurrency===1?parseArray(state,input,0,end):parseArrayConcurrent(state,input,{concurrency,end});if(!eff)return finish(state);if(effectIsExit(eff))return flatMapEager2(eff,()=>finish(state));let first=!0;return suspend2(()=>{if(!first)return parse(input,options);return first=!1,flatMap2(eff,()=>finish(state))})};return(input,options)=>{if(input===missing)return missingExit;try{if(!Array.isArray(input))return fail5(new InvalidType(ast,input,options));if(!elements)elements=ast.elements.map((ast)=>({ast,parser:compileField(ast)})),rest=ast.rest.map((ast)=>({ast,parser:compileField(ast)}));return parse(input,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks){let elements=mapOrSame(this.elements,recur),rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,void 0,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}};function stepArray(s,item,exit,i){if(exit._tag==="Failure")return wrapPropertyKeyIssue(s,s.ast,i,exit);let value=exit===sameExit?item:exit[args];if(value!==missing)s.output[i]=value;else{let p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;let issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all")if(s.issues)s.issues.push(issue);else s.issues=[issue];else return fail4(new Composite(s.ast,[issue],s.input,s.options))}}var parseArrayOptions={onItem(s,item,i){let value=i<s.len?item:missing;return s.getParser(s.tailThreshold,i).parser(value,s.options)},step:stepArray},parseArray=iterateEager()(parseArrayOptions),parseArrayConcurrent=iterateConcurrent()(parseArrayOptions),wrapPropertyKeyIssue=(s,ast,key,exit)=>{if(exit.cause.reasons.length===0)return exit;let issue=getSchemaIssue(exit.cause);if(issue===void 0)return failCause2(map3(exit.cause,(issue)=>new Composite(ast,[new Pointer([key],issue)],s.input,s.options)));let pointer=new Pointer([key],issue);if(s.options.errors==="all")if(s.issues)s.issues.push(pointer);else s.issues=[pointer];else return fail4(new Composite(ast,[pointer],s.input,s.options))},FINITE_PATTERN="[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys,symbolKeys;function go(parameter){switch(parameter._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchPart(k,options)!==void 0);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchKey(k,options)!==void 0);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>Object.prototype.propertyIsEnumerable.call(input,k)&¶meter.matchKey(k,options)!==void 0);case"Union":return[...new Set(parameter.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}var PropertySignature=class{name;type;constructor(name,type){this.name=name,this.type=type}};function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return!1}}function isIndexSignatureParameterEncodedSide(ast){let encoded=getLastEncoding(ast);switch(encoded._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return encoded.types.every(isIndexSignatureParameterEncodedSide);default:return!1}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterEncodedSide(ast)}var IndexSignature=class{parameter;type;constructor(parameter,type){if(!isIndexSignatureParameter(parameter))throw Error(`Invalid index signature parameter ${parameter._tag}`);if(this.parameter=parameter,this.type=type,isOptional(type)||type.encoding!==void 0&&isOptional(toEncoded(type)))throw Error("Cannot use `Schema.optionalKey` or `Schema.optional` with index signatures. Index signatures already allow keys to be absent; use `Schema.UndefinedOr` to allow `undefined` values.")}},Objects=class extends ASTNodeImpl{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.propertySignatures=propertySignatures,this.indexSignatures=indexSignatures,this.encodingChecks=encodingChecks}getParser(compile,compileField=compile){let ast=this,hasProperties=ast.propertySignatures.length,indexCount=ast.indexSignatures.length;if(!hasProperties&&!indexCount)return fromRefinement(ast,isNotNullish);let properties,indexes,compileMembers=()=>{if(!properties)properties=ast.propertySignatures.map((ps)=>({parser:compileField(ps.type),name:ps.name,type:ps.type})),indexes=indexCount?ast.indexSignatures.map((is)=>({is,parserKey:compile(parameterFromPropertyKey(is.parameter)),parserValue:compileField(is.type)})):void 0;return properties},makeFallback=()=>{let expectedKeys=new Set(ast.propertySignatures.map((ps)=>typeof ps.name==="number"?globalThis.String(ps.name):ps.name)),finishIndex=(s,key,k2,inputValue,exitValue)=>{if(exitValue._tag==="Failure")return wrapPropertyKeyIssue(s,ast,key,exitValue)??void_2;let value=exitValue===sameExit?inputValue:exitValue[args];if(k2!==missing&&value!==missing){if(hasProperties&&(expectedKeys.has(key)||expectedKeys.has(typeof k2==="number"?globalThis.String(k2):k2)))return void_2;assignProperty(s.out,k2,value)}return void_2},parseIndex=(s,key,index,exitKey)=>{if(!exitKey){let eff=index.parserKey(key,s.options);if(!effectIsExit(eff))return flatMap2(exit2(eff),(exit)=>parseIndex(s,key,index,exit));exitKey=eff}if(exitKey._tag==="Failure")return wrapPropertyKeyIssue(s,ast,key,exitKey)??void_2;let k2=exitKey===sameExit?key:exitKey[args],inputValue=s.input[key],result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,k2,inputValue,result):flatMap2(exit2(result),(exit)=>finishIndex(s,key,k2,inputValue,exit))},parseStringIndex=(s,key,index)=>{let inputValue=s.input[key],result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,key,inputValue,result):flatMap2(exit2(result),(exit)=>finishIndex(s,key,key,inputValue,exit))},parseIndexes=indexCount?iterateConcurrent()({onItem:(s,[key,index])=>index.is.parameter===string2?parseStringIndex(s,key,index):parseIndex(s,key,index),step:(_s,_item,exit)=>exit._tag==="Failure"?exit:void 0}):void 0;return fnUntracedEager2(function*(input,options){if(input===missing)return missing;if(!(typeof input==="object"&&input!==null&&!Array.isArray(input)))return yield*fail5(new InvalidType(ast,input,options));compileMembers();let record=input,out={},state={ast,input:record,out,issues:void 0,options},errorsAllOption=options.errors==="all",onExcessPropertyError=options.onExcessProperty==="error",concurrency=options.concurrency===void 0?1:resolveConcurrency(options.concurrency),indexKeys=indexCount&&onExcessPropertyError?ast.indexSignatures.map((index)=>getIndexSignatureKeys(record,index.parameter,options)):void 0;if(onExcessPropertyError){let coveredKeys=indexKeys?new Set(expectedKeys):expectedKeys;if(indexKeys)for(let keys of indexKeys)for(let key of keys)coveredKeys.add(key);let inputKeys=Reflect.ownKeys(record);for(let i=0;i<inputKeys.length;i++){let key=inputKeys[i];if(!coveredKeys.has(key)&&Object.prototype.propertyIsEnumerable.call(record,key)){let unexpected=new UnexpectedKey(ast,record[key],options),issue=new Pointer([key],unexpected);if(errorsAllOption){if(state.issues)state.issues.push(issue);else state.issues=[issue];continue}else return yield*fail5(new Composite(ast,[issue],input,options))}}}if(hasProperties){let eff=concurrency===1?parseProperties(state,properties):parsePropertiesConcurrent(state,properties,{concurrency});if(eff)yield*eff}if(indexCount&&concurrency===1)for(let i=0;i<indexCount;i++){let index=indexes[i],parse=index.is.parameter===string2?parseStringIndex:parseIndex,keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){let eff=parse(state,keys[j],index);if(!effectIsExit(eff))yield*eff;else if(eff._tag==="Failure")return yield*eff}}else if(parseIndexes){let keyPairs=empty2();for(let i=0;i<indexCount;i++){let index=indexes[i],keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++)keyPairs.push([keys[j],index])}let eff=parseIndexes(state,keyPairs,{concurrency});if(eff)yield*eff}if(state.issues)return yield*fail5(new Composite(ast,state.issues,input,options));return out})};if(indexCount)return makeFallback();let fallback,resume=(snapshot,index,pending)=>{let property=properties[index];return flatMap2(exit2(pending),(exit)=>{let state={...snapshot,out:{...snapshot.out}},terminal=stepProperty(state,property,exit);if(terminal)return terminal;let done=()=>succeed6(state.out),eff=parseProperties(state,properties.slice(index+1));return eff?flatMapEager2(eff,done):done()})};return(input,options)=>{if(input===missing)return missingExit;if(options.errors==="all"||options.onExcessProperty!==void 0||options.concurrency!==void 0&&resolveConcurrency(options.concurrency)!==1)return(fallback??=makeFallback())(input,options);if(!(typeof input==="object"&&input!==null&&!Array.isArray(input)))return fail5(new InvalidType(ast,input,options));let props=compileMembers(),record=input,out={},state={ast,input:record,out,issues:void 0,options};try{for(let index=0;index<props.length;index++){let property=props[index],name=property.name,hasKey=hasPropertySignature(record,name),value=hasKey?record[name]:missing,exit=property.parser(value,options);if(!effectIsExit(exit))return resume(state,index,exit);if(exit===sameExit){if(hasKey)assignProperty(out,name,value);continue}let terminal=stepProperty(state,property,exit);if(terminal)return terminal}}catch(error){return die3(error)}return succeed6(out)}}_rebuild(recur,recurParameter,checks,encodingChecks){let props=mapOrSame(this.propertySignatures,(ps)=>{let t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)}),indexes=mapOrSame(this.indexSignatures,(is)=>{let p=recurParameter(is.parameter),t=recur(is.type);return p===is.parameter&&t===is.type?is:new IndexSignature(p,t)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,void 0,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function stepProperty(s,p,exit){if(exit._tag==="Failure")return wrapPropertyKeyIssue(s,s.ast,p.name,exit);if(exit===sameExit)return;let value=exit[args];if(value!==missing){assignProperty(s.out,p.name,value);return}if(delete s.out[p.name],!isOptional(p.type)){let issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else return fail4(new Composite(s.ast,[issue],s.input,s.options))}}var parsePropertiesOptions={onItem(s,p){if(!hasPropertySignature(s.input,p.name))return p.parser(missing,s.options);let value=s.input[p.name];return assignProperty(s.out,p.name,value),p.parser(value,s.options)},step:stepProperty},parseProperties=iterateEager()(parsePropertiesOptions),parsePropertiesConcurrent=iterateConcurrent()(parsePropertiesOptions);function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>new PropertySignature(key,fields[key].ast)),[],annotations,checks)}function getAST(self){return self.ast}function tuple(elements,checks=void 0){return new Arrays(!1,elements.map((e)=>e.ast),[],void 0,checks)}function union(members,options,checks){return new Union(members.map(getAST),options,void 0,checks)}var toCandidate=memoizeIdempotent((ast)=>{while(!0){if(isSuspend(ast))return unknown;let encoding=ast.encoding;if(!encoding)return ast.recur?.(toCandidate,identity)??ast;if(encoding.some((link)=>link.transformation._tag==="Middleware"&&link.transformation.decode!==identity))return unknown;ast=encoding[encoding.length-1].to}});function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{let s=ast.annotations?.[SENTINELS_ANNOTATION_KEY];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{let type=ps.type;if(!isOptional(type)){if(isLiteral(type))return[{key:ps.name,literal:type.literal}];if(isUniqueSymbol(type))return[{key:ps.name,literal:type.symbol}]}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{if(!isOptional(e)){if(isLiteral(e))return[{key:i,literal:e.literal}];if(isUniqueSymbol(e))return[{key:i,literal:e.symbol}]}return[]});case"Union":{if(ast.types.length===0)return[];let members=ast.types.map((type)=>collectSentinels(toCandidate(type)));return members[0].filter((s)=>members.every((sentinels)=>sentinels.some((o)=>o.key===s.key&&o.literal===s.literal)))}case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap,emptyCandidates=Object.freeze([]),getRuntimeType=(input)=>input===null?"null":Array.isArray(input)?"array":typeof input,hasPropertySignature=(input,key)=>key==="__proto__"?Object.hasOwn(input,key):(key in input);function getCandidateIndex(types){let index=candidateIndexCache.get(types);if(index)return index;let bySentinel,sentinelCandidateCount=0,otherwise,literalCandidates,onlyLiterals=!0,literalOf=[];for(let i=0;i<types.length;i++){let a=types[i],encoded=toCandidate(a);if(isNever2(encoded))continue;if(isLiteral(encoded)||isUniqueSymbol(encoded)){literalCandidates??=new Map;let literal=isLiteral(encoded)?encoded.literal:encoded.symbol;literalOf[i]=literal;let arr=literalCandidates.get(literal);if(!arr)literalCandidates.set(literal,arr=[]);arr.push(i)}else onlyLiterals=!1;let sentinels=collectSentinels(encoded);if(sentinels.length){bySentinel??=new Map,sentinelCandidateCount++;for(let{key,literal}of sentinels){let entry=bySentinel.get(key);if(!entry)bySentinel.set(key,entry=[new Map,new Set]);entry[1].add(i);let indexes=entry[0].get(literal);if(!indexes)entry[0].set(literal,indexes=new Set);indexes.add(i)}}else{otherwise??={};let candidateTypes=getCandidateTypes(encoded);for(let t of candidateTypes)(otherwise[t]??=[]).push(i)}}let fallbacks={},getFallback=(type)=>fallbacks[type]??=Object.freeze(otherwise?.[type]??emptyCandidates);if(onlyLiterals&&literalCandidates)literalCandidates.forEach(Object.freeze),index=(input)=>literalCandidates.get(input)??emptyCandidates;else if(bySentinel?.size===1&&!otherwise){let[key,[byValue]]=bySentinel.entries().next().value,candidates=new Map;for(let[literal,indexes]of byValue)candidates.set(literal,Object.freeze(Array.from(indexes)));let all=Object.freeze(types.map((_,i)=>i));index=(input,isConstructor)=>{if(isObjectKeyword(input)){let value=hasPropertySignature(input,key)?input[key]:void 0;if(value!==void 0)return candidates.get(value)??emptyCandidates;if(isConstructor)return all}return emptyCandidates}}else if(bySentinel){let commonSentinel;for(let entry of bySentinel)if((!commonSentinel||entry[1][0].size>commonSentinel[1][0].size)&&entry[1][1].size===sentinelCandidateCount)commonSentinel=entry;index=(input,isConstructor)=>{let runtimeType=getRuntimeType(input);if(!isObjectKeyword(input))return getFallback(runtimeType);let selected=new Set(otherwise?.[runtimeType]),directKey;if(commonSentinel){let[key,[byValue]]=commonSentinel,hasKey=hasPropertySignature(input,key),value=hasKey?input[key]:void 0;if(hasKey&&(!isConstructor||value!==void 0)){let match=byValue.get(value);if(!match)return getFallback(runtimeType);for(let i of match)selected.add(i);directKey=key}}if(directKey===void 0)for(let[key,[byValue,all]]of bySentinel){let hasKey=hasPropertySignature(input,key),value=hasKey?input[key]:void 0;if(hasKey&&(!isConstructor||value!==void 0)){let match=byValue.get(value);if(match)for(let i of match)selected.add(i)}else if(isConstructor)for(let i of all)selected.add(i)}for(let[key,[byValue,all]]of bySentinel){if(key===directKey)continue;let hasKey=hasPropertySignature(input,key),value=hasKey?input[key]:void 0;if(hasKey&&(!isConstructor||value!==void 0)){let match=byValue.get(value);for(let i of selected)if(all.has(i)&&!match?.has(i))selected.delete(i)}}return Array.from(selected).sort((a,b)=>a-b)}}else index=(input)=>{let fallback=getFallback(getRuntimeType(input));return literalCandidates?fallback.filter((i)=>literalOf[i]===void 0||literalOf[i]===input):fallback};return candidateIndexCache.set(types,index),index}var Union=class extends ASTNodeImpl{_tag="Union";types;options;encodingChecks;constructor(types,options,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.types=types,this.options=options,this.encodingChecks=encodingChecks}getParser(compile,compileField){let ast=this,isConstructor=compileField!==void 0,parsers=[],parser=(i)=>parsers[i]??=compile(ast.types[i]),index;return(input,options)=>{if(input===missing)return missingExit;let candidates=(index??=getCandidateIndex(ast.types))(input,isConstructor);if(candidates.length===0)return fail5(new AnyOf(ast,[],input,options));if(candidates.length===1){let result=parser(candidates[0])(input,options);if(result._tag==="Success")return result;return effectIsExit(result)?failSingleUnionCandidate(ast,result.cause,input,options):catchSingleUnionCandidate(ast,result,input,options)}return parseUnionCandidates(ast,parser,candidates,input,options)}}_rebuild(recur,checks,encodingChecks){let types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.options,this.annotations,checks,void 0,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(let type of this.types){let out=type.matchPart(s,options);if(out!==void 0)return out}return}getExpected(getExpected){let expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";let types=this.types.map((type)=>{let encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{let literals=encoded.elements.filter(isLiteral);if(literals.length>0)return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`;break}case"Objects":{let literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0)return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`;break}}return getExpected(encoded)});return Array.from(new Set(types)).join(" | ")}};function failSingleUnionCandidate(ast,cause,input,options){let issue=getSchemaIssue(cause);if(!issue)return failCause2(cause);return fail4(new AnyOf(ast,[issue],input,options))}function catchSingleUnionCandidate(ast,result,input,options){return catchCause2(result,(cause)=>failSingleUnionCandidate(ast,cause,input,options))}function parseUnionCandidates(ast,parser,candidates,input,options){let state={ast,parser,input,out:void 0,successes:ast.options?.mode==="oneOf"?[]:void 0,issues:void 0,options},eff=parseUnion(state,candidates);if(!eff){if(state.out)return state.out;return fail5(new AnyOf(ast,state.issues??[],input,options))}if(effectIsExit(eff))return resumeUnion(eff,state);let first=!0;return suspend2(()=>{if(!first)return parseUnionCandidates(ast,parser,candidates,input,options);return first=!1,resumeUnion(eff,state)})}function resumeUnion(eff,state){return flatMapEager2(eff,(_)=>{if(state.out===sameExit)return succeed5(state.input);if(state.out)return state.out;return fail5(new AnyOf(state.ast,state.issues??[],state.input,state.options))})}var parseUnion=iterateEager()({onItem(s,i){return s.parser(i)(s.input,s.options)},step(s,i,exit){if(exit._tag==="Failure"){let issue=getSchemaIssue(exit.cause);if(issue===void 0)return exit;if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.successes)return s.successes.push(s.ast.types[i]),fail4(new OneOf(s.ast,s.successes,s.input,s.options));if(s.out=exit,s.successes)s.successes.push(s.ast.types[i]);else return void_2}}}),nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")]);function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}var Filter2=class extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=void 0,aborted=!1){super();this.run=run,this.annotations=annotations,this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,!0)}and(other,annotations){return new FilterGroup([this,other],annotations)}},FilterGroup=class extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=void 0){super();this.checks=checks,this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}};function makeFilter(filter,annotations,aborted=!1){return new Filter2((input,ast,options)=>normalizeFilterOutput(ast,filter(input,ast,options),input,options),annotations,aborted)}function isFinite(annotations){return makeFilter((n)=>globalThis.Number.isFinite(n),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...annotations})}var finite=appendChecks(number2,[isFinite()]),numberToJson=new Link(new Union([finite,nonFiniteLiterals]),new Transformation(Number3(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function isPattern(regExp,annotations){let copy=new globalThis.RegExp(regExp),payload={source:copy.source,flags:copy.flags};return makeFilter((s)=>(copy.lastIndex=0,copy.test(s)),{expected:`a string matching the RegExp ${payload.source}`,representation:{id:"effect/schema/isPattern",payload},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[payload]},...annotations})}var bodyOwners=new WeakMap;function copy(ast,changes){let out=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,changes);if(Reflect.ownKeys(changes).every((key)=>key==="context"||key==="encoding"))bodyOwners.set(out,getContextOwner(ast));return out}function getContextOwner(ast){let existing=bodyOwners.get(ast);if(existing!==void 0)return existing;if(ast.encoding===void 0)return ast;let owner=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,{encoding:void 0});return bodyOwners.set(ast,owner),owner}function replaceEncoding(ast,encoding){return ast.encoding===encoding?ast:copy(ast,{encoding})}function replaceContext(ast,context){if(ast.context===context)return ast;let owner=getContextOwner(ast);if(owner.context===context&&owner.encoding===ast.encoding)return owner;return copy(ast,{context})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){let last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return copy(ast,{annotations:{...ast.annotations,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks)throw Error("Cannot add checks to Suspend");if(ast.checks===checks)return ast;return copy(ast,{checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function mapLink(link,f){let to=f(link.to);return to===link.to?link:new Link(to,link.transformation)}function updateLastLink(encoding,f){let links=encoding,last=links[links.length-1],out=mapLink(last,f);return out===last?encoding:append(encoding.slice(0,encoding.length-1),out)}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function applyToSelfOrLastLinkEncodingIdempotent(f,options){function out(ast){if(ast.encoding){let last=ast.encoding[ast.encoding.length-1];return options?.stopAt?.(last)?ast:replaceEncoding(ast,updateLastLink(ast.encoding,out))}return f(ast)}return memoizeIdempotent(out)}function appendTransformation(from,transformation,to){let link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function mapOrSame(as,f){let out;for(let i=0;i<as.length;i++){let a=as[i],fa=f(a);if(out)out[i]=fa;else if(fa!==a){out=Array(as.length);for(let j=0;j<i;j++)out[j]=as[j];out[i]=fa}}return out??as}function annotateKey(ast,annotations){let context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.constructorDefault,{...ast.context.annotations,...annotations}):new Context(!1,!1,void 0,annotations);return replaceContext(ast,context)}var optionalKey=memoizeIdempotent((ast)=>{let context=ast.context?ast.context.isOptional===!1?new Context(!0,ast.context.isMutable,ast.context.constructorDefault,ast.context.annotations):ast.context:new Context(!0,!1);return optionalKeyLastLink(replaceContext(ast,context))}),optionalKeyLastLink=applyToLastLink(optionalKey),optional=memoize((ast)=>optionalKey(new Union([ast,undefined_2])));function withConstructorDefault(ast,defaultValue){let context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,defaultValue,ast.context.annotations):new Context(!1,!1,defaultValue);return replaceContext(ast,context)}function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function isOptional(ast){return ast.context?.isOptional??!1}function isStructuralCheck(check){return check.annotations?.[STRUCTURAL_ANNOTATION_KEY]===!0||check._tag==="FilterGroup"&&check.checks.every(isStructuralCheck)}function extractStructuralChecks(checks){function extract(check){if(isStructuralCheck(check))return[check];return check._tag==="FilterGroup"?check.checks.flatMap(extract):[]}let out=checks.flatMap(extract);return isArrayNonEmpty2(out)?out:void 0}function canPreserveEncodingChecks(ast){let preserve=!0;function visit(child){if(preserve=preserve&&!child.encoding&&!isSuspend(child),preserve&&"recur"in child)child.recur(visit);return child}if("recur"in ast)ast.recur(visit);return preserve}var toType=memoizeIdempotent((ast)=>{let owner=getContextOwner(ast);if(owner!==ast){let type=toType(owner);return type===owner&&ast.encoding===void 0?ast:replaceContext(type,ast.context)}let type="recur"in ast?ast.recur(toType):ast;if("encodingChecks"in type&&type.encodingChecks){let checks=canPreserveEncodingChecks(ast)?type.encodingChecks:isArrays(type)||isObjects(type)||isDeclaration(type)&&type.typeParameters.length>0?extractStructuralChecks(type.encodingChecks):void 0;return copy(type,{encodingChecks:void 0,checks:combineChecks(type.checks,checks)})}return type}),toEncoded=memoizeIdempotent((ast)=>toType(flip2(ast)));function flipEncoding(ast,encoding){let links=encoding,len=links.length,last=links[len-1],ls=[new Link(flip2(replaceEncoding(ast,void 0)),links[0].transformation.flip())];for(let i=1;i<len;i++)ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()));let to=flip2(last.to);if(to.encoding)return replaceEncoding(to,[...to.encoding,...ls]);else return replaceEncoding(to,ls)}var flip2=memoize((ast)=>{if(ast.encoding)return flipEncoding(ast,ast.encoding);let owner=getContextOwner(ast);if(owner!==ast){let flipped=flip2(owner);return flipped===owner?ast:replaceContext(flipped,ast.context)}return"flip"in ast?ast.flip(flip2):("recur"in ast)?ast.recur(flip2):ast});function fromConst(ast,value){let succeed=value===0?sameExit:succeed6(value);return(input,options)=>{if(input===missing)return missingExit;if(input===value)return succeed;return fail5(new InvalidType(ast,input,options))}}function fromRefinement(ast,refinement){return(input,options)=>{if(input===missing)return missingExit;if(refinement(input))return sameExit;return fail5(new InvalidType(ast,input,options))}}var parameterFromPropertyKey=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`),isStringNumberRegExp=new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:isStringFiniteRegExp.source}),...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]),finiteToString=new Link(finiteString,numberFromString),numberToString=new Link(new Union([finiteString,nonFiniteLiterals]),numberFromString),BIGINT_PATTERN="-?\\d+",isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\(([\\s\\S]*)\\)",isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value,issues,ast,options){for(let i=0;i<checks.length;i++){let check=checks[i];if(check._tag==="FilterGroup"){if(issues=collectIssues(check.checks,value,issues,ast,options),issues&&(options.errors!=="all"||issues[issues.length-1].filter.aborted))return issues}else{let issue=check.run(value,ast,options);if(issue){let filter=new Filter(check,issue,value,options);if(issues)issues.push(filter);else issues=[filter];if(options.errors!=="all"||check.aborted)return issues}}}return issues}function getConstructorDescriptor(ast){if(!isDeclaration(ast))return;let getDescriptor=ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];return isFunction(getDescriptor)?getDescriptor(ast.typeParameters):void 0}var flatMapTransformation=(result,current,f)=>result===sameExit?f(current):flatMapEager2(result,f);function compileTransformation(transformation){let apply=compileTransformationUnsafe(transformation);return(result,current,options)=>{try{return apply(result,current,options)}catch(error){return die3(error)}}}function compileTransformationUnsafe(transformation){if(transformation._tag==="Middleware")return(result,current,options)=>{let transformed=result===sameExit?transformation.decode(succeed6(toOption(current)),options):transformation.decode(mapEager2(result,toOption),options);return fromOptionalEffect(transformed)};let getter=transformation.decode;switch(getter._tag){case"Passthrough":return(result,current)=>result===sameExit?succeed6(current):result;case"Transform":{let transform=(value)=>value===missing?missingExit:succeed6(getter.transform(value));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformOptional":{let transform=(value)=>fromOptionExit(getter.transform(toOption(value)));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>value===missing?missingExit:getter.transform(value,options));case"TransformOptionalEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>fromOptionalEffect(getter.transform(toOption(value),options)))}}var fromOptionalEffect=(effect)=>flatMapEager2(effect,fromOptionExit),wrapEncoding=(ast,input,options,effect)=>catchCause2(effect,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new Encoding(ast,issue,input,options))));function makeConstructorParser(descriptor,compile){let transform=compileTransformation(descriptor.link.transformation),sourceParser;return(input,options)=>{if(input===missing)return missingExit;if(descriptor.isConstructed(input))return sameExit;let result=(sourceParser??=compile(descriptor.link.to))(input,options);return transform(result,input,options)}}function withDefault2(ast,parser){let defaultValue=ast.context.constructorDefault;return(input,options)=>{if(input!==missing&&input!==void 0)return parser(input,options);let result=defaultValue;if(effectIsExit(result)&&result._tag==="Success"){let local=parser(result[args],options);return local===sameExit?result:local}return flatMapEager2(wrapEncoding(ast,input,options,result),(value)=>{let local=parser(value,options);return local===sameExit?succeed6(value):local})}}function compileField(ast,compile){let parser=compile(ast);return ast.context?.constructorDefault===void 0?parser:withDefault2(ast,parser)}function compile(ast,compile,compileField,base,specialize){if(ast._tag==="Declaration")for(let parameter of ast.typeParameters)compile(parameter);let descriptor=compileField?getConstructorDescriptor(ast):void 0,parser=descriptor?makeConstructorParser(descriptor,compile):base??ast.getParser(compile,compileField),{checks,encoding:links}=ast,transformations=links?.map((link)=>compileTransformation(link.transformation)),encodingChecks=ast.encodingChecks;if(!links&&!checks&&!encodingChecks)return parser;let encodingParsers,parseChecks=(input,options)=>{let result=parser(input,options);try{if(encodingChecks&&!options.disableChecks)if(effectIsExit(result)){if(result._tag==="Success"){let output=result===sameExit?input:result[args];if(input!==missing&&output!==missing){let issues=collectIssues(encodingChecks,input,void 0,ast,options);if(issues)result=fail5(new Composite(ast,issues,input,options))}}}else result=flatMap2(result,(value)=>{if(input!==missing&&value!==missing){let issues=collectIssues(encodingChecks,input,void 0,ast,options);if(issues)return fail5(new Composite(ast,issues,input,options))}return succeed5(value)});if(checks&&!options.disableChecks)if(effectIsExit(result)){if(result._tag==="Success"){let value=result===sameExit?input:result[args];if(value===missing)return result;let issues=collectIssues(checks,value,void 0,ast,options);if(issues)result=fail5(new Composite(ast,issues,value,options))}}else result=flatMap2(result,(value)=>{if(value!==missing){let issues=collectIssues(checks,value,void 0,ast,options);if(issues)return fail5(new Composite(ast,issues,value,options))}return succeed5(value)});return result}catch(error){return die3(error)}},parseLocal=specialize===void 0?parseChecks:specialize(parseChecks);if(!links)return parseLocal;return(input,options)=>{let parsers=encodingParsers??=links.map((link)=>compile(link.to)),current=input,result=parsers[parsers.length-1](input,options);for(let i=links.length-1;i>=0;i--)if(result=transformations[i](result,current,options),i!==0){let next=parsers[i-1];if(result._tag==="Success")current=result[args],result=next(current,options);else result=flatMapEager2(result,(value)=>{let nextResult=next(value,options);return nextResult===sameExit?succeed6(value):nextResult})}if(result._tag==="Success"){let value=result[args],local=parseLocal(value,options);return local===sameExit?result:local}return result=wrapEncoding(ast,input,options,result),flatMapEager2(result,(value)=>{let local=parseLocal(value,options);return local===sameExit?succeed6(value):local})}}var invalid=Symbol(),cache=new WeakMap,compiler,compilerAdaptersEnabled=!1;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve2,ast,"parser"):resolve2(ast).parser,makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve2,ast,"makeEffect"):resolve2(ast).makeEffect,makeField=(ast)=>compileField(ast,makeChild);class InterpretedEntry{ast;constructor(ast){this.ast=ast}get decodeEffect(){return this.cachedDecodeEffect??=compile(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile(this.ast,makeChild,makeField)}}class CompilerEntry extends InterpretedEntry{compiled;resolve;constructor(ast,compiled,resolve){super(ast);this.compiled=compiled,this.resolve=resolve}save(key,value){return Object.defineProperty(this,key,{value}),value}operation(key){let compiled=this.compiled;return typeof compiled==="function"?compiled(this.ast,this.resolve,key):compiled?.[key]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get compiledMakeEffect(){return this.save("compiledMakeEffect",this.operation("makeEffect"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile(this.ast,(ast)=>lazyParser(this.resolve,ast,"parser")))}get parser(){let decode=this.decode;return decode===void 0?this.decodeEffect:this.save("parser",withDecode(decode,()=>this.decodeEffect))}get makeEffect(){let makeEffect=this.compiledMakeEffect;if(makeEffect!==void 0)return this.save("makeEffect",makeEffect);let child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile(this.ast,child,(ast)=>compileField(ast,child)))}}function withDecode(fastDecode,decodeEffect){let detailed;return(input,options)=>{if(input!==missing)try{let value=fastDecode(input,options);if(value!==invalid)return value===input?sameExit:succeed6(value)}catch(error){return die3(error)}return(detailed??=decodeEffect())(input,options)}}function lazyParser(resolve,ast,operation){let entry=resolve(ast);if(entry.compiled===void 0||Object.hasOwn(entry,operation))return entry[operation];let parser;return(input,options)=>(parser??=entry[operation])(input,options)}function resolve2(ast){let cached=cache.get(ast);if(cached!==void 0)return cached;let entry=compiler===void 0?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve2),resolve2);return cache.set(ast,entry),entry}function makeEffect(schema){let ast=schema.ast,parser;return(input,options)=>(parser??=runWithCompiler(constructorCompiler,toType(ast)))(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:!0}:{disableChecks:!0}:options?.parseOptions)}function makeOption(schema){let parser=makeEffect(schema);return(input,options)=>{let exit=runSyncExit2(parser(input,options));if(isSuccess3(exit))return some2(exit.value);return getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues"),none2()}}function make3(schema){return makeConstructorSync(toType(schema.ast))}function decodeUnknownEffect(schema,options){let parser=run(schema.ast);return options===void 0?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function decodeUnknownOption(schema,options){return asOption(decodeUnknownEffect(schema,options))}function encodeUnknownEffect(schema,options){let parser=run(flip2(schema.ast));return options===void 0?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var mergeParseOptions=(options,overrideOptions)=>overrideOptions?{...options,...overrideOptions}:options,getValue=(value)=>{if(value===missing)return fail5(new InvalidValue);return succeed5(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit)return succeed5(input);if(!effectIsExit(result))return flatMapEager2(result,getValue);return result[args]===missing?getValue(missing):result}function runWithCompiler(compiler,ast){let parser;return(input,options)=>{let result=(parser??=compiler(ast))(input,options??defaultParseOptions);if(result===sameExit)return succeed5(input);if(!effectIsExit(result))return flatMapEager2(result,getValue);return result[args]===missing?getValue(missing):result}}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function asOption(parser){let parserExit=asExit(parser);return(input,options)=>{let exit=parserExit(input,options);if(isSuccess3(exit))return some2(exit.value);return getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues"),none2()}}function runSync2(effect,message){let exit=runSyncExit2(effect);if(isSuccess3(exit))return exit.value;let issue=getSchemaIssueOrThrow(exit.cause,message);throw Error("Schema validation failed",{cause:issue})}var constructorDefectMessage="Constructor adapter can only throw schema issues";function throwConstructorDefect(error){throw Error(constructorDefectMessage,{cause:die2(error)})}function makeConstructorSync(ast){let entry;return(input,options)=>constructSync(entry??=resolve2(ast),input,options)}function constructSync(entry,input,options){let parseOptions=options?.disableChecks?options.parseOptions?{...options.parseOptions,disableChecks:!0}:{disableChecks:!0}:options?.parseOptions??defaultParseOptions,make=entry.make;if(make!==void 0&&input!==missing){let output;try{output=make(input,parseOptions)}catch(error){throwConstructorDefect(error)}if(output!==invalid&&output!==missing)return output}return runSync2(parserResult(entry.makeEffect(input,parseOptions),input),constructorDefectMessage)}var normalCompiler=(ast)=>resolve2(ast).parser,constructorCompiler=(ast)=>resolve2(ast).makeEffect;var TypeId7="~effect/Schema/Schema",RebuildOptions=Symbol(),SchemaProto={[TypeId7]:TypeId7,get make(){let value=make3(this);return Object.defineProperty(this,"make",{value,enumerable:!0}),value},get makeEffect(){let value=makeEffect(this);return Object.defineProperty(this,"makeEffect",{value,enumerable:!0}),value},get makeOption(){let value=makeOption(this);return Object.defineProperty(this,"makeOption",{value,enumerable:!0}),value},pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))},rebuild(ast){return make4(ast,this[RebuildOptions])}};function make4(ast,options){function Schema(){}let self=Object.setPrototypeOf(Schema,SchemaProto);if(options&&(Object.hasOwn(options,"name")||Object.hasOwn(options,"length")||Object.hasOwn(options,"__proto__")))Object.defineProperties(self,Object.getOwnPropertyDescriptors({...options}));else Object.assign(self,options);return self[RebuildOptions]=options,self.ast=ast,self}var lambda=(f)=>f;var SchemaErrorTypeId="~effect/Schema/SchemaError";function isSchemaError(u){return hasProperty(u,SchemaErrorTypeId)&&u[SchemaErrorTypeId]===SchemaErrorTypeId}function declareConstructor(){return(typeParameters,run,annotations)=>make5(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make5(ast))),annotations))}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed5(input):fail5(new InvalidType(ast,input,options)),annotations)}class SchemaError extends TaggedError2("SchemaError"){[SchemaErrorTypeId]=SchemaErrorTypeId;constructor(issue){let stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);try{super({issue})}finally{setStackTraceLimit(stackTraceLimit)}}get message(){return defaultFormatter(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[NodeInspectSymbol](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}}function isSchemaError2(u){return isSchemaError(u)}function fromIssueEffect(self){if(effectIsExit(self))return fromIssueExit(self);return catchCause2(self,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map3(exit.cause,(issue)=>new SchemaError(issue)))}function getSchemaErrorOrThrow(cause,message){let schemaError;for(let reason of cause.reasons){if(!isFailReason2(reason)||!isSchemaError2(reason.error))throw new globalThis.Error(message,{cause});schemaError??=reason.error}if(schemaError===void 0)throw new globalThis.Error(message,{cause});return schemaError}function runSchemaErrorSync(self){let exit=runSyncExit2(self);if(isSuccess3(exit))return exit.value;throw getSchemaErrorOrThrow(exit.cause,"Sync adapter can only throw schema errors")}function decodeUnknownEffect2(schema,options){let parser=decodeUnknownEffect(schema,options);return(input,options)=>fromIssueEffect(parser(input,options))}var decodeUnknownOption2=decodeUnknownOption;function decodeUnknownSync(schema,options){let parser=decodeUnknownEffect2(schema,options);return(input,options)=>runSchemaErrorSync(parser(input,options))}function encodeUnknownEffect2(schema,options){let parser=encodeUnknownEffect(schema,options);return(input,options)=>fromIssueEffect(parser(input,options))}function encodeUnknownSync(schema,options){let parser=encodeUnknownEffect2(schema,options);return(input,options)=>runSchemaErrorSync(parser(input,options))}var encodeSync=encodeUnknownSync,make5=make4;var optionalKey2=lambda((schema)=>make5(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{let schema=UndefinedOr(self);return make5(optional(self.ast),{schema})});var toEncoded2=lambda((schema)=>make5(toEncoded(schema.ast),{schema}));function Literal2(literal){let out=make5(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Null2=make5(null_),Undefined2=make5(undefined_2),String4=make5(string2);var Number5=make5(number2),Boolean3=make5(boolean);function makeStruct(ast,fields){return make5(ast,{fields,mapFields(f,options){let fields=f(this.fields);return makeStruct(struct(fields,options?.unsafePreserveChecks?this.ast.checks:void 0),fields)}})}function Struct(fields){return makeStruct(struct(fields,void 0),fields)}function makeTuple(ast,elements){return make5(ast,{elements,mapElements(f,options){let elements=f(this.elements);return makeTuple(tuple(elements,options?.unsafePreserveChecks?this.ast.checks:void 0),elements)}})}function Tuple(elements){return makeTuple(tuple(elements),elements)}var ArraySchema=lambda((schema)=>make5(new Arrays(!1,[],[schema.ast]),{value:schema}));var NonEmptyArray=lambda((schema)=>make5(new Arrays(!1,[schema.ast],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make5(ast,{members,mapMembers(f,options){let members=f(this.members);return makeUnion(union(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:void 0),members)}})}function Union2(members,options){return makeUnion(union(members,options,void 0),members)}function Literals(literals){let members=literals.map(Literal2);return make5(union(members,void 0,void 0),{literals,members,mapMembers(f){return Union2(f(this.members))},pick(literals){return Literals(literals)},transform(to){return Union2(members.map((member,index)=>member.transform(to[index])))}})}var NullOr=lambda((self)=>Union2([self,Null2])),UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function brand(identifier){return(schema)=>make5(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>make5(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}function withConstructorDefault2(defaultValue){return(schema)=>make5(withConstructorDefault(schema.ast,defaultValue),{schema})}function toIssueEffect(self){if(effectIsExit(self)&&self._tag==="Success")return self;return catchCause2(self,(cause)=>failCauseSync2(()=>map3(cause,(error)=>error.issue)))}function withDecodingDefaultKey(defaultValue,options){let encode=options?.encodingStrategy==="omit"?omit():passthrough();return(self)=>optionalKey2(toEncoded2(self)).pipe(decodeTo2(self,{decode:withDefault(toIssueEffect(defaultValue)),encode}))}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed5(literal)))}function TaggedStruct(value,fields){return Struct({_tag:tag(value),...fields})}function instanceOf(constructor,annotations){return declare((u)=>u instanceof constructor,annotations)}function link(){return(encodeTo,transformation)=>new Link(encodeTo.ast,makeTransformation(transformation))}var makeFilter2=makeFilter;function isPattern2(regExp,annotations){let{source,flags}=regExp,canExport=/^[dg]*uy?$/.test(flags),runtimeRegExp=flags===""?`new globalThis.RegExp(${format(source)})`:`new globalThis.RegExp(${format(source)}, ${format(flags)})`;return isPattern(regExp,{toJsonSchema:()=>canExport?{pattern:flags.endsWith("y")?`^(?:${source})`:source}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${runtimeRegExp})`}),...annotations})}function isBase64(annotations){let regExp=/^[0-9a-zA-Z+/]*={0,2}$/;return makeFilter2((s)=>s.length%4===0&®Exp.test(s),{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:"^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$"}),arbitraryConstraint:{patterns:[{source:"^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$",flags:""}]},toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make5(finite),isFinite2=isFinite;function makeIsGreaterThan(options){let gt=isGreaterThan(options.order),formatter=options.formatter??format;return(exclusiveMinimum,annotations)=>makeFilter2((input)=>gt(input,exclusiveMinimum),{expected:`a value greater than ${formatter(exclusiveMinimum)}`,arbitraryConstraint:{order:options.order,minimum:exclusiveMinimum,exclusiveMinimum:!0},...options.annotate?.(exclusiveMinimum),...annotations})}function makeIsGreaterThanOrEqualTo(options){let gte=isGreaterThanOrEqualTo(options.order),formatter=options.formatter??format;return(minimum,annotations)=>makeFilter2((input)=>gte(input,minimum),{expected:`a value greater than or equal to ${formatter(minimum)}`,arbitraryConstraint:{order:options.order,minimum},...options.annotate?.(minimum),...annotations})}function makeIsLessThanOrEqualTo(options){let lte=isLessThanOrEqualTo(options.order),formatter=options.formatter??format;return(maximum,annotations)=>makeFilter2((input)=>lte(input,maximum),{expected:`a value less than or equal to ${formatter(maximum)}`,arbitraryConstraint:{order:options.order,maximum},...options.annotate?.(maximum),...annotations})}function makeIsBetween(deriveOptions){let greaterThanOrEqualTo=isGreaterThanOrEqualTo(deriveOptions.order),greaterThan=isGreaterThan(deriveOptions.order),lessThanOrEqualTo=isLessThanOrEqualTo(deriveOptions.order),lessThan=isLessThan(deriveOptions.order),formatter=deriveOptions.formatter??format;return(options,annotations)=>{let gte=options.exclusiveMinimum?greaterThan:greaterThanOrEqualTo,lte=options.exclusiveMaximum?lessThan:lessThanOrEqualTo;return makeFilter2((input)=>gte(input,options.minimum)&<e(input,options.maximum),{expected:`a value between ${formatter(options.minimum)}${options.exclusiveMinimum?" (excluded)":""} and ${formatter(options.maximum)}${options.exclusiveMaximum?" (excluded)":""}`,arbitraryConstraint:{order:deriveOptions.order,minimum:options.minimum,maximum:options.maximum,...options.exclusiveMinimum&&{exclusiveMinimum:!0},...options.exclusiveMaximum&&{exclusiveMaximum:!0}},...deriveOptions.annotate?.(options),...annotations})}}function encodeNumberPayload(number){if(!globalThis.Number.isFinite(number))throw new globalThis.RangeError(`Expected a finite number, got ${format(number)}`);return number}var isGreaterThan2=makeIsGreaterThan({order:Number2,annotate:(exclusiveMinimum)=>({representation:{id:"effect/schema/isGreaterThan",payload:{exclusiveMinimum:encodeNumberPayload(exclusiveMinimum)}},toJsonSchema:()=>({exclusiveMinimum}),toCode:()=>({runtime:`Schema.isGreaterThan(${format(exclusiveMinimum)})`})})}),isGreaterThanOrEqualTo2=makeIsGreaterThanOrEqualTo({order:Number2,annotate:(minimum)=>({representation:{id:"effect/schema/isGreaterThanOrEqualTo",payload:{minimum:encodeNumberPayload(minimum)}},toJsonSchema:()=>({minimum}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${format(minimum)})`})})});var isLessThanOrEqualTo2=makeIsLessThanOrEqualTo({order:Number2,annotate:(maximum)=>({representation:{id:"effect/schema/isLessThanOrEqualTo",payload:{maximum:encodeNumberPayload(maximum)}},toJsonSchema:()=>({maximum}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${format(maximum)})`})})}),isBetween=makeIsBetween({order:Number2,annotate:(options)=>{let exclusiveMinimum=options.exclusiveMinimum?!0:void 0,exclusiveMaximum=options.exclusiveMaximum?!0:void 0;return{representation:{id:"effect/schema/isBetween",payload:{minimum:encodeNumberPayload(options.minimum),maximum:encodeNumberPayload(options.maximum),...exclusiveMinimum&&{exclusiveMinimum},...exclusiveMaximum&&{exclusiveMaximum}}},toJsonSchema:()=>({[exclusiveMinimum?"exclusiveMinimum":"minimum"]:options.minimum,[exclusiveMaximum?"exclusiveMaximum":"maximum"]:options.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${format(options.minimum)}, maximum: ${format(options.maximum)}, exclusiveMinimum: ${format(exclusiveMinimum)}, exclusiveMaximum: ${format(exclusiveMaximum)} })`})}}});function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>({type:"integer",minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...annotations})}var Int=Number5.check(isInt());function isMinLength(minLength,annotations){return minLength=normalizeCardinality(minLength),makeIsMinLength(minLength,Math.ceil(minLength/2),annotations)}function makeIsMinLength(minLength,minCodePoints,annotations){return makeFilter2((input)=>input.length>=minLength,{expected:`a value with a length of at least ${minLength}`,representation:{id:"effect/schema/isMinLength",payload:{minLength}},toJsonSchema:({type})=>type==="string"?minLength<=1?{minLength:minCodePoints}:[{minLength:minCodePoints},!0]:type==="array"?{minItems:minLength}:type===void 0?[{minLength:minCodePoints,minItems:minLength},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${minLength})`}),[STRUCTURAL_ANNOTATION_KEY]:!0,arbitraryConstraint:{minLength},...annotations})}function isNonEmpty(annotations){return makeIsMinLength(1,1,annotations)}function isMaxLength(maxLength,annotations){return maxLength=normalizeCardinality(maxLength),makeFilter2((input)=>input.length<=maxLength,{expected:`a value with a length of at most ${maxLength}`,representation:{id:"effect/schema/isMaxLength",payload:{maxLength}},toJsonSchema:({type})=>type==="string"?maxLength===0?{maxLength}:[{maxLength},!0]:type==="array"?{maxItems:maxLength}:type===void 0?[{maxLength,maxItems:maxLength},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${maxLength})`}),[STRUCTURAL_ANNOTATION_KEY]:!0,arbitraryConstraint:{maxLength},...annotations})}function normalizeCardinality(value){if(!globalThis.Number.isFinite(value))throw new globalThis.RangeError(`Expected a finite number, got ${value}`);return Math.max(0,Math.floor(value))}var NonEmptyString=String4.check(isNonEmpty());var RegExp2=instanceOf(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:"Schema.RegExp",Type:"globalThis.RegExp"}),expected:"RegExp",toCodecJson:()=>link()(Struct({source:String4,flags:String4}),transformEffect2({decode:(e,options)=>try_2({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed5({source:regExp.source,flags:regExp.flags})}))}),URLString=String4.annotate({expected:"a string that will be decoded as a URL"}),URL2=instanceOf(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:"Schema.URL",Type:"globalThis.URL"}),expected:"URL",toCodecJson:()=>link()(URLString,urlFromString)});var JsonString=String4.annotate({expected:"a string that will be decoded as JSON"});function fromJsonString2(schema,options){return JsonString.pipe(decodeTo2(schema,fromJsonString(options)))}var File2=instanceOf(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:"Schema.File",Type:"globalThis.File"}),expected:"File",toCodecJson:()=>link()(Struct({data:String4.check(isBase64()),type:String4,name:String4,lastModified:Int}),transformEffect2({decode:(e,options)=>match(decode(e.data),{onFailure:()=>fail5(new InvalidValue({expected:"a valid Base64 string"},e.data,options)),onSuccess:(bytes)=>{let buffer=new globalThis.Uint8Array(bytes);return succeed5(new globalThis.File([buffer],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(file,options)=>tryPromise2({try:async()=>{let bytes=new globalThis.Uint8Array(await file.arrayBuffer());return{data:encode(bytes),type:file.type,name:file.name,lastModified:file.lastModified}},catch:()=>new InvalidValue({expected:"a readable File"},file,options)})}))});var URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:"Schema.URLSearchParams",Type:"globalThis.URLSearchParams"}),expected:"URLSearchParams",toCodecJson:()=>link()(String4.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var FiniteFromString=String4.annotate({expected:"a string that will be decoded as a finite number"}).pipe(decodeTo2(Finite,numberFromString));var Base64String=String4.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"}),Uint8Array2=instanceOf(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:"Schema.Uint8Array",Type:"globalThis.Uint8Array"}),expected:"Uint8Array",toCodecJson:()=>link()(Base64String,uint8ArrayFromBase64String)});var arbitraryMinimumDateTimestamp=-8640000000000000,arbitraryMaximumDateTimestamp=8640000000000000,arbitraryMinimumZonedDateTimeTimestamp=arbitraryMinimumDateTimestamp+50400000,arbitraryMaximumZonedDateTimeTimestamp=arbitraryMaximumDateTimestamp-50400000;var OrganizationId=String4.check(isPattern2(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/)).pipe(brand("OrganizationId")),OrganizationSummary=Struct({id:OrganizationId,name:NonEmptyString,slug:NonEmptyString,personal:Boolean3}),WorkspaceAccount=Struct({user:Struct({name:String4,email:String4,emailVerified:Boolean3,image:NullOr(String4),signedInWith:Literals(["github","password"])}),active:OrganizationSummary,organizations:ArraySchema(OrganizationSummary),members:ArraySchema(Struct({id:String4,name:String4,email:String4,role:String4})),role:String4});var Identity=String4.check(isPattern2(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/)),Natural=Number5.check(isInt(),isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)),RepositoryId=String4.check(isPattern2(/^(?:github:[1-9][0-9]{0,15}|local:[a-z0-9][a-z0-9._-]{0,127})$/)).pipe(brand("RepositoryId")),GitHubRepositoryNumber=Natural.check(isGreaterThanOrEqualTo2(1)).pipe(brand("GitHubRepositoryNumber")),LocalRepositoryName=String4.check(isPattern2(/^[a-z0-9][a-z0-9._-]{0,127}$/)).pipe(brand("LocalRepositoryName"));var SnapshotId=Identity.pipe(brand("SnapshotId")),FileId=Identity.pipe(brand("FileId")),OccurrenceId=Identity.pipe(brand("OccurrenceId")),GroupId=Identity.pipe(brand("GroupId")),AccountUserId=String4.check(isPattern2(/^[A-Za-z0-9_-]{1,200}$/)).pipe(brand("AccountUserId")),ReviewerId=String4.check(isPattern2(/^account:[A-Za-z0-9_-]{1,200}$/)).pipe(brand("ReviewerId"));var DecisionId=Identity.pipe(brand("DecisionId")),CommandId=Identity.pipe(brand("CommandId")),CommentId=Identity.pipe(brand("CommentId")),PublicationId=Identity.pipe(brand("PublicationId")),Fingerprint=String4.check(isPattern2(/^[a-f0-9]{64}$/)).pipe(brand("Fingerprint")),GitRevision=String4.check(isPattern2(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)).pipe(brand("GitRevision")),RepoPath=String4.check(makeFilter2((path)=>path.length>0&&path.length<=4096&&!path.startsWith("/")&&!path.includes("\\")&&!/[\u0000-\u001f\u007f]/u.test(path)&&path.split("/").every((part)=>part!==""&&part!=="."&&part!==".."))).pipe(brand("RepoPath")),ByteOffset=Natural.pipe(brand("ByteOffset")),ByteLength=Natural.pipe(brand("ByteLength")),LineNumber=Natural.check(isGreaterThanOrEqualTo2(1)).pipe(brand("LineNumber")),Version=Natural.pipe(brand("Version")),Timestamp=String4.check(makeFilter2((text)=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(text)&&Number.isFinite(Date.parse(text))&&new Date(text).toISOString()===text)).pipe(brand("Timestamp")),CommentBody=String4.check(isMinLength(1),isMaxLength(65536),makeFilter2((text)=>text.trim().length>0)).pipe(brand("CommentBody")),EntityId=Identity.pipe(brand("EntityId")),Similarity=Number5.check(isFinite2(),isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(1)).pipe(brand("Similarity")),CommentVersion=Natural.pipe(brand("CommentVersion")),RemotePositiveId=Natural.check(isGreaterThanOrEqualTo2(1)),GitHubReviewCommentId=RemotePositiveId.pipe(brand("GitHubReviewCommentId")),GitHubIssueCommentId=RemotePositiveId.pipe(brand("GitHubIssueCommentId")),GitHubReviewId=RemotePositiveId.pipe(brand("GitHubReviewId"));var AgentName=String4.check(isPattern2(/^[A-Za-z0-9][A-Za-z0-9 ._:/@()+-]{0,63}$/),makeFilter2((text)=>text.trimEnd()===text)).pipe(brand("AgentName")),Actor=Union2([Struct({kind:Literal2("human"),suggestedBy:optional2(AgentName)}),Struct({kind:Literal2("agent"),agent:AgentName})]);var CatalogEntry=Struct({id:OccurrenceId,fingerprint:Fingerprint}),OccurrenceIndex=Int.check(isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("OccurrenceIndex")),Position=Int.check(isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)),Count=Int.check(isGreaterThanOrEqualTo2(1)),Runs=NonEmptyArray(Tuple([Position,Count])).check(makeFilter2((runs)=>runs.every(([start],index)=>{let previous=runs[index-1];return previous===void 0||start>previous[0]+previous[1]}))),expand=([start,count])=>Array.from({length:count},(_,offset)=>start+offset),runsOf=(positions)=>{let runs=[];for(let position of[...positions].sort((left,right)=>left-right)){let last=runs.at(-1);if(last!==void 0&&position===last[0]+last[1])last[1]++;else if(last===void 0||position>last[0]+last[1])runs.push([position,1])}let[head=[positions[0],1],...tail]=runs;return[head,...tail]},OccurrencePositions=Runs.pipe(decodeTo2(NonEmptyArray(OccurrenceIndex),transform2({decode:([head,...tail])=>[head[0],...expand([head[0]+1,head[1]-1]),...tail.flatMap(expand)],encode:runsOf})));var Disposition=Literals(["inspected","no-further-inspection","not-reviewed"]);var CarriedFrom=Struct({snapshotId:SnapshotId,decisionId:DecisionId}),HistorySubject=String4.check(isMinLength(1),isMaxLength(160),makeFilter2((text)=>text.trim()===text&&!/[\u0000-\u001f\u007f]/u.test(text))).pipe(brand("HistorySubject")),provenanceFields={actor:Actor,carriedFrom:optional2(CarriedFrom),subject:optional2(HistorySubject),redoOf:optional2(DecisionId)},ReviewDecision=Struct({id:DecisionId,snapshotId:SnapshotId,occurrenceIds:NonEmptyArray(OccurrenceId),disposition:Disposition,recordedAt:Timestamp,...provenanceFields}),RevisitAction=Literals(["mark","clear"]),RevisitDecision=Struct({id:DecisionId,snapshotId:SnapshotId,occurrenceIds:NonEmptyArray(OccurrenceId),action:RevisitAction,recordedAt:Timestamp,...provenanceFields}),PositionedReviewDecision=Struct({id:DecisionId,occurrences:OccurrencePositions,disposition:Disposition,recordedAt:Timestamp,...provenanceFields}),PositionedRevisitDecision=Struct({id:DecisionId,occurrences:OccurrencePositions,action:RevisitAction,recordedAt:Timestamp,...provenanceFields}),Count2=Int.check(isGreaterThanOrEqualTo2(0)),PositiveCount=Int.check(isGreaterThanOrEqualTo2(1)),HistoryEntryKind=Literals(["review","revisit","clear-revisit"]),ChangedStep=Struct({decisionId:DecisionId,changedEdits:PositiveCount,lapsed:optional2(Struct({kind:HistoryEntryKind,disposition:NullOr(Disposition),subject:optional2(HistorySubject),actor:Actor,recordedAt:Timestamp}))}),HistoryEvent=Union2([Struct({kind:Literal2("recorded"),decisionId:DecisionId}),Struct({kind:Literal2("undone"),decisionId:DecisionId,actor:Actor}),Struct({kind:Literal2("redone"),decisionId:DecisionId,redoDecisionId:DecisionId}),Struct({kind:Literal2("carried"),from:SnapshotId,changed:ArraySchema(ChangedStep)})]),commandFields={commandId:CommandId,snapshotId:SnapshotId,reviewerId:ReviewerId,expectedVersion:Version,actor:optional2(Actor)},selectionFields={decisionId:DecisionId,occurrenceIds:NonEmptyArray(OccurrenceId),recordedAt:Timestamp,subject:optional2(HistorySubject)},ReviewCommand=Union2([Struct({...commandFields,...selectionFields,kind:Literal2("review-edits"),disposition:Disposition}),Struct({...commandFields,kind:Literal2("undo-review"),decisionId:DecisionId}),Struct({...commandFields,...selectionFields,kind:Literal2("mark-revisit")}),Struct({...commandFields,...selectionFields,kind:Literal2("clear-revisit")}),Struct({...commandFields,kind:Literal2("redo-review"),decisionId:DecisionId,redoDecisionId:DecisionId,recordedAt:Timestamp})]),CatalogSelection=Struct({catalogDigest:Fingerprint,occurrences:OccurrencePositions}),positionedSelectionFields={decisionId:DecisionId,selection:CatalogSelection,recordedAt:Timestamp,subject:optional2(HistorySubject)},PositionedReviewCommand=Union2([Struct({...commandFields,...positionedSelectionFields,kind:Literal2("review-edits"),disposition:Disposition}),Struct({...commandFields,kind:Literal2("undo-review"),decisionId:DecisionId}),Struct({...commandFields,...positionedSelectionFields,kind:Literal2("mark-revisit")}),Struct({...commandFields,...positionedSelectionFields,kind:Literal2("clear-revisit")}),Struct({...commandFields,kind:Literal2("redo-review"),decisionId:DecisionId,redoDecisionId:DecisionId,recordedAt:Timestamp})]);var ReviewReceipt=Struct({commandId:CommandId,version:Version,snapshotId:SnapshotId}),CommandRecord=Struct({commandId:CommandId,fingerprint:Fingerprint,receipt:ReviewReceipt}),ReviewState=Struct({snapshotId:SnapshotId,reviewerId:ReviewerId,version:Version,catalog:ArraySchema(CatalogEntry),decisions:ArraySchema(ReviewDecision),revisits:ArraySchema(RevisitDecision),undoneDecisionIds:ArraySchema(DecisionId),history:ArraySchema(HistoryEvent),commands:ArraySchema(CommandRecord)}),PositionedReviewState=Struct({snapshotId:SnapshotId,reviewerId:ReviewerId,version:Version,catalogDigest:Fingerprint,occurrences:Int.check(isGreaterThanOrEqualTo2(0)),decisions:ArraySchema(PositionedReviewDecision),revisits:ArraySchema(PositionedRevisitDecision),undoneDecisionIds:ArraySchema(DecisionId),history:ArraySchema(HistoryEvent)}),ReviewError=Union2([Struct({kind:Literal2("stale-snapshot"),expected:SnapshotId,received:SnapshotId}),Struct({kind:Literal2("stale-version"),expected:Version,received:Version}),Struct({kind:Literal2("wrong-reviewer")}),Struct({kind:Literal2("command-conflict"),commandId:CommandId}),Struct({kind:Literal2("unknown-occurrences"),occurrenceIds:NonEmptyArray(OccurrenceId)}),Struct({kind:Literal2("duplicate-occurrences")}),Struct({kind:Literal2("decision-conflict"),decisionId:DecisionId}),Struct({kind:Literal2("unknown-decision"),decisionId:DecisionId}),Struct({kind:Literal2("already-undone"),decisionId:DecisionId}),Struct({kind:Literal2("not-undone"),decisionId:DecisionId}),Struct({kind:Literal2("already-redone"),decisionId:DecisionId,redoDecisionId:DecisionId}),Struct({kind:Literal2("nothing-to-redo"),decisionId:DecisionId}),Struct({kind:Literal2("revisit-not-applicable"),action:RevisitAction,occurrenceIds:NonEmptyArray(OccurrenceId)}),Struct({kind:Literal2("version-exhausted")})]),ReviewResult=Union2([Struct({kind:Literal2("accepted"),state:ReviewState,receipt:ReviewReceipt,replayed:Boolean3}),Struct({kind:Literal2("rejected"),error:ReviewError})]),PositionedReviewResult=Union2([Struct({kind:Literal2("accepted"),progress:PositionedReviewState,receipt:ReviewReceipt,replayed:Boolean3}),Struct({kind:Literal2("rejected"),error:ReviewError})]);var OccurrenceStatus=Literals(["pending","reviewed","revisit"]);var StatusCounts=Struct({total:Count2,reviewed:Count2,revisit:Count2,pending:Count2,remaining:Count2});var HistoryEntry=Struct({decisionId:DecisionId,kind:HistoryEntryKind,disposition:NullOr(Disposition),subject:NullOr(HistorySubject),editCount:PositiveCount,changedEdits:Count2,lapsed:Boolean3,earlierRevision:Boolean3,actor:Actor,recordedAt:Timestamp,label:NonEmptyString});var ScopeState=Literals(["empty","pending","partial","reviewed","revisit"]);var CommentAnchor=Union2([Struct({kind:Literal2("line"),snapshotId:SnapshotId,fileId:FileId,path:RepoPath,commit:GitRevision,side:Literals(["base","head"]),line:LineNumber,startLine:optional2(LineNumber)}).check(makeFilter2((anchor)=>anchor.startLine===void 0||anchor.startLine<anchor.line)),Struct({kind:Literal2("review"),snapshotId:SnapshotId}),Struct({kind:Literal2("github-thread"),snapshotId:SnapshotId,rootCommentId:GitHubReviewCommentId})]),HttpsUrl=String4.check(makeFilter2((input)=>{try{let url=new URL(input);return url.protocol==="https:"&&!url.username&&!url.password}catch{return!1}})).pipe(brand("HttpsUrl")),GitHubCommentId=Number5.check(isInt(),isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("GitHubCommentId")),fields={id:CommentId,reviewerId:ReviewerId,anchor:CommentAnchor,body:CommentBody,createdAt:Timestamp,updatedAt:Timestamp,version:CommentVersion,writtenBy:optional2(Actor)},DraftComment=Struct({...fields,kind:Literal2("draft")}),PublishingComment=Struct({...fields,kind:Literal2("publishing"),publicationId:PublicationId}),UncertainComment=Struct({...fields,kind:Literal2("uncertain"),publicationId:PublicationId,reason:NonEmptyString}),PublishedComment=Struct({...fields,kind:Literal2("published"),publicationId:PublicationId,remoteId:GitHubCommentId,url:HttpsUrl}),Comment=Union2([DraftComment,PublishingComment,UncertainComment,PublishedComment]),CommentError=Union2([Struct({kind:Literal2("stale-comment"),expected:CommentVersion,received:CommentVersion}),Struct({kind:Literal2("comment-version-exhausted")}),Struct({kind:Literal2("comment-locked"),state:Literals(["publishing","uncertain","published"])}),Struct({kind:Literal2("stale-anchor"),expected:SnapshotId,received:SnapshotId}),Struct({kind:Literal2("wrong-publication"),expected:PublicationId,received:PublicationId}),Struct({kind:Literal2("not-publishing")}),Struct({kind:Literal2("proposal-stale"),baseVersion:CommentVersion,current:CommentVersion})]),CommentResult=Union2([Struct({kind:Literal2("accepted"),comment:Comment}),Struct({kind:Literal2("rejected"),error:CommentError})]);var PublicationOutcome=Union2([Struct({kind:Literal2("confirmed"),remoteId:GitHubCommentId,url:HttpsUrl}),Struct({kind:Literal2("uncertain"),reason:NonEmptyString}),Struct({kind:Literal2("confirmed-not-published")})]);var ProposalReason=String4.check(isMinLength(1),isMaxLength(2000)),CommentEditProposal=Struct({id:CommandId,commentId:CommentId,baseVersion:CommentVersion,baseBody:CommentBody,body:CommentBody,proposedBy:AgentName,reason:optional2(ProposalReason),createdAt:Timestamp});var ExactCorrespondence=Struct({previousSnapshotId:SnapshotId,nextSnapshotId:SnapshotId,matches:ArraySchema(Struct({previousOccurrenceId:OccurrenceId,nextOccurrenceId:OccurrenceId,fingerprint:Fingerprint,basis:Literal2("exact-file-context")}))}),CarryResult=Union2([Struct({kind:Literal2("accepted"),state:ReviewState}),Struct({kind:Literal2("rejected"),reason:Literals(["wrong-snapshot","duplicate-catalog","invalid-correspondence","ambiguous-fingerprint"])})]);var FindingSeverity=Literals(["critical","high","medium","low"]),FindingConfidence=Literals(["high","medium","low"]),FindingId=String4.check(isPattern2(/^finding_[a-f0-9]{32}$/)).pipe(brand("FindingId")),NonBlank=(max)=>String4.check(isMinLength(1),isMaxLength(max),makeFilter2((text)=>text.trim().length>0)),FindingTitle=NonBlank(200).pipe(brand("FindingTitle")),FindingDetail=NonBlank(4000).pipe(brand("FindingDetail")),MAX_FINDING_EDITS=50,MAX_REPORTED_FINDINGS=50;var FindingInput=Struct({occurrenceIds:ArraySchema(OccurrenceId).check(isMinLength(1),isMaxLength(MAX_FINDING_EDITS),makeFilter2((ids)=>new Set(ids).size===ids.length)),severity:FindingSeverity,confidence:FindingConfidence,title:FindingTitle,detail:FindingDetail}),FindingInputs=ArraySchema(FindingInput).check(isMinLength(1),isMaxLength(MAX_REPORTED_FINDINGS)),FindingState=Union2([Struct({kind:Literal2("open")}),Struct({kind:Literal2("drafted"),commentId:CommentId,at:Timestamp}),Struct({kind:Literal2("dismissed"),at:Timestamp})]),Finding=Struct({id:FindingId,reportId:CommandId,snapshotId:SnapshotId,...FindingInput.fields,reportedBy:AgentName,reportedAt:Timestamp,state:FindingState});var GitHubOwner=String4.check(isPattern2(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/)).pipe(brand("GitHubOwner")),GitHubRepository=String4.check(isPattern2(/^[A-Za-z0-9_.-]{1,100}$/),makeFilter2((name)=>name!=="."&&name!=="..")).pipe(brand("GitHubRepository")),PullRequestNumber=Number5.check(isInt(),isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("PullRequestNumber")),GitHubReference=Struct({owner:GitHubOwner,repository:GitHubRepository,number:PullRequestNumber});var MergeMethod=Literals(["merge","squash","rebase"]),CommitTitle=String4.check(isMinLength(1),isMaxLength(1024)),CommitBody=String4.check(isMaxLength(65536)),MergeCommitMessage=Struct({title:CommitTitle,body:CommitBody}),GitHubMergeBox=Struct({methods:ArraySchema(MergeMethod).check(isMaxLength(3)),defaultMethod:NullOr(MergeMethod),mergeable:Literals(["mergeable","conflicting","unknown"]),state:Literals(["clean","behind","blocked","dirty","unstable","has_hooks","draft","unknown"]),canUpdateBranch:Boolean3,messages:Struct({merge:NullOr(MergeCommitMessage),squash:NullOr(MergeCommitMessage)})}),MergePullRequest=Struct({method:MergeMethod,expectedHead:GitRevision,message:NullOr(MergeCommitMessage)}),MergeRefusal=Literals(["head-moved","not-mergeable","method-not-allowed","app-permission","no-permission","conflicts","not-found","invalid"]),MergeResponse=Union2([Struct({kind:Literal2("merged"),sha:GitRevision,method:MergeMethod}),Struct({kind:Literal2("refused"),refusal:MergeRefusal,message:NonEmptyString}),Struct({kind:Literal2("uncertain"),message:NonEmptyString})]),UpdatePullBranch=Struct({expectedHead:GitRevision}),UpdateBranchResponse=Union2([Struct({kind:Literal2("started"),message:NonEmptyString}),Struct({kind:Literal2("refused"),refusal:MergeRefusal,message:NonEmptyString}),Struct({kind:Literal2("uncertain"),message:NonEmptyString})]);var RemoteText=String4.check(isMaxLength(262144)),GitHubBodyHtml=String4.check(isMaxLength(524288)).pipe(brand("GitHubBodyHtml")),BodyHtml=optional2(GitHubBodyHtml),Count3=Int.check(isGreaterThanOrEqualTo2(0)),GitHubAuthor=Struct({login:String4.check(isMinLength(1),isMaxLength(100)),url:HttpsUrl}),GitHubCollectionCoverage=Union2([Struct({kind:Literal2("complete"),fetched:Count3}),Struct({kind:Literal2("partial"),fetched:Count3,reason:Literals(["page-limit","byte-limit","rate-limit","access-denied","not-found","upstream-error","invalid-response"]),message:NonEmptyString,retryAt:NullOr(Timestamp)})]),Name=String4.check(isMinLength(1),isMaxLength(256)),GitHubPullStats=Struct({additions:Count3,deletions:Count3,changedFiles:Count3,commits:Count3}),GitHubMergeability=Struct({mergeable:Literals(["mergeable","conflicting","unknown"]),mergeState:Literals(["clean","behind","blocked","dirty","unstable","has_hooks","draft","unknown"])}),GitHubLabel=Struct({name:Name,color:String4.check(isMaxLength(16))}),GitHubRequestedReviewer=Struct({kind:Literals(["user","team"]),name:Name}),GitHubPullFacts=Struct({stats:GitHubPullStats,mergeability:GitHubMergeability,requestedReviewers:ArraySchema(GitHubRequestedReviewer).check(isMaxLength(100)),assignees:ArraySchema(Name).check(isMaxLength(100)),labels:ArraySchema(GitHubLabel).check(isMaxLength(100)),milestone:NullOr(Struct({title:RemoteText,url:HttpsUrl}))}),GitHubPullMetadata=Struct({reference:GitHubReference,url:HttpsUrl,title:RemoteText,body:RemoteText,bodyHtml:BodyHtml,author:NullOr(GitHubAuthor),state:Literals(["open","closed","merged"]),draft:Boolean3,comparisonBaseRevision:NullOr(GitRevision),baseRevision:GitRevision,headRevision:GitRevision,baseRef:String4,headRef:String4,createdAt:Timestamp,updatedAt:Timestamp,facts:optional2(GitHubPullFacts)}),GitHubChecks=Union2([Struct({kind:Literal2("none")}),Struct({kind:Literal2("forbidden")}),Struct({kind:Literal2("rolled-up"),state:Literals(["success","failure","pending"]),passed:Count3,failed:Count3,pending:Count3,skipped:Count3})]),GitHubLinkedIssue=Struct({number:PullRequestNumber,title:RemoteText,url:HttpsUrl,state:Literals(["open","closed"])}),GitHubPullStatus=Union2([Struct({kind:Literal2("available"),headRevision:GitRevision,checks:GitHubChecks,isStale:optional2(Boolean3),reviewDecision:NullOr(Literals(["approved","changes-requested","review-required"])),linkedIssues:NullOr(ArraySchema(GitHubLinkedIssue).check(isMaxLength(10))),merge:optional2(GitHubMergeBox)}),Struct({kind:Literal2("unavailable")})]),GitHubIssueComment=Struct({id:GitHubIssueCommentId,author:NullOr(GitHubAuthor),body:RemoteText,bodyHtml:BodyHtml,url:HttpsUrl,createdAt:Timestamp,updatedAt:Timestamp}),GitHubReview=Struct({id:GitHubReviewId,author:NullOr(GitHubAuthor),body:RemoteText,bodyHtml:BodyHtml,url:HttpsUrl,state:Literals(["PENDING","APPROVED","CHANGES_REQUESTED","COMMENTED","DISMISSED"]),commit:GitRevision,submittedAt:NullOr(Timestamp)}),GitHubLineRange=Struct({side:Literals(["base","head"]),startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((range)=>range.endLine>=range.startLine)),GitHubReviewLocation=Union2([Struct({kind:Literal2("line"),path:RepoPath,commit:GitRevision,originalCommit:GitRevision,current:NullOr(GitHubLineRange),original:NullOr(GitHubLineRange),diffHunk:RemoteText}),Struct({kind:Literal2("file"),path:RepoPath,commit:GitRevision,originalCommit:GitRevision,diffHunk:RemoteText}),Struct({kind:Literal2("unavailable"),path:NullOr(RepoPath),reason:NonEmptyString,diffHunk:RemoteText})]),GitHubReviewComment=Struct({id:GitHubReviewCommentId,reviewId:NullOr(GitHubReviewId),inReplyTo:NullOr(GitHubReviewCommentId),author:NullOr(GitHubAuthor),body:RemoteText,bodyHtml:BodyHtml,url:HttpsUrl,createdAt:Timestamp,updatedAt:Timestamp,location:GitHubReviewLocation}),GitHubThreadResolution=Union2([Struct({kind:Literal2("resolved"),by:NullOr(GitHubAuthor)}),Struct({kind:Literal2("unresolved")})]),GitHubReviewThread=Union2([Struct({kind:Literal2("complete"),root:GitHubReviewComment,replies:ArraySchema(GitHubReviewComment),resolution:optional2(GitHubThreadResolution)}),Struct({kind:Literal2("missing-root"),rootId:GitHubReviewCommentId,comments:ArraySchema(GitHubReviewComment)})]),GitHubStackNumber=Int.check(isGreaterThan2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("GitHubStackNumber")),GitHubStackMember=Struct({number:PullRequestNumber,title:RemoteText,url:HttpsUrl,state:Literals(["open","closed","merged"]),draft:Boolean3,headRef:String4,headRevision:GitRevision}),GitHubStackStatus=Union2([Struct({kind:Literal2("none")}),Struct({kind:Literal2("available"),number:GitHubStackNumber,baseRef:String4,open:Boolean3,members:ArraySchema(GitHubStackMember).check(isMinLength(1),isMaxLength(100))}),Struct({kind:Literal2("unavailable"),message:NonEmptyString})]),GitHubDiscussion=Struct({pull:GitHubPullMetadata,fetchedAt:Timestamp,changedAt:optional2(Timestamp),stack:optional2(GitHubStackStatus),status:optional2(GitHubPullStatus),issueComments:ArraySchema(GitHubIssueComment),reviews:ArraySchema(GitHubReview),threads:ArraySchema(GitHubReviewThread),coverage:Struct({issueComments:GitHubCollectionCoverage,reviews:GitHubCollectionCoverage,reviewComments:GitHubCollectionCoverage})}),ResolveGitHubThread=Struct({rootCommentId:GitHubReviewCommentId,to:Literals(["resolved","unresolved"])}),GitHubThreadResolutionResponse=Union2([Struct({kind:Literal2("changed"),rootCommentId:GitHubReviewCommentId,resolution:GitHubThreadResolution}),Struct({kind:Literal2("refused"),refusal:Literals(["no-permission","app-permission","thread-gone"]),message:NonEmptyString})]);var Count4=Int.check(isGreaterThanOrEqualTo2(0)),Title=String4.check(isMaxLength(1024)),GitHubPushChange=Union2([Struct({kind:Literal2("added"),commits:Count4,files:Count4,filesCapped:Boolean3}),Struct({kind:Literal2("rewritten")}),Struct({kind:Literal2("unknown")})]),GitHubPushStatus=Union2([Struct({kind:Literal2("current"),updatedAt:optional2(Timestamp),isClosed:optional2(Boolean3)}),Struct({kind:Literal2("moved"),headRevision:GitRevision,change:GitHubPushChange,updatedAt:optional2(Timestamp),isClosed:optional2(Boolean3)})]),MyGitHubReview=Literals(["approved","approved-earlier","changes-requested","commented","none"]),PullRequestLabel=Struct({name:String4.check(isMinLength(1),isMaxLength(100)),color:String4.check(isPattern2(/^[0-9a-fA-F]{6}$/))}),BranchName=String4.check(isMinLength(1),isMaxLength(255)),PullRequestChecks=Literals(["success","failure","pending"]),PullRequestListItem=Struct({reference:GitHubReference,url:HttpsUrl,title:Title,author:NullOr(GitHubAuthor),isMine:Boolean3,draft:Boolean3,headRevision:GitRevision,updatedAt:Timestamp,myReview:MyGitHubReview,reviewRequested:Boolean3,additions:Count4,deletions:Count4,changedFiles:Count4,labels:ArraySchema(PullRequestLabel).check(isMaxLength(20)),checks:optional2(PullRequestChecks),baseRef:BranchName,headRef:BranchName}),ConnectedRepository=Struct({owner:GitHubOwner,repository:GitHubRepository}),KnownRepository=Struct({repositoryId:RepositoryId,...ConnectedRepository.fields}),ConnectedRepositories=Union2([Struct({kind:Literal2("unavailable"),reason:Literals(["not-connected","no-repositories","github-error"]),message:NonEmptyString}),Struct({kind:Literal2("available"),repositories:ArraySchema(KnownRepository),isPartial:Boolean3})]),PullRequestListCoverage=Union2([Struct({kind:Literal2("complete")}),Struct({kind:Literal2("partial"),message:NonEmptyString})]),PullRequestAuthor=String4.check(isPattern2(/^[A-Za-z0-9][A-Za-z0-9_-]{0,38}(?:\[bot\])?$/)).pipe(brand("PullRequestAuthor"));var PullRequestLabelName=String4.check(isMinLength(1),isMaxLength(100),isPattern2(/^[^"\u0000-\u001f\u007f]+$/u)).pipe(brand("PullRequestLabelName")),MAX_LABEL_FILTERS=5;var PullRequestFilters=Struct({notMine:Boolean3,notApprovedByMe:Boolean3,author:NullOr(PullRequestAuthor).pipe(withDecodingDefaultKey(succeed5(null))),labels:ArraySchema(PullRequestLabelName).check(isMaxLength(MAX_LABEL_FILTERS)).pipe(withDecodingDefaultKey(succeed5([])))});var PullRequestCursor=String4.check(isMinLength(1),isMaxLength(200),isPattern2(/^[A-Za-z0-9+/=_-]+$/)).pipe(brand("PullRequestCursor"));var MAX_LISTED_PULL_REQUESTS=100,AvailablePullRequestList=Struct({kind:Literal2("available"),viewer:NonEmptyString,fetchedAt:Timestamp,repositoryId:RepositoryId,repository:ConnectedRepository,filters:PullRequestFilters,pullRequests:ArraySchema(PullRequestListItem).check(isMaxLength(MAX_LISTED_PULL_REQUESTS)),next:NullOr(PullRequestCursor),coverage:PullRequestListCoverage}),PullRequestList=Union2([Struct({kind:Literal2("unavailable"),reason:Literals(["not-connected","not-readable","github-error"]),message:NonEmptyString}),AvailablePullRequestList]),ProjectPullRequests=Struct({open:Count4,counted:Count4,waitingForMe:Count4,byOthers:Count4,fetchedAt:Timestamp});var WorkspaceProject=Struct({repositoryId:RepositoryId,...ConnectedRepository.fields,addedAt:Timestamp}),ProjectAccess=Literals(["readable","no-access","unknown"]),WorkspaceProjects=Struct({projects:ArraySchema(Struct({...WorkspaceProject.fields,access:ProjectAccess,pullRequests:NullOr(ProjectPullRequests)})),canManage:Boolean3});var PinnedProjects=Struct({pinned:ArraySchema(ConnectedRepository).check(isMaxLength(100))});var IndexOmissionReason=Literals(["excluded","oversized","file-budget","byte-budget","binary","symlink","submodule"]);var LANGUAGE=String.raw`[a-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*`,RAILS_LOCALE=/^config\/locales\/(?:[^/]+\/)*[^/]+\.ya?ml$/u,I18NEXT_LOCALE=new RegExp(String.raw`^((?:[^/]+/)*locales)/(${LANGUAGE})/([A-Za-z0-9_\-]+)\.json$`,"u"),NEXT_INTL_LOCALE=new RegExp(String.raw`^((?:[^/]+/)*messages)/(${LANGUAGE})\.json$`,"u"),TranslationLibrary=Literals(["rails","i18next","next-intl"]),localeFileOf=(path)=>{if(/(?:^|\/)node_modules\//u.test(path))return null;if(RAILS_LOCALE.test(path))return{library:"rails",root:"config/locales"};let i18next=I18NEXT_LOCALE.exec(path);if(i18next!==null)return{library:"i18next",root:i18next[1]??"",locale:i18next[2]??"",namespace:i18next[3]??""};let nextIntl=NEXT_INTL_LOCALE.exec(path);if(nextIntl!==null)return{library:"next-intl",root:nextIntl[1]??"",locale:nextIntl[2]??""};return null},isLocalePath=(path)=>localeFileOf(path)!==null,LocaleRoot=Struct({library:TranslationLibrary,path:String4,files:Int.check(isGreaterThanOrEqualTo2(0)),namespaces:ArraySchema(String4)});var TranslationFrame=Union2([Struct({library:Literal2("rails")}),Struct({library:Literal2("i18next"),namespace:NullOr(String4),keyPrefix:NullOr(String4)}),Struct({library:Literal2("next-intl"),namespace:NullOr(String4)})]);var KEY=String.raw`\.?[A-Za-z0-9_][A-Za-z0-9_\-/]*(?:\.[A-Za-z0-9_][A-Za-z0-9_\-/]*)*`,SCRIPT_PART=String.raw`[A-Za-z0-9_$][A-Za-z0-9_$\-]*`,SCRIPT_KEY=String.raw`(?:[A-Za-z0-9_][A-Za-z0-9_\-]*:)?${SCRIPT_PART}(?:\.${SCRIPT_PART})*`,CALL=new RegExp(String.raw`(?<![\w@$.:])(?:I18n\s*\.\s*(?:t|translate)|t|translate)(?:\s*\(\s*|[ \t]+)(['"])(${KEY})\1`,"gu");var QUOTED=String.raw`(?:'([^'\\\n]*)'|"([^"\\\n]*)"|\x60([^\x60\\$\n]*)\x60)`;var NAME=String.raw`[A-Za-z_$][\w$]*`,I18NEXT_MODULE=String.raw`['"](?:i18next|react-i18next|next-i18next)['"]`,NEXT_INTL_MODULE=String.raw`['"]next-intl(?:/server)?['"]`;var TranslationKey=String4.check(isMinLength(1),isMaxLength(500),isPattern2(new RegExp(`^(?:${KEY}|${SCRIPT_KEY})$`,"u")));var LocaleTarget=Union2([Struct({library:Literal2("rails")}),Struct({library:Literal2("i18next"),root:String4,namespace:String4,isDefaultNamespace:Boolean3}),Struct({library:Literal2("next-intl"),root:String4})]);var LocaleReading=Union2([Struct({kind:Literal2("read"),entries:ArraySchema(Tuple([String4,String4,Int,String4]))}),Struct({kind:Literal2("unreadable"),reason:String4})]),LocaleFileReading=Struct({fileId:FileId,reading:LocaleReading});var LocaleText=Struct({line:Int.check(isGreaterThanOrEqualTo2(1)),value:String4}),TranslationChange=Struct({locale:String4,key:String4,head:NullOr(LocaleText),base:NullOr(LocaleText)}),LocaleFileChanges=Union2([Struct({kind:Literal2("read"),path:RepoPath,previousPath:NullOr(RepoPath),changes:ArraySchema(TranslationChange)}),Struct({kind:Literal2("unread"),path:RepoPath,previousPath:NullOr(RepoPath),reason:Literals(["unreadable","too-many-changes"])})]),IndexedTranslation=Struct({path:RepoPath,locale:String4,key:String4,line:Int,value:String4}),OmittedLocaleFile=Struct({path:RepoPath,reason:IndexOmissionReason});var IndexedTranslations=Struct({localeFiles:Int,unread:Int,localeRoots:ArraySchema(LocaleRoot),entries:ArraySchema(IndexedTranslation),unparsed:ArraySchema(Struct({path:RepoPath,reason:String4})),held:ArraySchema(RepoPath),omitted:NullOr(ArraySchema(OmittedLocaleFile))});var RouteFramework=Literals(["next","expo-router","tanstack-start"]),RouterFolder=Literals(["app","pages","src/app","src/pages"]),unique=(values)=>new Set(values).size===values.length,PackageSide=Union2([Struct({kind:Literal2("unreadable")}),Struct({kind:Literal2("read"),frameworks:ArraySchema(RouteFramework).check(makeFilter2(unique)),routing:NullOr(Struct({folders:ArraySchema(RouterFolder).check(makeFilter2(unique)),customised:ArraySchema(RouteFramework).check(makeFilter2(unique))}))})]),PackageDirectory=String4.check(makeFilter2((directory)=>directory===""||directory.length<=4096&&!directory.includes("\\")&&!/[\u0000-\u001f\u007f]/u.test(directory)&&directory.split("/").every((part)=>part!==""&&part!=="."&&part!==".."))),ProjectPackage=Struct({directory:PackageDirectory,base:NullOr(PackageSide),head:NullOr(PackageSide)}),RouteKind=Literals(["page","api","route","layout","template","loading","error","not-found","fallback","document","middleware","metadata"]),RouteRouter=Literals(["next-app","next-pages","expo-router","tanstack-start"]),FileRoute=Struct({router:RouteRouter,kind:RouteKind,path:String4.check(isPattern2(/^\//)),interceptedFrom:optional2(String4.check(isPattern2(/^\//))),platform:optional2(Literals(["ios","android","web","native"]))}),ModuleDirective=Literals(["use client","use server"]),Sides=(schema)=>Struct({before:NullOr(schema),after:NullOr(schema)}),FileRoutes=Sides(FileRoute),FileDirectives=Sides(ModuleDirective);var DependencyEcosystem=Literals(["rubygems","npm"]),DependencyFormat=Literals(["gemfile-lock","package-json","package-lock","yarn-lock","pnpm-lock","bun-lock"]),DependencyName=String4.check(isPattern2(/^(?:@[A-Za-z0-9._~-]{1,100}\/)?[A-Za-z0-9._~-]{1,214}$/u)).pipe(brand("DependencyName")),DependencyVersion=String4.check(isPattern2(/^[0-9][0-9A-Za-z.+_-]{0,63}$/u)).pipe(brand("DependencyVersion")),WrittenVersion=String4.check(isMinLength(1),isMaxLength(128)),DependencyTarget=Struct({ecosystem:DependencyEcosystem,name:DependencyName,from:DependencyVersion,to:DependencyVersion});var DependencyLookup=Union2([Struct({kind:Literal2("public"),target:DependencyTarget,registry:Literals(["named","default"])}),Struct({kind:Literal2("none"),reason:Literals(["other-source","not-a-version","same-version"])})]),DependencyChange=Union2([Struct({kind:Literal2("changed"),name:DependencyName,before:WrittenVersion,after:WrittenVersion,lookup:DependencyLookup}),Struct({kind:Literal2("added"),name:DependencyName,after:WrittenVersion}),Struct({kind:Literal2("removed"),name:DependencyName,before:WrittenVersion})]);var DependencyFileChanges=Union2([Struct({kind:Literal2("read"),path:RepoPath,format:DependencyFormat,ecosystem:DependencyEcosystem,changes:ArraySchema(DependencyChange),omitted:Int.check(isGreaterThanOrEqualTo2(0))}),Struct({kind:Literal2("unread"),path:RepoPath,format:DependencyFormat,ecosystem:DependencyEcosystem,message:String4})]);var SourceSpan=Struct({startByte:ByteOffset,byteLength:ByteLength,startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((span)=>span.endLine>=span.startLine&&(span.byteLength>0||span.endLine===span.startLine)&&span.startByte+span.byteLength<=Number.MAX_SAFE_INTEGER)),SourcePosition=Struct({path:RepoPath,byteOffset:ByteOffset,line:LineNumber}),SourceSelection=Struct({path:RepoPath,span:SourceSpan,text:String4}).check(makeFilter2((selection)=>{let extraLines=(selection.text.match(/\n/g)??[]).length-(selection.text.endsWith(`
|
|
20
|
+
`)?1:0);return!/[\uD800-\uDFFF]/u.test(selection.text)&&new TextEncoder().encode(selection.text).length===selection.span.byteLength&&selection.span.endLine===selection.span.startLine+extraLines})),Language=Literals(["ruby","javascript","typescript","tsx","json","jsonc","yaml","erb","shell","markdown","python","go","rust","java","css","toml","html","unknown"]),FileRole=Literals(["business","infrastructure","tests","documentation","configuration","dependencies","generated"]),ChangeKind=Literals(["added","deleted","modified","renamed"]),sourceText=String4.check(makeFilter2((value)=>!/[\uD800-\uDFFF]/u.test(value))),binaryBlobs={beforeBlob:optional2(NullOr(GitRevision)),afterBlob:optional2(NullOr(GitRevision))},InputFile=Union2([Struct({kind:Literal2("added"),path:RepoPath,after:sourceText}),Struct({kind:Literal2("deleted"),path:RepoPath,before:sourceText}),Struct({kind:Literal2("modified"),path:RepoPath,before:sourceText,after:sourceText}),Struct({kind:Literal2("renamed"),path:RepoPath,beforePath:RepoPath,before:sourceText,after:sourceText}),Struct({kind:Literal2("binary"),path:RepoPath,beforePath:NullOr(RepoPath),change:ChangeKind,media:Literals(["binary","svg","symlink","submodule"]),beforeHash:NullOr(Fingerprint),afterHash:NullOr(Fingerprint),beforeBytes:ByteLength,afterBytes:ByteLength,...binaryBlobs}),Struct({kind:Literal2("metadata"),path:RepoPath,beforeMode:String4,afterMode:String4})]),packagesField={packages:optional2(ArraySchema(ProjectPackage))},AnalyzeInput=Struct({repositoryId:RepositoryId,baseRevision:GitRevision,headRevision:GitRevision,files:ArraySchema(InputFile),...packagesField}).check(makeFilter2((input)=>{let keys=input.files.map((file)=>`${file.kind==="metadata"?"metadata":"content"}:${file.path}`);return new Set(keys).size===keys.length})),Coverage=Union2([Struct({kind:Literal2("parsed"),language:Language}),Struct({kind:Literal2("fallback"),reason:String4})]),AnalyzedFile=Union2([Struct({kind:Literal2("text"),id:FileId,path:RepoPath,previousPath:NullOr(RepoPath),change:ChangeKind,before:NullOr(String4),after:NullOr(String4),language:Language,role:FileRole,coverage:Coverage,occurrenceIds:ArraySchema(OccurrenceId),routes:optional2(FileRoutes),directives:optional2(FileDirectives)}),Struct({kind:Literal2("binary"),id:FileId,path:RepoPath,previousPath:NullOr(RepoPath),change:ChangeKind,media:Literals(["binary","svg","symlink","submodule"]),beforeHash:NullOr(Fingerprint),afterHash:NullOr(Fingerprint),beforeBytes:ByteLength,afterBytes:ByteLength,...binaryBlobs,role:FileRole,occurrenceIds:ArraySchema(OccurrenceId)}),Struct({kind:Literal2("metadata"),id:FileId,path:RepoPath,beforeMode:String4,afterMode:String4,role:FileRole,occurrenceIds:ArraySchema(OccurrenceId)})]),EditCategory=Literals(["presentation","identifier","content","structure","comment","literal","metadata"]),occurrenceFields={id:OccurrenceId,snapshotId:SnapshotId,fileId:FileId,category:EditCategory,label:String4,fingerprint:Fingerprint},EditOccurrence=Union2([Struct({...occurrenceFields,kind:Literal2("added"),after:SourceSelection,beforePosition:SourcePosition}),Struct({...occurrenceFields,kind:Literal2("removed"),before:SourceSelection,afterPosition:SourcePosition}),Struct({...occurrenceFields,kind:Literal2("replaced"),before:SourceSelection,after:SourceSelection}),Struct({...occurrenceFields,kind:Literal2("metadata"),path:RepoPath,before:sourceText,after:sourceText})]),EditKind=Literals(["replacement","insertion","deletion","metadata"]);var TextOffset=Int.check(isGreaterThanOrEqualTo2(0)).pipe(brand("TextOffset")),TextRange=Struct({start:TextOffset,end:TextOffset}).check(makeFilter2((range)=>range.end>range.start)),ExampleExcerpt=Struct({source:SourceSelection,highlights:ArraySchema(TextRange)}).check(makeFilter2((excerpt)=>excerpt.highlights.every((range,index)=>range.end<=excerpt.source.text.length&&(index===0||(excerpt.highlights[index-1]?.end??0)<=range.start)))),ShapeExample=Struct({occurrenceId:OccurrenceId,before:ExampleExcerpt,after:ExampleExcerpt}),ShapeContext=Literals(["call","definition","parameter","property-key","import","type","variable","reference","code","string","symbol","comment","regex","documentation","data","template","text"]),NamingConvention=Literals(["snake","camel","pascal","screaming","lower","other"]),ShapeKey=String4.check(isPattern2(/^[a-z]+(?:-[a-z]+)*(?::[a-z]+)?$/)).pipe(brand("ShapeKey")),ReplacementVariant=Struct({beforeText:String4,afterText:String4,convention:NamingConvention}),ReplacementShape=Struct({key:ShapeKey,context:ShapeContext,convention:NamingConvention,label:String4,unusual:Boolean3,reason:NullOr(String4),occurrenceIds:NonEmptyArray(OccurrenceId),fileCount:Int.check(isGreaterThanOrEqualTo2(1)),example:ShapeExample}).check(makeFilter2((shape)=>shape.occurrenceIds.includes(shape.example.occurrenceId))),groupFields={id:GroupId,label:String4,occurrenceIds:ArraySchema(OccurrenceId),explanation:String4},ReplacementGroup=Struct({...groupFields,kind:Literal2("replacement"),beforeText:String4,afterText:String4,variants:NonEmptyArray(ReplacementVariant),shapes:NonEmptyArray(ReplacementShape)}).check(makeFilter2((group)=>{let members=new Set(group.occurrenceIds),shaped=group.shapes.flatMap((shape)=>shape.occurrenceIds);return members.size===group.occurrenceIds.length&&shaped.length===members.size&&new Set(shaped).size===shaped.length&&shaped.every((id)=>members.has(id))})),ReviewGroup=Union2([Struct({...groupFields,kind:Literal2("role"),role:FileRole}),Struct({...groupFields,kind:Literal2("feature"),feature:String4,within:optional2(String4)}),ReplacementGroup,Struct({...groupFields,kind:Literal2("move"),origin:SourceSelection,destination:SourceSelection,match:Literals(["exact","edited"]),similarity:Similarity}),Struct({...groupFields,kind:Literal2("copy"),origin:SourceSelection,destination:SourceSelection,match:Literal2("exact")}),Struct({...groupFields,kind:Literal2("addition"),text:String4,fileCount:Int.check(isGreaterThanOrEqualTo2(1))})]),SourceEntity=Struct({id:EntityId,fileId:FileId,side:Literals(["before","after"]),name:String4,kind:String4,source:SourceSelection,fingerprint:Fingerprint}),AnalysisLimitation=Struct({path:NullOr(RepoPath),code:Literals(["unsupported-language","parse-error","size-limit","diff-limit","binary","oversized-svg","ambiguous-move","work-limit"]),message:String4}),CodeLines=Struct({path:RepoPath,startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((lines)=>lines.endLine>=lines.startLine)),SameAsRemoved=Struct({at:CodeLines,removedFrom:NonEmptyArray(CodeLines),elsewhere:Int.check(isGreaterThanOrEqualTo2(0))}),AnalyzerRevision=String4.check(isPattern2(/^tree-sitter-v[1-9][0-9]*$/)).pipe(brand("AnalyzerRevision")),AnalysisSnapshot=Struct({analyzerRevision:AnalyzerRevision,id:SnapshotId,repositoryId:RepositoryId,baseRevision:GitRevision,headRevision:GitRevision,files:ArraySchema(AnalyzedFile),occurrences:ArraySchema(EditOccurrence),groups:ArraySchema(ReviewGroup),entities:ArraySchema(SourceEntity),limitations:ArraySchema(AnalysisLimitation),localeChanges:optional2(ArraySchema(LocaleFileChanges)),...packagesField,dependencyChanges:optional2(ArraySchema(DependencyFileChanges)),sameAsRemoved:optional2(ArraySchema(SameAsRemoved))});var offset=decodeUnknownSync(ByteOffset),length=decodeUnknownSync(ByteLength),line=decodeUnknownSync(LineNumber);var strictUtf8=new TextDecoder("utf-8",{fatal:!0});var QueryText=String4.check(isMinLength(1),isMaxLength(1000),makeFilter2((text)=>text.trim().length>0)).pipe(brand("EvidenceQueryText")),ResultLimit=Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(100)).pipe(brand("EvidenceResultLimit")),EvidenceQuery=Union2([Struct({kind:Literal2("search"),text:QueryText,limit:ResultLimit,side:optional2(Literals(["before","after"]))}),Struct({kind:Literal2("related"),occurrenceId:OccurrenceId,limit:ResultLimit})]),side=Literals(["before","after"]),EvidenceHit=Union2([Struct({kind:Literal2("declaration"),entityId:EntityId,name:String4,side,source:SourceSelection,endLine:LineNumber,reason:String4}),Struct({kind:Literal2("reference-candidate"),side,source:SourceSelection,matchedTerms:ArraySchema(String4),reason:String4})]),EvidenceTarget=Union2([Struct({kind:Literal2("indexed-file"),path:RepoPath}),Struct({kind:Literal2("unresolved"),name:String4}),Struct({kind:Literal2("route"),name:String4})]),EvidenceRelationship=Struct({kind:Literals(["import","test-pair","route","reference-candidate"]),basis:Literals(["syntax","lexical","convention"]),side,source:SourceSelection,target:EvidenceTarget,explanation:String4}),count=Int.check(isGreaterThanOrEqualTo2(0)),EvidenceResult=Struct({snapshotId:SnapshotId,query:EvidenceQuery,hits:ArraySchema(EvidenceHit),relationships:ArraySchema(EvidenceRelationship),coverage:Struct({scope:Literal2("changed-files"),parsedFiles:count,fallbackFiles:count,nonTextFiles:count,capped:Boolean3}),notes:ArraySchema(String4)});var PLACEHOLDER=/\{([a-z]+)\}/gu,placeholdersOf=(template)=>Array.from(template.matchAll(PLACEHOLDER),(match)=>match[1]??""),pairTemplateProblem=(template)=>{if(template.length===0)return"Write a path from the repository's root, such as src/{path}.ts.";if(template.length>256)return"Use at most 256 characters.";if(template.trim()!==template)return"Leave out spaces at either end.";if(template.startsWith("/"))return"Start from the repository's root, without a leading /.";if(/[\\\u0000-\u001f\u007f]/u.test(template))return"Use / between folders, and no control characters.";if(/[*?[\]]/u.test(template))return"Use {name} or {path} for the part both files share, not wildcards.";if(template.split("/").some((part)=>part===""||part==="."||part===".."))return"Name each folder: no empty, . or .. parts.";if(/[{}]/u.test(template.replace(PLACEHOLDER,"")))return"Write a placeholder as a lowercase word in braces, such as {name} or {path}.";let names=placeholdersOf(template);if(names.length===0)return"Use {name} or {path} for the part both files share.";if(new Set(names).size!==names.length)return"Use each placeholder once.";if(template.includes("}{"))return"Put some text between two placeholders.";return null},pairRuleProblem=(source,test)=>{let problem=pairTemplateProblem(source)??pairTemplateProblem(test);if(problem!==null)return problem;if(source===test)return"The file and its test need different paths.";let left=[...placeholdersOf(source)].sort().join(","),right=[...placeholdersOf(test)].sort().join(",");return left===right?null:"Use the same placeholders in both paths, so each file names the other."},TestPairRuleId=String4.check(isPattern2(/^[a-z][a-z0-9._-]{0,63}$/u)).pipe(brand("TestPairRuleId")),PairTemplate=String4.check(makeFilter2((template)=>pairTemplateProblem(template)===null)).pipe(brand("PairTemplate")),TestPairRule=Struct({id:TestPairRuleId,name:String4.check(isMinLength(1),isMaxLength(256)),source:PairTemplate,test:PairTemplate}).check(makeFilter2((rule)=>pairRuleProblem(rule.source,rule.test)===null));var JS_TEST_FOLDERS=["test","tests","__tests__","spec"],JS_HELPER_FOLDERS=new Set([...JS_TEST_FOLDERS,"__mocks__","__fixtures__","fixtures","node_modules"]);var CertainTestPair=Struct({path:RepoPath,kind:Literals(["test","source"]),target:RepoPath});var key=String4.check(isPattern2(/^[a-z][a-z0-9._-]{0,63}$/)),label=String4.check(isMinLength(1),isMaxLength(256)),ProfileId=key.pipe(brand("ProfileId")),ProfileRuleId=key.pipe(brand("ProfileRuleId")),ComponentId=key.pipe(brand("ComponentId")),FeatureName=String4.check(isMinLength(1),isMaxLength(4096)).pipe(brand("FeatureName")),Framework=Literals(["rails","next","expo","node"]),PathPattern=String4.check(isMinLength(1),isMaxLength(256),makeFilter2((pattern)=>!pattern.startsWith("/")&&!/[\\[\]{}()!\u0000-\u001f\u007f]/u.test(pattern)&&pattern.split("/").every((part)=>part!==""&&part!=="."&&part!==".."&&(!part.includes("**")||part==="**")))).pipe(brand("PathPattern")),matcher=Struct({include:ArraySchema(PathPattern).check(isMinLength(1),isMaxLength(100)),exclude:ArraySchema(PathPattern).check(isMaxLength(100))}),origin=Union2([Struct({kind:Literal2("human"),note:label}),Struct({kind:Literal2("agent-proposal"),note:label}),Struct({kind:Literal2("accepted-agent"),note:label})]),dependency=Struct({path:RepoPath,contentFingerprint:Fingerprint}),ruleFields={id:ProfileRuleId,name:label,priority:Int.check(isGreaterThanOrEqualTo2(-1000),isLessThanOrEqualTo2(1000)),match:matcher,origin,dependencies:ArraySchema(dependency).check(isMaxLength(100))},ProfileRule=Union2([Struct({...ruleFields,kind:Literal2("role"),role:FileRole}),Struct({...ruleFields,kind:Literal2("feature"),feature:FeatureName}),Struct({...ruleFields,kind:Literal2("component"),componentId:ComponentId})]),ProjectComponent=Struct({id:ComponentId,label,description:String4.check(isMaxLength(2000))}),BoundaryPolicy=Struct({from:ComponentId,to:ComponentId,policy:Literals(["allow","forbid"]),reason:label}),profileFields={id:ProfileId,name:label,frameworks:ArraySchema(Framework),components:ArraySchema(ProjectComponent).check(isMaxLength(100)),rules:ArraySchema(ProfileRule).check(isMaxLength(1000)),boundaries:ArraySchema(BoundaryPolicy).check(isMaxLength(1000)),testPairs:ArraySchema(TestPairRule).check(isMaxLength(100)).pipe(withDecodingDefaultKey(succeed5([])))},ProjectProfile=Struct(profileFields).check(makeFilter2((profile)=>{if(new Set(profile.frameworks).size!==profile.frameworks.length||new Set(profile.rules.map((rule)=>rule.id)).size!==profile.rules.length||new Set(profile.components.map((component)=>component.id)).size!==profile.components.length||new Set(profile.testPairs.map((rule)=>rule.id)).size!==profile.testPairs.length)return!1;if(profile.components.some((component)=>frameworkComponents(profile.frameworks).some((preset)=>preset.id===component.id)))return!1;let ids=new Set([...profile.components.map((component)=>String(component.id)),...frameworkComponents(profile.frameworks).map((component)=>String(component.id))]);return profile.rules.every((rule)=>rule.kind!=="component"||ids.has(rule.componentId))&&profile.boundaries.every((boundary)=>ids.has(boundary.from)&&ids.has(boundary.to))&&new Set(profile.boundaries.map((boundary)=>`${boundary.from}:${boundary.to}`)).size===profile.boundaries.length})),RuleEvaluation=Struct({ruleId:ProfileRuleId,state:Literals(["active","proposed","stale","unverified"]),explanation:String4}),InferredFeatureRef=Struct({feature:FeatureName,label:String4.check(isMinLength(1))}),ProfileFile=Struct({fileId:FileId,path:RepoPath,role:FileRole,feature:FeatureName,inferred:ArraySchema(InferredFeatureRef),components:ArraySchema(ComponentId),appliedRuleIds:ArraySchema(ProfileRuleId),conflicts:ArraySchema(String4),explanation:ArraySchema(String4)}),BoundaryObservation=Struct({from:ComponentId,to:ComponentId,declaredPolicy:Literals(["allow","forbid","unspecified"]),relationship:EvidenceRelationship,explanation:String4}),ProfileProjection=Struct({snapshotId:SnapshotId,profileFingerprint:Fingerprint,profile:ProjectProfile,files:ArraySchema(ProfileFile),components:ArraySchema(ProjectComponent),ruleEvaluations:ArraySchema(RuleEvaluation),boundaryObservations:ArraySchema(BoundaryObservation),notes:ArraySchema(String4)}),component=(id,title)=>decodeUnknownSync(ProjectComponent)({id,label:title,description:"Framework path convention; membership does not establish runtime behavior."}),frameworkRules=[...["models","controllers","services","jobs","policies","serializers","views"].map((name)=>({framework:"rails",patterns:[`**/app/${name}/**`],role:"business",component:component(`rails-${name}`,`Rails ${name}`)})),{framework:"rails",patterns:["**/db/migrate/**"],role:"infrastructure",component:component("rails-migrations","Rails migrations")},{framework:"rails",patterns:["**/config/routes.rb"],role:"business",component:component("rails-routes","Rails routes")},{framework:"next",patterns:["**/app/**/page.tsx","**/app/**/page.jsx","**/app/**/route.ts","**/app/**/route.js","**/pages/**"],role:"business",component:component("next-routes","Next.js route entries")},{framework:"next",patterns:["**/server/**","**/*.server.ts","**/*.server.tsx"],role:"business",component:component("next-server","Next.js server convention")},{framework:"next",patterns:["**/components/**","**/*.client.tsx"],role:"business",component:component("next-ui","Next.js UI convention")},{framework:"expo",patterns:["**/app/**/*.tsx","**/app/**/*.jsx"],role:"business",component:component("expo-routes","Expo Router entries")},{framework:"expo",patterns:["**/*.native.ts","**/*.native.tsx","**/*.ios.tsx","**/*.android.tsx"],role:"business",component:component("expo-platform","Expo platform code")},{framework:"node",patterns:["**/server/**","**/routes/**"],role:"business",component:component("node-server","Node.js server convention")}];function frameworkComponents(frameworks){return frameworkRules.filter((rule)=>frameworks.includes(rule.framework)).map((rule)=>rule.component)}var ProfileSuggestion=Struct({profile:ProjectProfile,evidence:ArraySchema(Struct({framework:Framework,path:RepoPath,reason:String4})),notes:ArraySchema(String4)});var RepositoryIndexId=String4.check(isPattern2(/^index_[a-f0-9]{64}$/)).pipe(brand("RepositoryIndexId")),count2=Int.check(isGreaterThanOrEqualTo2(0)),INDEX_POLICY_LIMITS={maxFiles:20000,maxFileBytes:2097152,maxTotalBytes:67108864},RepositoryIndexPolicy=Struct({maxFiles:Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxFiles)),maxFileBytes:ByteLength.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxFileBytes)),maxLocaleFileBytes:ByteLength.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxFileBytes)),maxTotalBytes:ByteLength.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(INDEX_POLICY_LIMITS.maxTotalBytes)),include:ArraySchema(PathPattern),exclude:ArraySchema(PathPattern)}),DEFAULT_INDEX_POLICY=decodeUnknownSync(RepositoryIndexPolicy)({maxFiles:1e4,maxFileBytes:262144,maxLocaleFileBytes:1048576,maxTotalBytes:33554432,include:[],exclude:["**/node_modules/**","**/vendor/**","**/dist/**","**/build/**","**/.next/**","**/coverage/**","**/*.min.js","**/*.lock","**/package-lock.json"]}),maxFileBytesFor=(policy,path)=>isLocalePath(path)?Math.max(policy.maxFileBytes,policy.maxLocaleFileBytes):policy.maxFileBytes;var GitBlobId=String4.check(isPattern2(/^[a-f0-9]{40}$/)).pipe(brand("GitBlobId")),IndexedSource=Struct({id:FileId,path:RepoPath,blob:GitBlobId,text:String4,contentFingerprint:Fingerprint,language:Language,role:FileRole,coverage:Coverage}),IndexedDeclaration=Struct({id:EntityId,fileId:FileId,name:String4,kind:String4,source:SourceSelection,fingerprint:Fingerprint}),IndexOmission=Struct({reason:IndexOmissionReason,count:count2,examples:ArraySchema(RepoPath).check(isMaxLength(10))}),RepositoryIndex=Struct({id:RepositoryIndexId,repositoryId:RepositoryId,revision:GitRevision,analyzerRevision:AnalyzerRevision,policy:RepositoryIndexPolicy,files:ArraySchema(IndexedSource),declarations:ArraySchema(IndexedDeclaration),omissions:ArraySchema(IndexOmission),coverage:Struct({treeFiles:count2,indexedFiles:count2,indexedBytes:ByteLength,parsedFiles:count2,fallbackFiles:count2,omittedFiles:count2})}),RepositoryOutline=Struct({indexId:RepositoryIndexId,repositoryId:RepositoryId,revision:GitRevision,files:ArraySchema(Struct({path:RepoPath,role:FileRole,contentFingerprint:Fingerprint})),manifests:ArraySchema(Struct({path:RepoPath,text:String4}))}),RepositoryIndexInput=Struct({repositoryId:RepositoryId,revision:GitRevision,policy:RepositoryIndexPolicy,treeFiles:count2,files:ArraySchema(Struct({path:RepoPath,text:String4,bytes:ByteLength})),omissions:ArraySchema(Struct({path:RepoPath,reason:IndexOmission.fields.reason}))}).check(makeFilter2((input)=>{if(input.files.length>input.policy.maxFiles||input.files.length+input.omissions.length!==input.treeFiles)return!1;let paths=[...input.files.map((file)=>file.path),...input.omissions.map((file)=>file.path)];if(new Set(paths).size!==paths.length)return!1;if(input.files.reduce((sum,file)=>sum+file.text.length,0)>input.policy.maxTotalBytes||input.files.reduce((sum,file)=>sum+file.bytes,0)>input.policy.maxTotalBytes)return!1;return input.files.every((file)=>file.bytes<=maxFileBytesFor(input.policy,file.path)&&file.text.length<=maxFileBytesFor(input.policy,file.path)&&!/[\uD800-\uDFFF]/u.test(file.text)&&new TextEncoder().encode(file.text).length===file.bytes)}));var RepositoryEvidenceQuery=Struct({text:String4.check(isMinLength(1),isMaxLength(1000),makeFilter2((text)=>text.trim().length>0)),limit:Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(100))}),RepositoryEvidenceResult=Struct({indexId:RepositoryIndexId,revision:GitRevision,query:RepositoryEvidenceQuery,hits:ArraySchema(EvidenceHit),relationships:ArraySchema(EvidenceRelationship),coverage:Struct({scope:Literal2("repository"),indexedFiles:Int,omittedFiles:Int,capped:Boolean3}),notes:ArraySchema(String4)});var count3=Int.check(isGreaterThanOrEqualTo2(0)),RepositorySummary=Struct({indexId:RepositoryIndexId,revision:GitRevision,languages:ArraySchema(Struct({language:Language,fileCount:count3})),roles:ArraySchema(Struct({role:FileRole,fileCount:count3})),declarationCount:count3,declarationExamples:ArraySchema(IndexedDeclaration).check(isMaxLength(20)),omissions:ArraySchema(IndexOmission),notes:ArraySchema(String4),localeFiles:optional2(count3),localeRoots:optional2(ArraySchema(LocaleRoot))});var GitHubViewedReason=Literals(["not-connected","needs-sign-in","earlier-head","app-permission","no-permission","pull-gone","unavailable"]),GitHubViewedSync=Union2([Struct({kind:Literal2("synced"),version:Version}),Struct({kind:Literal2("not-synced"),reason:GitHubViewedReason,message:NonEmptyString})]),GitHubViewedResponse=Struct({snapshotId:SnapshotId,sync:GitHubViewedSync});var GitHubReviewEvent=Literals(["COMMENT","APPROVE","REQUEST_CHANGES"]),ReviewSummaryBody=String4.check(isMaxLength(60000)),ReviewDraftSelection=Struct({commentId:CommentId,expectedVersion:CommentVersion}),maxReviewDrafts=100,SubmitGitHubReview=Struct({publicationId:PublicationId,expectedSnapshotId:SnapshotId,event:GitHubReviewEvent,body:ReviewSummaryBody,drafts:optional2(ArraySchema(ReviewDraftSelection).check(isMaxLength(maxReviewDrafts)))}).check(makeFilter2((value)=>value.event==="APPROVE"||value.body.trim().length>0||value.event==="COMMENT"&&(value.drafts?.length??0)>0),makeFilter2((value)=>new Set((value.drafts??[]).map((draft)=>draft.commentId)).size===(value.drafts??[]).length)),shared={publicationId:PublicationId,reviewerId:ReviewerId,event:GitHubReviewEvent,body:ReviewSummaryBody,createdAt:Timestamp,commentIds:optional2(ArraySchema(CommentId))},GitHubReviewSubmission=Union2([Struct({...shared,kind:Literal2("publishing")}),Struct({...shared,kind:Literal2("uncertain"),reason:NonEmptyString}),Struct({...shared,kind:Literal2("rejected"),reason:NonEmptyString}),Struct({...shared,kind:Literal2("published"),remoteId:GitHubReviewId,url:HttpsUrl}),Struct({...shared,kind:Literal2("abandoned"),reason:NonEmptyString,abandonedAt:Timestamp})]),GitHubReviewSubmissions=ArraySchema(GitHubReviewSubmission),PublishedReviewComment=Struct({commentId:CommentId,remoteId:GitHubCommentId,url:HttpsUrl}),GitHubReviewOutcome=Union2([Struct({kind:Literal2("confirmed"),remoteId:GitHubReviewId,url:HttpsUrl,comments:optional2(ArraySchema(PublishedReviewComment))}),Struct({kind:Literal2("uncertain"),reason:NonEmptyString}),Struct({kind:Literal2("confirmed-not-published")})]),AbandonGitHubReview=Struct({publicationId:PublicationId,expectedSnapshotId:SnapshotId}),AbandonPublication=Struct({commentId:CommentId,publicationId:PublicationId,expectedSnapshotId:SnapshotId});var ReviewRefusal=Union2([Struct({kind:Literal2("review-not-found")}),Struct({kind:Literal2("wrong-reviewer")}),Struct({kind:Literal2("command-id-reused")}),Struct({kind:Literal2("comment-id-taken")}),Struct({kind:Literal2("comment-not-found")}),Struct({kind:Literal2("proposal-not-found")}),Struct({kind:Literal2("finding-not-found")}),Struct({kind:Literal2("finding-settled"),state:Literals(["open","drafted","dismissed"])}),Struct({kind:Literal2("too-many-findings"),limit:Int}),Struct({kind:Literal2("wrong-snapshot")}),Struct({kind:Literal2("comment-rule"),error:CommentError}),Struct({kind:Literal2("submission-unsupported")}),Struct({kind:Literal2("publication-id-taken")}),Struct({kind:Literal2("unresolved-submission")}),Struct({kind:Literal2("selected-draft"),problem:Literals(["missing","publishing","not-a-line-comment","changed"])}),Struct({kind:Literal2("still-publishing"),subject:Literals(["submission","comment"])}),Struct({kind:Literal2("submission-not-abandonable")}),Struct({kind:Literal2("submission-not-found")}),Struct({kind:Literal2("comment-in-submission")}),Struct({kind:Literal2("inconsistent"),detail:String4})]);var COMPANION_DEFAULT_ORIGIN="https://diffclarity.com",companionCommand=(verb,origin)=>`npx @diffclarity/companion@latest ${verb}${origin===COMPANION_DEFAULT_ORIGIN?"":` --origin ${origin}`}`,COMPANION_CLIENT_NAME="DiffClarity companion",companionClientName=(machine)=>{let name=machine.trim().replace(/\.local$/u,"").replace(/[^\w .'-]/gu,"").slice(0,60).trim();return name.length===0?COMPANION_CLIENT_NAME:`${COMPANION_CLIENT_NAME} on ${name}`},GRANT_WORKSPACE_FIELD="diffclarity_workspace",GRANT_WORKSPACE_NAME_FIELD="diffclarity_workspace_name",GRANT_WORKSPACE_PERSONAL_FIELD="diffclarity_workspace_personal",SEVERAL_WORKSPACES_PARAM="diffclarity_workspaces",SEVERAL_WORKSPACES_VALUE="several",GRANT_MORE_CODES_PARAM="diffclarity_code";var CompanionAgentKind=Literals(["claude","codex","opencode"]),COMPANION_AGENT_LABELS={claude:"Claude Code",codex:"Codex",opencode:"opencode"},ShortText=String4.check(isMaxLength(120)),AgentModelId=String4.check(isPattern2(/^[A-Za-z0-9][A-Za-z0-9._/:@+-]{0,159}$/)).pipe(brand("AgentModelId")),AgentEffort=String4.check(isPattern2(/^[a-z][a-z0-9-]{0,31}$/)).pipe(brand("AgentEffort")),Efforts=ArraySchema(AgentEffort).check(isMaxLength(12)),AgentModel=Struct({id:AgentModelId,label:ShortText,efforts:Efforts}),CompanionAgent=Struct({kind:CompanionAgentKind,version:ShortText,models:ArraySchema(AgentModel).check(isMaxLength(1000)),efforts:Efforts}),KeyProvider=Literals(["anthropic","openai"]);var AssistantAgentKind=Literals([...CompanionAgentKind.literals,...KeyProvider.literals]),ASSISTANT_AGENT_LABELS={...COMPANION_AGENT_LABELS,anthropic:"Claude API",openai:"OpenAI API"};var AssistantAgent=Struct({kind:AssistantAgentKind,version:ShortText,models:ArraySchema(AgentModel).check(isMaxLength(1000)),efforts:Efforts}),effortsFor=(agent,model)=>model===void 0?agent.efforts:agent.models.find((candidate)=>candidate.id===model)?.efforts??[],isOffered=(agent,model,effort)=>(model===void 0||agent.models.some((candidate)=>candidate.id===model))&&(effort===void 0||effortsFor(agent,model).includes(effort)),efforts=(...names)=>names.map((name)=>decodeUnknownSync(AgentEffort)(name)),keyModel=(id,label,effortNames)=>({id:decodeUnknownSync(AgentModelId)(id),label,efforts:efforts(...effortNames)}),ALL_EFFORTS=["low","medium","high","xhigh","max"],KEY_AGENTS={anthropic:{defaultModel:decodeUnknownSync(AgentModelId)("claude-opus-5-5"),defaultEffort:decodeUnknownSync(AgentEffort)("high"),models:[keyModel("claude-opus-5-5","Claude Opus 5.5",ALL_EFFORTS),keyModel("claude-sonnet-5-5","Claude Sonnet 5.5",ALL_EFFORTS),keyModel("claude-haiku-5-5","Claude Haiku 5.5",ALL_EFFORTS),keyModel("claude-fable-5-1","Claude Fable 5.1",ALL_EFFORTS)]},openai:{defaultModel:decodeUnknownSync(AgentModelId)("gpt-6-astra"),defaultEffort:decodeUnknownSync(AgentEffort)("high"),models:[keyModel("gpt-6-astra","GPT-6 Astra",ALL_EFFORTS),keyModel("gpt-6.1-sol","GPT-6.1 Sol",ALL_EFFORTS),keyModel("gpt-6.1-terra","GPT-6.1 Terra",ALL_EFFORTS),keyModel("gpt-6-luna","GPT-6 Luna",ALL_EFFORTS)]}};var CompanionHello=Struct({version:ShortText,agents:ArraySchema(CompanionAgent).check(isMaxLength(3))}),CompanionWorkspace=Struct({id:OrganizationId,name:NonEmptyString.check(isMaxLength(200)),personal:Boolean3}),CompanionElsewhere=Struct({workspace:CompanionWorkspace,agents:ArraySchema(CompanionAgent)}),CompanionStatus=Union2([Struct({kind:Literal2("connected"),agents:ArraySchema(CompanionAgent),connectedAt:Timestamp}),Struct({kind:Literal2("not-connected"),elsewhere:optional2(ArraySchema(CompanionElsewhere).check(isMaxLength(3)))})]),AgentSessionId=String4.check(isPattern2(/^[A-Za-z0-9._:-]{1,128}$/)).pipe(brand("AgentSessionId")),CompanionRunId=String4.check(isPattern2(/^run_[a-f0-9]{32}$/)).pipe(brand("CompanionRunId")),MAX_ASSISTANT_QUESTION=8000,AssistantQuestion=String4.check(isMinLength(1),isMaxLength(MAX_ASSISTANT_QUESTION)),AskedLines=Struct({startLine:LineNumber,endLine:LineNumber}).check(makeFilter2((lines)=>lines.endLine>=lines.startLine)),AskedEdit=Struct({occurrenceId:OccurrenceId,base:optional2(AskedLines),head:optional2(AskedLines)}),MAX_ASKED_EDITS=100,AskedFile=Struct({path:RepoPath,fileId:FileId,editCount:Int.check(isGreaterThanOrEqualTo2(0)),edits:ArraySchema(AskedEdit).check(isMaxLength(MAX_ASKED_EDITS))}),MAX_MENTIONED_FILES=5,MAX_ASKED_EXACT_EDITS=200;var MAX_ASKED_EDIT_TEXT=1200,AskedEditText=Struct({text:String4.check(isMaxLength(MAX_ASKED_EDIT_TEXT)),isCut:Boolean3}),AskedExactEdit=Struct({...AskedEdit.fields,path:RepoPath,fileId:FileId,label:String4.check(isMaxLength(120)),before:optional2(AskedEditText),after:optional2(AskedEditText)}),AskSubject=Union2([Struct({kind:Literal2("edits"),label:String4.check(isMaxLength(256)),edits:ArraySchema(AskedExactEdit).check(isMinLength(1),isMaxLength(MAX_ASKED_EXACT_EDITS))}),Struct({kind:Literal2("selection"),path:RepoPath,side:Literals(["base","head"]),startLine:LineNumber,endLine:LineNumber,text:String4.check(isMinLength(1),isMaxLength(4000))}),Struct({kind:Literal2("file"),...AskedFile.fields})]),QuestionFields={model:optional2(AgentModelId),effort:optional2(AgentEffort),question:AssistantQuestion,subject:optional2(AskSubject),mentions:optional2(ArraySchema(AskedFile).check(isMaxLength(MAX_MENTIONED_FILES)))},CompanionQuestion=Struct({agent:CompanionAgentKind,...QuestionFields,resumeId:optional2(AgentSessionId)}),MAX_KEY_HISTORY=6,MAX_KEY_HISTORY_ANSWER=8000,AssistantHistoryTurn=Struct({question:AssistantQuestion,answer:String4.check(isMaxLength(MAX_KEY_HISTORY_ANSWER))}),KeyQuestion=Struct({agent:KeyProvider,...QuestionFields,history:optional2(ArraySchema(AssistantHistoryTurn).check(isMaxLength(MAX_KEY_HISTORY)))}),AssistantRequest=Union2([CompanionQuestion,KeyQuestion]),CompanionRun=Struct({runId:CompanionRunId,snapshotId:SnapshotId,agent:CompanionAgentKind,model:optional2(AgentModelId),effort:optional2(AgentEffort),prompt:String4.check(isMaxLength(32000)),resumeId:optional2(AgentSessionId)}),ReviewProposal=Struct({occurrenceIds:ArraySchema(OccurrenceId).check(isMinLength(1),isMaxLength(500)),reason:String4.check(isMinLength(1),isMaxLength(2000))}),ProposeReviewRequest=Struct({runId:CompanionRunId,...ReviewProposal.fields}),ProposeCommentEditRequest=Struct({commandId:CommandId,commentId:CommentId,baseVersion:CommentVersion,body:CommentBody,reason:optional2(ProposalReason),runId:optional2(CompanionRunId)}),CommentEditProposed=Struct({status:Literal2("awaiting-reviewer-approval"),proposalId:CommandId,commentId:CommentId,isInConversation:Boolean3,message:String4}),ReportFindingsRequest=Struct({commandId:CommandId,findings:FindingInputs,runId:optional2(CompanionRunId)}),FindingsReported=Struct({status:Literal2("awaiting-reviewer"),reportId:CommandId,findingIds:ArraySchema(FindingId),isInConversation:Boolean3,message:String4}),ReviewProposalEvent=Struct({kind:Literal2("proposal"),...ReviewProposal.fields}),CommentEditEvent=Struct({kind:Literal2("comment-edit"),proposalId:CommandId,commentId:CommentId}),FindingsEvent=Struct({kind:Literal2("findings"),reportId:CommandId,findingIds:ArraySchema(FindingId).check(isMaxLength(50))}),RunProposal=Union2([ReviewProposalEvent,CommentEditEvent,FindingsEvent]),AssistantEvent=Union2([Struct({kind:Literal2("session"),sessionId:AgentSessionId}),Struct({kind:Literal2("text"),text:String4}),Struct({kind:Literal2("tool"),name:String4.check(isMaxLength(200))}),Struct({kind:Literal2("answer"),text:String4}),ReviewProposalEvent,CommentEditEvent,FindingsEvent,Struct({kind:Literal2("failed"),message:NonEmptyString})]),AssistantStreamLine=Union2([Struct({kind:Literal2("started"),runId:CompanionRunId}),...AssistantEvent.members]),StopAssistantRequest=Struct({runId:CompanionRunId}),StopAssistantResponse=Struct({stopped:Boolean3}),CompanionReport=Struct({events:ArraySchema(AssistantEvent).check(isMaxLength(500)),isDone:Boolean3});var KeyHint=String4.check(isPattern2(/^[A-Za-z0-9_-]{4}$/)).pipe(brand("KeyHint")),SavedAssistantKey=Struct({provider:KeyProvider,hint:KeyHint,savedAt:Timestamp}),AssistantKeys=Union2([Struct({kind:Literal2("available"),keys:ArraySchema(SavedAssistantKey).check(isMaxLength(KeyProvider.literals.length))}),Struct({kind:Literal2("unavailable")})]);var ImportJobKey=String4.check(isPattern2(/^(?:sample(?::(?:media|folding|mechanical|routes|dependencies|translations|rails))?|pull:(?:github:[1-9][0-9]{0,15}|local:[a-z0-9][a-z0-9._-]{0,127}):[1-9][0-9]{0,15}|reanalysis:[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255})$/)).pipe(brand("ImportJobKey"));var SampleName=Literals(["media","folding","mechanical","routes","dependencies","translations","rails"]);var Count5=Int.check(isGreaterThanOrEqualTo2(0)),Message=String4,ImportFailure=Union2([Struct({reason:Literal2("sign-in-needed"),message:Message}),Struct({reason:Literal2("access-denied"),message:Message}),Struct({reason:Literal2("not-found"),message:Message}),Struct({reason:Literal2("rate-limited"),message:Message}),Struct({reason:Literal2("github-unavailable"),message:Message}),Struct({reason:Literal2("too-many-files"),message:Message,changedFiles:Count5,limit:Count5}),Struct({reason:Literal2("file-too-large"),message:Message,path:RepoPath,bytes:Count5,limit:Count5}),Struct({reason:Literal2("over-budget"),message:Message,bytes:Count5,limit:Count5}),Struct({reason:Literal2("listing-incomplete"),message:Message,listed:Count5,expected:Count5}),Struct({reason:Literal2("other-repository"),message:Message}),Struct({reason:Literal2("analysis-failed"),message:Message}),Struct({reason:Literal2("stalled"),message:Message}),Struct({reason:Literal2("expired"),message:Message}),Struct({reason:Literal2("error"),message:Message})]),ImportJobPhase=Literals(["reading-pull","listing-files","reading-files","reading-contents","analyzing"]),ImportJobState=Union2([Struct({kind:Literal2("running"),phase:ImportJobPhase,done:Count5,total:Count5,startedAt:Timestamp}),Struct({kind:Literal2("finished"),snapshotId:SnapshotId,finishedAt:Timestamp}),Struct({kind:Literal2("failed"),failure:ImportFailure,failedAt:Timestamp})]),ImportJobStatus=Struct({key:ImportJobKey,run:Count5,state:ImportJobState});var GitHubLocationMapping=Union2([Struct({kind:Literal2("mapped"),anchor:CommentAnchor.members[0],range:GitHubLineRange}),Struct({kind:Literal2("link-only"),reason:Literals(["file-level","location-unavailable","outdated","different-revision","unverified-context","base-unverified","renamed-file","file-unavailable","source-unavailable","hunk-mismatch"])})]);var RasterType=Literals(["image/png","image/jpeg","image/gif","image/webp"]);var PICTURE_FILE=/\.(?:png|jpe?g|gif|webp|svg)$/iu,UNSAFE_SEGMENT=/[\u0000-\u001f\u007f/\\]/u,MAX_FILE_SEGMENTS=64,MAX_FILE_LENGTH=1024,isRepositoryPictureFile=(segments)=>{let last=segments.at(-1);return segments.length>=2&&segments.length<=MAX_FILE_SEGMENTS&&last!==void 0&&PICTURE_FILE.test(last)&&segments.join("/").length<=MAX_FILE_LENGTH&&segments.every((segment)=>segment.length>0&&segment!=="."&&segment!==".."&&!UNSAFE_SEGMENT.test(segment))},RepositoryPictureFile=ArraySchema(String4).check(makeFilter2(isRepositoryPictureFile)).pipe(brand("RepositoryPictureFile"));var Count6=Int.check(isGreaterThanOrEqualTo2(0)),StackMemberProgress=Struct({snapshotId:SnapshotId,headRevision:GitRevision,upToDate:Boolean3,total:Count6,reviewed:Count6,revisit:Count6,pending:Count6}),ReviewStackMember=Struct({...GitHubStackMember.fields,baseRef:String4,isCurrent:Boolean3,review:NullOr(StackMemberProgress)}),ReviewStack=Union2([Struct({kind:Literal2("none")}),Struct({kind:Literal2("available"),number:GitHubStackNumber,baseRef:String4,open:Boolean3,members:ArraySchema(ReviewStackMember).check(isMinLength(1),isMaxLength(100))}),Struct({kind:Literal2("unavailable"),message:NonEmptyString})]);var count4=Int.check(isGreaterThanOrEqualTo2(0)),LeftoverSource=Struct({path:RepoPath,text:String4});var LeftoverRequest=Struct({groupId:GroupId,oldNames:ArraySchema(String4),headRevision:GitRevision,changedPaths:ArraySchema(RepoPath),changedFiles:ArraySchema(LeftoverSource),limit:optional2(Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(500)))}).check(makeFilter2((request)=>{let changed=new Set(request.changedPaths);return changed.size===request.changedPaths.length&&new Set(request.changedFiles.map((file)=>file.path)).size===request.changedFiles.length&&request.changedFiles.every((file)=>changed.has(file.path))})),LeftoverHit=Struct({path:RepoPath,line:LineNumber,name:String4,origin:Literals(["changed-file","repository-index"]),excerpt:ExampleExcerpt}),LeftoverIndexCoverage=Union2([Struct({kind:Literal2("absent")}),Struct({kind:Literal2("mismatched"),indexId:RepositoryIndexId,indexRevision:GitRevision}),Struct({kind:Literal2("searched"),indexId:RepositoryIndexId,revision:GitRevision,searchedFiles:count4,treeFiles:count4,omittedFiles:count4,omissions:ArraySchema(IndexOmission)})]),LeftoverCoverage=Struct({searchedNames:ArraySchema(String4),changedFiles:count4,index:LeftoverIndexCoverage,complete:Boolean3,capped:Boolean3,totalHits:count4,statement:String4}),LeftoverReport=Struct({groupId:GroupId,headRevision:GitRevision,hits:ArraySchema(LeftoverHit),coverage:LeftoverCoverage,notes:ArraySchema(String4)});var textOffset=decodeUnknownSync(TextOffset),lineNumber=decodeUnknownSync(LineNumber);var InstallationUrl=String4.check(isPattern2(/^https:\/\/github\.com\/apps\/[a-z0-9-]+\/installations\/new$/)),GitHubConnectionStatus=Union2([Struct({kind:Literal2("unconfigured"),message:String4}),Struct({kind:Literal2("disconnected"),installUrl:InstallationUrl}),Struct({kind:Literal2("connected"),login:NonEmptyString,installUrl:InstallationUrl}),Struct({kind:Literal2("reconnect"),login:NonEmptyString,installUrl:InstallationUrl,message:String4})]),GitHubInstallations=Struct({installations:ArraySchema(Struct({id:Number5.check(isInt(),isGreaterThan2(0)),account:NonEmptyString,repositories:Literals(["all","selected"]),canReview:Boolean3}))});var ConnectedAgentEntry=Struct({consentId:NonEmptyString,clientName:String4,referenceId:NullOr(String4),allowedAt:String4,lastUsedAt:NullOr(String4)});var McpGrant=Struct({kind:Literal2("granted"),userId:NonEmptyString,organizationId:OrganizationId,clientId:NonEmptyString,clientName:String4}),McpRefusal=Struct({kind:Literal2("refused"),reason:Literals(["invalid-token","wrong-resource","missing-scope","no-workspace","not-a-member","no-consent","unknown-client"])}),McpAccess=Union2([McpGrant,McpRefusal]);var LIVE_PING="ping",LIVE_PONG="pong";var COMPANION_SOCKET_PATH="/api/companion/socket",LiveEvent=Union2([Struct({kind:Literal2("import"),status:ImportJobStatus}),Struct({kind:Literal2("review-index"),snapshotId:SnapshotId}),Struct({kind:Literal2("project-index"),repositoryId:RepositoryId}),Struct({kind:Literal2("review-changed"),snapshotId:SnapshotId,what:Literals(["decisions","activity"]),version:Version}),Struct({kind:Literal2("companion"),status:CompanionStatus}),Struct({kind:Literal2("pull-head"),repositoryId:RepositoryId,number:PullRequestNumber,headRevision:GitRevision}),Struct({kind:Literal2("pull-checks"),repositoryId:RepositoryId,number:PullRequestNumber,headRevision:GitRevision}),Struct({kind:Literal2("pull-requests"),repositoryId:RepositoryId}),Struct({kind:Literal2("project-pull-requests")}),Struct({kind:Literal2("github-repositories")})]),PageFrame=Union2([Struct({kind:Literal2("event"),event:LiveEvent})]),CompanionFrame=Union2([Struct({kind:Literal2("hello"),hello:CompanionHello}),Struct({kind:Literal2("report"),runId:CompanionRunId,report:CompanionReport})]),HubFrame=Union2([Struct({kind:Literal2("welcome"),status:CompanionStatus,workspace:optional2(CompanionWorkspace)}),Struct({kind:Literal2("work"),run:CompanionRun}),Struct({kind:Literal2("cancel"),runId:CompanionRunId})]);var TranslationRequest=Struct({key:TranslationKey,path:RepoPath,frame:TranslationFrame,knownChanges:ArraySchema(RepoPath)}),Line=Int.check(isGreaterThanOrEqualTo2(1)),Count7=Int.check(isGreaterThanOrEqualTo2(0)),TranslationText=Struct({line:Line,value:String4}),TranslationValue=Struct({path:RepoPath,locale:String4,key:String4,head:NullOr(TranslationText),base:NullOr(TranslationText)}),ChangedLocaleFile=Struct({path:RepoPath,change:Literals(["added","modified","deleted","renamed"])}),TranslationLookup=Union2([Struct({kind:Literal2("unresolved"),requestedKey:String4,reason:String4}),Struct({kind:Literal2("looked-up"),requestedKey:String4,key:String4,scope:NullOr(String4),target:LocaleTarget,values:ArraySchema(TranslationValue),localeFiles:Count7,unread:Count7,changedLocaleFiles:ArraySchema(ChangedLocaleFile),unreadable:ArraySchema(Struct({path:RepoPath,side:Literals(["base","head"]),reason:String4})),omitted:NullOr(ArraySchema(OmittedLocaleFile)),searched:Literals(["index","changed-files"]),isCapped:Boolean3})]);var Line2=Int.check(isGreaterThanOrEqualTo2(1)),Offset=Int.check(isGreaterThanOrEqualTo2(0)),JumpPlace=Union2([Struct({kind:Literal2("at"),path:RepoPath,line:Line2,start:Offset}),Struct({kind:Literal2("usages"),path:RepoPath,line:Line2,name:String4.check(isPattern2(/^[A-Za-z_$][\w$]*[?!=]?$/u),isMaxLength(200))})]),JumpTargetKind=Literals(["controller","action","method","model","partial","template","route","test","tested","usage"]),JumpTarget=Struct({path:RepoPath,line:Line2,kind:JumpTargetKind,label:String4,note:NullOr(String4)}),JumpAnswer=Union2([Struct({kind:Literal2("found"),title:String4,certainty:Literals(["resolved","likely"]),how:String4,caveats:ArraySchema(String4),targets:ArraySchema(JumpTarget).check(isMinLength(1))}),Struct({kind:Literal2("not-found"),title:String4,reason:String4}),Struct({kind:Literal2("no-jump")})]);var JumpRequest=Struct({place:JumpPlace,side:Literals(["base","head"])}),JumpLookup=Struct({answer:JumpAnswer,side:Literals(["base","head"]),searched:Literals(["index","changed-files"])}),KnownTestPair=Struct({path:RepoPath,side:Literals(["base","head"]),kind:Literals(["test","source"]),target:RepoPath}),TestPairsLookup=Union2([Struct({kind:Literal2("known"),pairs:ArraySchema(KnownTestPair)}),Struct({kind:Literal2("index-not-ready")})]);var RubyConstantName=String4.check(isMinLength(1),isMaxLength(1024)).pipe(brand("RubyConstantName")),RubyConstantSpelling=String4.check(isPattern2(/^[A-Z][A-Za-z0-9_]*$/u),isMaxLength(256)).pipe(brand("RubyConstantSpelling")),Line3=Int.check(isGreaterThanOrEqualTo2(1)),Column=Int.check(isGreaterThanOrEqualTo2(0)),Count8=Int.check(isGreaterThanOrEqualTo2(0)),RubyPlace=Struct({path:RepoPath,line:Line3,column:Column}),AncestorsState=Literals(["complete","partial","cyclic"]),RubyDeclaration=Struct({name:RubyConstantName,kind:String4,definitions:ArraySchema(Struct({kind:String4,at:RubyPlace})),definitionCount:Count8,referenceCount:Count8,descendantCount:Count8,ancestors:NullOr(AncestorsState)}),RubyResolveAnswer=Union2([Struct({kind:Literal2("reference"),spelled:RubyConstantSpelling,at:RubyPlace,declaration:RubyDeclaration}),Struct({kind:Literal2("declared"),spelled:RubyConstantSpelling,declaration:RubyDeclaration}),Struct({kind:Literal2("unresolved"),spelled:RubyConstantSpelling,at:RubyPlace}),Struct({kind:Literal2("none")}),Struct({kind:Literal2("no-document")})]),RubyMethodSpelling=String4.check(isPattern2(/^[a-z_][A-Za-z0-9_]*[?!]?$/u),isMaxLength(256)).pipe(brand("RubyMethodSpelling")),MethodHow=Literals(["own","inherited","included","prepended","extended","concern"]),Overrider=Struct({name:RubyConstantName,at:NullOr(RubyPlace)}),MethodUnknownReason=Literals(["receiver","unresolved-receiver","top-level","unindexed-class","singleton-class-body","block-in-body"]),RubyMethodAnswer=Union2([Struct({kind:Literal2("method"),spelled:RubyMethodSpelling,at:RubyPlace,self:Literals(["class","instance"]),owner:RubyConstantName,ownerKind:String4,inBlock:Boolean3,found:NullOr(Struct({declaration:RubyDeclaration,in:RubyConstantName,how:MethodHow})),unindexed:ArraySchema(String4),tied:ArraySchema(RubyDeclaration),inBlocks:ArraySchema(RubyDeclaration),overriddenCount:Count8,overriddenIn:ArraySchema(Overrider)}),Struct({kind:Literal2("method-definition"),spelled:RubyMethodSpelling,declaration:RubyDeclaration,overrides:NullOr(RubyDeclaration),overriddenCount:Count8,overriddenIn:ArraySchema(Overrider)}),Struct({kind:Literal2("method-unknown"),spelled:RubyMethodSpelling,at:RubyPlace,reason:MethodUnknownReason}),Struct({kind:Literal2("local"),spelled:RubyMethodSpelling}),Struct({kind:Literal2("none")}),Struct({kind:Literal2("no-document")})]),NoDeclaration=Struct({kind:Literal2("no-declaration")}),RubyReferencesAnswer=Union2([Struct({kind:Literal2("references"),name:RubyConstantName,total:Count8,at:ArraySchema(RubyPlace)}),NoDeclaration]),RubyAncestorsAnswer=Union2([Struct({kind:Literal2("ancestors"),name:RubyConstantName,state:AncestorsState,ancestors:ArraySchema(Struct({name:String4,resolved:Boolean3}))}),NoDeclaration]),DescentKind=Literals(["inherits","includes","prepends","extends","indirectly"]),RubyDescendantsAnswer=Union2([Struct({kind:Literal2("descendants"),name:RubyConstantName,total:Count8,descendants:ArraySchema(Struct({name:RubyConstantName,kind:String4,how:DescentKind,at:NullOr(RubyPlace)}))}),NoDeclaration]),RubyStats=Struct({kind:Literal2("stats"),files:Count8,bytes:Count8,declarations:Count8,constantReferences:Count8,resolvedConstantReferences:Count8}),RubyQuery=Union2([Struct({kind:Literal2("resolve"),path:RepoPath,line:Line3,column:Column,spelled:RubyConstantSpelling}),Struct({kind:Literal2("method"),path:RepoPath,line:Line3,column:Column,spelled:RubyMethodSpelling}),Struct({kind:Literal2("references"),name:RubyConstantName,limit:Int.check(isBetween({minimum:1,maximum:500}))}),Struct({kind:Literal2("ancestors"),name:RubyConstantName}),Struct({kind:Literal2("descendants"),name:RubyConstantName,limit:Int.check(isBetween({minimum:1,maximum:500}))})]),RubyAnswer=Union2([RubyResolveAnswer,RubyMethodAnswer,RubyReferencesAnswer,RubyAncestorsAnswer,RubyDescendantsAnswer]);var Count9=Int.check(isGreaterThanOrEqualTo2(0)),RubyIndexFacts=Struct({revision:GitRevision,rubyFiles:Count9,rubyBytes:Count9,omittedFiles:Count9,leftOutTestFiles:Count9,declarations:Count9,constantReferences:Count9,resolvedConstantReferences:Count9,cache:Literals(["kept","built"]),buildMs:NullOr(Finite)}),RubyConstantLookup=Union2([Struct({kind:Literal2("answered"),answer:RubyAnswer,index:RubyIndexFacts}),Struct({kind:Literal2("too-large"),rubyBytes:Count9,limitBytes:Count9}),Struct({kind:Literal2("failed"),message:String4})]);var DependencyNotesRequest=Struct({target:DependencyTarget}),NotesSource=Literals(["rubygems","npm","github","osv"]),NotesFailure=Struct({source:NotesSource,reason:Literals(["not-found","refused","rate-limited","timed-out","unavailable","too-large","unreadable"]),message:String4}),NotesUrl=String4.check(isPattern2(/^https:\/\/[^\s"<>]{1,2040}$/u)),GitHubPart=String4.check(isPattern2(/^[A-Za-z0-9_.-]{1,100}$/u)),NotesRepository=Struct({owner:GitHubPart,name:GitHubPart,url:NotesUrl}),PackageNotes=Union2([Struct({kind:Literal2("found"),registryUrl:NotesUrl,repository:NullOr(NotesRepository),changelogUrl:NullOr(NotesUrl)}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),TagName=String4.check(isMinLength(1),isMaxLength(255)),MAX_RELEASE_NOTES=32000,NoneFromGitHub=Literals(["no-repository","not-on-github","no-tag","no-release"]),ReleaseNotes=Union2([Struct({kind:Literal2("found"),tag:TagName,title:NullOr(String4),url:NotesUrl,body:String4.check(isMaxLength(MAX_RELEASE_NOTES)),isCut:Boolean3,publishedAt:NullOr(String4)}),Struct({kind:Literal2("none"),reason:NoneFromGitHub}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),CompareLink=Union2([Struct({kind:Literal2("found"),url:NotesUrl,fromTag:TagName,toTag:TagName}),Struct({kind:Literal2("none"),reason:NoneFromGitHub}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),AdvisoryId=String4.check(isPattern2(/^[A-Za-z0-9._:-]{1,64}$/u)),AdvisorySeverity=Literals(["low","moderate","high","critical"]),Advisory=Struct({id:AdvisoryId,summary:NullOr(String4.check(isMaxLength(500))),aliases:ArraySchema(AdvisoryId),severity:NullOr(AdvisorySeverity),url:NotesUrl});var AdvisoryNotes=Union2([Struct({kind:Literal2("found"),fixed:ArraySchema(Advisory),remaining:ArraySchema(Advisory),introduced:ArraySchema(Advisory)}),Struct({kind:Literal2("failed"),failure:NotesFailure})]),DependencyNotes=Struct({target:DependencyTarget,readAt:String4,package:PackageNotes,release:ReleaseNotes,compare:CompareLink,advisories:AdvisoryNotes});var FileRange=Literals(["0","1","2-5","6-20","21-50","51-200","201+"]),EditRange=Literals(["0","1-10","11-50","51-200","201-1000","1001+"]),rangeOf=(bounds,last)=>(count)=>bounds.find(([upTo])=>count<=upTo)?.[1]??last,fileRange=rangeOf([[0,"0"],[1,"1"],[5,"2-5"],[20,"6-20"],[50,"21-50"],[200,"51-200"]],"201+"),editRange=rangeOf([[0,"0"],[10,"1-10"],[50,"11-50"],[200,"51-200"],[1000,"201-1000"]],"1001+"),AppVersion=String4.check(isPattern2(/^(?:[0-9a-f]{7,40}|dev)$/u)),PAGE_KINDS=["Home","Projects","Review","GitHubReview","GitHubRevision","Account","GitHubProject","Repository","Project","Authorize","ConnectedAgents","NotFound","Unknown"],PageKind=Literals(PAGE_KINDS),PageErrorKind=Literals(["error","unhandled-rejection","crash"]),ErrorName=String4.check(isPattern2(/^[A-Za-z][A-Za-z0-9_$]{0,63}$/u)),StackFrame=String4.check(isPattern2(/^(?:assets|src|node_modules)\/[A-Za-z0-9._/@+-]{1,200}\.(?:m?js|tsx?):[0-9]{1,7}:[0-9]{1,7}$/u)),MAX_ERROR_MESSAGE=300,MAX_STACK_FRAMES=12,PageErrorReport=Struct({kind:PageErrorKind,name:ErrorName,message:String4.check(isMaxLength(MAX_ERROR_MESSAGE)),frames:ArraySchema(StackFrame).check(isMaxLength(MAX_STACK_FRAMES)),version:AppVersion,page:PageKind});var TimingOutcome=Literals(["ok","failed"]),TimingEntry=Literals(["first-page","in-app"]),TimingMs=Finite.check(isBetween({minimum:0,maximum:3600000})),BrowserTiming=Union2([TaggedStruct("pull-request-import",{phase:Literal2("click-to-usable"),outcome:TimingOutcome,entry:TimingEntry,files:FileRange,edits:EditRange,ms:TimingMs}),TaggedStruct("review-open",{phase:Literal2("click-to-usable"),outcome:TimingOutcome,entry:TimingEntry,files:FileRange,edits:EditRange,ms:TimingMs}),TaggedStruct("repository-import",{phase:Literal2("click-to-ready"),outcome:TimingOutcome,ms:TimingMs}),TaggedStruct("lookup",{phase:Literals(["first-answer","repository","ruby","jump","translation"]),outcome:TimingOutcome,ms:TimingMs}),TaggedStruct("code-search",{phase:Literals(["first-results","complete"]),scope:Literals(["changed","whole"]),files:FileRange,ms:TimingMs}),TaggedStruct("page-load",{phase:Literals(["first-byte","dom-ready","load","first-render"]),page:PageKind,ms:TimingMs})]),MAX_TIMINGS_PER_REPORT=20,TimingReport=Struct({version:AppVersion,timings:ArraySchema(BrowserTiming).check(isMinLength(1),isMaxLength(MAX_TIMINGS_PER_REPORT))});var Label=String4.check(isMinLength(1),isMaxLength(1024)),ReviewSource=Union2([Struct({kind:Literal2("fixture"),label:Label}),Struct({kind:Literal2("github"),reference:GitHubReference,url:HttpsUrl})]),ActivityVersion=Int.check(isGreaterThanOrEqualTo2(0)).pipe(brand("ActivityVersion")),ReviewDocument=Struct({analysis:AnalysisSnapshot,state:ReviewState,comments:ArraySchema(Comment),commentProposals:optional2(ArraySchema(CommentEditProposal)),findings:optional2(ArraySchema(Finding)),githubReviews:optional2(GitHubReviewSubmissions),activityVersion:optional2(ActivityVersion),source:ReviewSource,title:Label,createdAt:Timestamp}),SnapshotCount=Int.check(isGreaterThanOrEqualTo2(0)),ReviewSnapshot=Struct({id:SnapshotId,analyzerRevision:AnalyzerRevision,repositoryId:RepositoryId,baseRevision:GitRevision,headRevision:GitRevision,files:SnapshotCount,occurrences:SnapshotCount,catalogDigest:Fingerprint,source:ReviewSource,title:Label,createdAt:Timestamp}),ReviewActivity=Struct({comments:ArraySchema(Comment),githubReviews:GitHubReviewSubmissions,activityVersion:ActivityVersion}),ReviewOverview=Struct({snapshot:ReviewSnapshot,progress:PositionedReviewState,...ReviewActivity.fields,commentProposals:ArraySchema(CommentEditProposal),findings:ArraySchema(Finding)}),ReviewRead=Literals(["open","other"]);var GitHubReviewResponse=Union2([Struct({kind:Literal2("recorded"),...ReviewActivity.fields}),Struct({kind:Literal2("not-submitted"),message:NonEmptyString})]),Count10=Int.check(isGreaterThanOrEqualTo2(0)),ReviewStage=Literals(["in-progress","not-started","done"]),ReviewStanding=Literals(["started","commented","new-pushes","not-started","approved","changes-requested","newer-revision","closed"]);var ReviewSummary=Struct({id:SnapshotId,repositoryId:RepositoryId,title:Label,source:ReviewSource,createdAt:Timestamp,baseRevision:GitRevision,headRevision:GitRevision,files:Count10,occurrences:Count10,reviewed:Count10,pending:Count10,revisit:Count10,standing:ReviewStanding}),ReviewList=ArraySchema(ReviewSummary),ReviewCursor=Struct({stage:ReviewStage,createdAt:Timestamp,snapshotId:SnapshotId});var ReviewPage=Struct({reviews:ReviewList,next:NullOr(ReviewCursor)}),ReviewListScope=Union2([Struct({kind:Literal2("workspace")}),Struct({kind:Literal2("repository"),repositoryId:RepositoryId}),Struct({kind:Literal2("github-repository"),repository:ConnectedRepository}),Struct({kind:Literal2("pull-request"),reference:GitHubReference})]),ReviewListQuery=Struct({repository:optional2(RepositoryId),owner:optional2(GitHubOwner),name:optional2(GitHubRepository),pull:optional2(FiniteFromString.pipe(decodeTo2(PullRequestNumber))),beforeStage:optional2(ReviewStage),before:optional2(Timestamp),beforeId:optional2(SnapshotId)}),reviewListQueryKeys=new Set(Object.keys(ReviewListQuery.fields));var ImportRequest=Union2([Struct({kind:Literal2("reanalyze"),snapshotId:SnapshotId}),Struct({kind:Literal2("fixture"),sample:optional2(SampleName)}),Struct({kind:Literal2("github"),reference:GitHubReference}),Struct({kind:Literal2("public-github"),reference:GitHubReference})]);var DraftCommand=Union2([Struct({kind:Literal2("create"),commandId:CommandId,id:CommentId,reviewerId:ReviewerId,anchor:CommentAnchor,body:CommentBody}),Struct({kind:Literal2("edit"),commandId:CommandId,id:CommentId,reviewerId:ReviewerId,expectedVersion:CommentVersion,body:CommentBody}),Struct({kind:Literal2("delete"),commandId:CommandId,id:CommentId,reviewerId:ReviewerId,expectedVersion:CommentVersion})]),DraftResponse=Struct({comments:ArraySchema(Comment),activityVersion:ActivityVersion}),ProposeCommentEdit=Struct({commandId:CommandId,commentId:CommentId,reviewerId:ReviewerId,baseVersion:CommentVersion,body:CommentBody,reason:optional2(ProposalReason)}),CommentEditResolution=Union2([Struct({kind:Literal2("apply"),body:optional2(CommentBody)}),Struct({kind:Literal2("dismiss")})]),ResolveCommentEdit=Struct({commandId:CommandId,proposalId:CommandId,reviewerId:ReviewerId,resolution:CommentEditResolution}),FindingResolution=Union2([Struct({kind:Literal2("draft"),commentId:CommentId,body:optional2(CommentBody)}),Struct({kind:Literal2("dismiss")}),Struct({kind:Literal2("reopen")})]),ResolveFinding=Struct({commandId:CommandId,findingId:FindingId,reviewerId:ReviewerId,resolution:FindingResolution}),FindingsResponse=Struct({findings:ArraySchema(Finding),comments:ArraySchema(Comment),activityVersion:ActivityVersion}),CommentProposalsResponse=Struct({comments:ArraySchema(Comment),commentProposals:ArraySchema(CommentEditProposal),activityVersion:ActivityVersion}),PublishRequest=Struct({commandId:CommandId,commentId:CommentId,reviewerId:ReviewerId,publicationId:PublicationId,expectedSnapshotId:SnapshotId,expectedCommentVersion:CommentVersion}),ReadySession=Struct({kind:Literal2("ready"),reviewerId:ReviewerId,canPublish:Boolean3,organizationId:OrganizationId}),Session=Union2([ReadySession,Struct({kind:Literal2("anonymous"),signIn:Struct({github:Boolean3,password:Boolean3})})]),ReleasedReview=Struct({snapshotId:SnapshotId,state:Literals(["releasing","released"]),reason:Literals(["closed","unused"]),releasedAt:Timestamp,source:ReviewSource}),ApiError=Union2([Struct({kind:Literal2("invalid-request"),message:String4}),Struct({kind:Literal2("not-found"),message:String4}),Struct({kind:Literal2("forbidden"),message:String4}),Struct({kind:Literal2("conflict"),message:String4}),Struct({kind:Literal2("project-not-added"),message:String4,repository:ConnectedRepository}),Struct({kind:Literal2("refused"),message:String4,refusal:ReviewRefusal}),Struct({kind:Literal2("review-released"),message:String4,release:ReleasedReview}),Struct({kind:Literal2("dependency-unavailable"),message:String4}),Struct({kind:Literal2("too-large"),message:String4}),Struct({kind:Literal2("internal"),message:String4})]),ErrorResponse=Struct({error:ApiError}),ProfileVersion=Int.check(isGreaterThanOrEqualTo2(0),isLessThanOrEqualTo2(Number.MAX_SAFE_INTEGER)).pipe(brand("ProfileVersion")),SavedProjectProfile=Struct({kind:Literal2("saved"),repositoryId:RepositoryId,version:ProfileVersion,profile:ProjectProfile,author:ReviewerId,updatedAt:Timestamp}),ProjectProfileRecord=Union2([Struct({kind:Literal2("absent"),repositoryId:RepositoryId,version:ProfileVersion}),SavedProjectProfile]),SaveProjectProfile=Struct({commandId:CommandId,expectedVersion:ProfileVersion,profile:ProjectProfile}),ReadyRepositoryIndex=Struct({kind:Literal2("ready"),repositoryId:RepositoryId,summary:RepositorySummary,coverage:RepositoryIndex.fields.coverage}),ReadyProjectIndex=Struct({...ReadyRepositoryIndex.fields,branch:NonEmptyString,builtAt:Timestamp}),ProjectIndexStatus=Union2([Struct({kind:Literal2("absent"),repositoryId:RepositoryId}),ReadyProjectIndex]),IndexFailureReason=Literals(["access-lost","parser-incomplete","stalled","expired","error"]),RepositoryIndexStatus=Union2([Struct({kind:Literal2("absent"),repositoryId:RepositoryId,revision:GitRevision}),Struct({kind:Literal2("preparing"),repositoryId:RepositoryId,revision:GitRevision,waitingFor:Literals(["project","revision"])}),Struct({kind:Literal2("failed"),repositoryId:RepositoryId,revision:GitRevision,reason:IndexFailureReason,of:Literals(["project","revision"]),message:String4}),ReadyRepositoryIndex]),ProjectStatus=Union2([Struct({kind:Literal2("not-imported")}),Struct({kind:Literal2("importing"),startedAt:Timestamp}),Struct({kind:Literal2("ready"),branch:NonEmptyString,revision:GitRevision,indexedFiles:Int.check(isGreaterThanOrEqualTo2(0)),builtAt:Timestamp}),Struct({kind:Literal2("failed"),reason:IndexFailureReason,message:String4})]),ImportProjectRequest=Struct({kind:Literals(["import","refresh"])}),SourceLineCount=Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(200)).pipe(brand("SourceLineCount")),RepositorySourceRequest=Struct({path:RepoPath,startLine:LineNumber,lineCount:SourceLineCount}),RepositorySourceExcerpt=Struct({indexId:RepositoryIndexId,revision:GitRevision,path:RepoPath,startLine:LineNumber,endLine:LineNumber,text:String4,utf8Bytes:ByteLength,truncated:Boolean3}),LeftoversRequest=Struct({groupId:GroupId,limit:optional2(Int.check(isGreaterThanOrEqualTo2(1),isLessThanOrEqualTo2(500)))});var AGENT_KINDS=["claude","codex","opencode"],COMMANDS={claude:"claude",codex:"codex",opencode:"opencode"},CODEX_FEATURES_OFF=["shell_tool","apps","plugins","remote_plugin","browser_use","browser_use_external","browser_use_full_cdp_access","computer_use","in_app_browser","in_app_local_automation","image_generation","memories","multi_agent","skill_search","skill_mcp_dependency_install","tool_suggest","hooks","goals","sleep_tool"],toml=(value)=>JSON.stringify(value),codexMcpConfig=(mcp)=>{let env=`{ ${Object.entries(mcp.env).map(([key,value])=>`${key} = ${toml(value)}`).join(", ")} }`;return["-c",`mcp_servers.diffclarity.command=${toml(mcp.command)}`,"-c",`mcp_servers.diffclarity.args=[${mcp.args.map(toml).join(", ")}]`,"-c",`mcp_servers.diffclarity.env=${env}`]};function agentCommand(run,directory,mcp,opencode){switch(run.agent){case"claude":return{cmd:[COMMANDS.claude,"-p","--output-format","stream-json","--verbose","--include-partial-messages","--tools","","--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:{diffclarity:mcp}}),"--allowedTools","mcp__diffclarity",...run.model?["--model",run.model]:[],...run.effort?["--effort",run.effort]:[],...run.resumeId?["--resume",run.resumeId]:[]],env:{},stdin:run.prompt};case"codex":return{cmd:[COMMANDS.codex,"exec","--json","--skip-git-repo-check","--ignore-user-config","--sandbox","read-only","-C",directory,...CODEX_FEATURES_OFF.flatMap((feature)=>["--disable",feature]),"-c",'web_search="disabled"',"-c","suppress_unstable_features_warning=true",...codexMcpConfig(mcp),...run.model?["-m",run.model]:[],...run.effort?["-c",`model_reasoning_effort=${toml(run.effort)}`]:[],...run.resumeId?["resume",run.resumeId]:[],"-"],env:{},stdin:run.prompt};case"opencode":if(opencode===void 0)throw Error("opencode answers through its private server, which isn't running.");return{cmd:[COMMANDS.opencode,"run","--server",opencode.url,"--format","json",...run.model?["--model",run.model]:[],...run.resumeId?["--session",run.resumeId]:[]],env:opencode.env,stdin:run.prompt}}}var parse=(line)=>{try{return JSON.parse(line)}catch{return}},record2=(value)=>typeof value==="object"&&value!==null?Object.fromEntries(Object.entries(value)):{},text=(value)=>typeof value==="string"?value:void 0,sessionEvent=(value)=>{let decoded=decodeUnknownOption2(AgentSessionId)(value);return decoded._tag==="Some"?[{kind:"session",sessionId:decoded.value}]:[]},toolName=(name)=>name.replace(/^mcp__diffclarity__|^diffclarity[_.]/u,"").slice(0,200),failed=(message)=>({kind:"failed",message:message.length>0?message.slice(0,2000):"The agent stopped with an error."}),claudeEvents=()=>(line)=>{let event=record2(parse(line));if(event.type==="system"&&event.subtype==="init")return sessionEvent(event.session_id);if(event.type==="stream_event"){let delta=record2(record2(event.event).delta),chunk=delta.type==="text_delta"?text(delta.text):void 0;return chunk?[{kind:"text",text:chunk}]:[]}if(event.type==="assistant"){let content=record2(event.message).content;return Array.isArray(content)?content.flatMap((block)=>{let name=text(record2(block).name);return record2(block).type==="tool_use"&&name?[{kind:"tool",name:toolName(name)}]:[]}):[]}if(event.type==="result"){let result=text(event.result)??"";return event.is_error===!0?[failed(result)]:[{kind:"answer",text:result}]}return[]},codexEvents=()=>(line)=>{let event=record2(parse(line));if(event.type==="thread.started")return sessionEvent(event.thread_id);if(event.type==="item.started"||event.type==="item.completed"){let item=record2(event.item);if(event.type==="item.started"&&item.type==="mcp_tool_call")return[{kind:"tool",name:toolName(text(item.tool)??"tool")}];if(event.type==="item.started"&&item.type==="command_execution")return[{kind:"tool",name:"shell (read-only sandbox)"}];let answer=text(item.text);if(event.type==="item.completed"&&item.type==="agent_message"&&answer)return[{kind:"answer",text:answer}];return[]}if(event.type==="turn.failed"||event.type==="error")return[failed(text(record2(event.error).message)??text(event.message)??"")];return[]},opencodeEvents=()=>{let hasSession=!1,hasText=!1;return(line)=>{let event=record2(parse(line)),session=hasSession?[]:sessionEvent(event.sessionID);hasSession||=session.length>0;let part=record2(event.part);if(event.type==="text"){let chunk=text(part.text);if(!chunk)return session;let separated=hasText?`
|
|
21
21
|
|
|
22
22
|
${chunk}`:chunk;return hasText=!0,[...session,{kind:"text",text:separated}]}if(event.type==="tool_use")return[...session,{kind:"tool",name:toolName(text(part.tool)??"tool")}];if(event.type==="error"){let error=record2(event.error);return[...session,failed(text(record2(error.data).message)??text(error.message)??text(error.name)??"")]}return session}},eventParser=(agent)=>agent==="claude"?claudeEvents():agent==="codex"?codexEvents():opencodeEvents(),agentLabel=(agent)=>COMPANION_AGENT_LABELS[agent];import{createHash,randomBytes as randomBytes2}from"node:crypto";import{createServer}from"node:http";import{homedir,hostname as hostname2}from"node:os";import{join}from"node:path";import{spawn}from"node:child_process";var crypto2;crypto2=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((m)=>m.webcrypto);async function getRandomValues(size){return(await crypto2).getRandomValues(new Uint8Array(size))}async function random2(size){let evenDistCutoff=Math.pow(2,8)-Math.pow(2,8)%66,result="";while(result.length<size){let randomBytes=await getRandomValues(size-result.length);for(let randomByte of randomBytes)if(randomByte<evenDistCutoff)result+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[randomByte%66]}return result}async function generateVerifier(length){return await random2(length)}async function generateChallenge(code_verifier){let buffer=await(await crypto2).subtle.digest("SHA-256",new TextEncoder().encode(code_verifier));return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(length){if(!length)length=43;if(length<43||length>128)throw`Expected a length between 43 and 128. Received ${length}.`;let verifier=await generateVerifier(length),challenge=await generateChallenge(verifier);return{code_verifier:verifier,code_challenge:challenge}}function getEnumValues(entries){let numericValues=Object.values(entries).filter((v)=>typeof v==="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}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=void 0}get value(){let getter=this._getter;if(getter!==void 0)this._value=getter(),this._getter=void 0;return this._value}}function cached2(getter){return new Cached(getter)}function nullish(input){return input===null||input===void 0}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=4*Number.EPSILON*Math.max(Math.abs(ratio),1);if(Math.abs(ratio-roundedRatio)<tolerance)return 0;return ratio-roundedRatio}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function rawShape(def){let 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(){let value=getter();return assignProp(this,key,value),value},enumerable:!0,configurable:!0})}function putProp(target,key,value){if(key in target)assignProp(target,key,value);else target[key]=value}function mirrorShape(target,source,keys,wrap){let raw=sourceShape(source);for(let key of keys){let desc=Object.getOwnPropertyDescriptor(raw,key);if(!desc.enumerable)continue;if(desc.get)deferProp(target,key,()=>{let 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(let key of Reflect.ownKeys(source)){let 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){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}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 isObject2(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}var allowsEval=cached2(()=>{if(globalConfig.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});function isPlainObject(o){if(isObject2(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;if(typeof ctor!=="function")return!0;let prot=ctor.prototype;if(isObject2(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}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}var propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return params}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)=>shape[k]._zod.optin!==void 0&&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]}))(),BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let newShape={};return mirrorShape(newShape,schema,maskedKeys(schema,mask)),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema,mask){let raw=sourceShape(schema),keys=[];for(let key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw,key)?.enumerable)throw Error(`Unrecognized key: "${String(key)}"`);if(mask[key])keys.push(key)}return keys}function omit2(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let omitted=new Set(maskedKeys(schema,mask)),newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)).filter((key)=>!omitted.has(key))),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=sourceShape(schema);for(let key of Reflect.ownKeys(shape))if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw 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){let newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema))),mirrorProps(newShape,shape),newShape}function safeExtend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to safeExtend: expected a plain object");return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function merge2(a,b){if(!b?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(a._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let newShape={};mirrorShape(newShape,a,Reflect.ownKeys(sourceShape(a))),mirrorShape(newShape,b,Reflect.ownKeys(sourceShape(b)));let 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(Class,schema,mask,name="partial"){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw Error(`.${name}() cannot be used on object schemas containing refinements`);let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),Class&&((value,key)=>selected&&!selected.has(key)?value:new Class({type:"optional",innerType:value}))),clone(schema,mergeDefs(schema._zod.def,{shape:newShape,checks:[]}))}function required(Class,schema,mask){let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),(value,key)=>selected&&!selected.has(key)?value:new Class({type:"nonoptional",innerType:value})),clone(schema,mergeDefs(schema._zod.def,{shape:newShape}))}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map((iss)=>{var _a;return(_a=iss).path??(_a.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function sizeCaps(defChecks){let caps=[];for(let ch of defChecks??[]){let d=ch._zod.def;if(!/_(length|size)$|_equals$/.test(d.check))break;let max=d.maximum??d.length??d.size;if(max>=0)caps.push([max,ch])}return caps}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;let 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;let schemaError=iss.schema!==iss.inst?iss.schema?._zod.def?.error:void 0,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",full={};for(let k of Object.keys(iss)){if(k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__")continue;full[k]=iss[k]}if(full.path??(full.path=[]),full.message=message,ctx?.reportInput)full.input=iss.input;return full}var highSurrogate=/[\uD800-\uDBFF]/;function codePointLength(str){let 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){let 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";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function members(proto,table){for(let key in table){let desc=Object.getOwnPropertyDescriptor(table,key);if(desc.get)Object.defineProperty(proto,key,{...desc,enumerable:!1});else defineBound(proto,key,desc.value)}}function own(inst,key,value,enumerable=!0){return Object.defineProperty(inst,key,{configurable:!0,writable:!0,enumerable,value}),value}function hide(inst,key,value){return own(inst,key,value,!1)}function derived(computes,table){for(let key in computes){let compute=computes[key];Object.defineProperty(table,key,{configurable:!0,enumerable:!0,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:!0,get(){return this==null?fn:own(this,key,fn.bind(this))},set(value){own(this,key,value)}})}function claim(inst,sentinel){let proto=Object.getPrototypeOf(inst);return sentinel in proto?void 0:proto}var installing,broke=!1,breaker={configurable:!0,get(){broke=!0;return}};function defineLazyInternal(inst,key,compute){let proto=Object.getPrototypeOf(inst._zod);if(key in proto&&installing!==inst._zod){installing=void 0;return}installing=inst._zod,Object.defineProperty(proto,key,{configurable:!0,get(){Object.defineProperty(this,key,breaker);let outer=broke;broke=!1;try{let value=compute(this);if(broke)delete this[key];else Object.defineProperty(this,key,{configurable:!0,writable:!0,value});return broke=broke||outer,value}catch(err){throw delete this[key],broke=broke||outer,err}},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,value})}})}function installLazyProp(inst,key,make,enumerable){let proto=claim(inst,key);if(!proto)return;Object.defineProperty(proto,key,{configurable:!0,get(){let desc={configurable:!0,writable:!0,enumerable,value:void 0};return Object.defineProperty(this,key,desc),desc.value=make(this),Object.defineProperty(this,key,desc),desc.value},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable,value})}})}var CONSTANT_CATCH="~constantCatch";function constantCatch(value){let fn=()=>value;return fn[CONSTANT_CATCH]=!0,fn}var _a,NEVER=Object.freeze({status:"aborted"}),_zodDesc={value:void 0,enumerable:!1},_E="captureStackTrace"in Error?Error:null;function newError(Definition){let E=_E;if(E){let saved=E.stackTraceLimit;if(typeof saved==="number"){try{E.stackTraceLimit=0}catch{return _E=null,new Definition}try{return new Definition}finally{E.stackTraceLimit=saved}}}return new Definition}function $constructor(name,initializer,proto,params){let zodProto={};function Internals(def){this.def=def,this.constr=_,this.traits=new Set}Internals.prototype=zodProto;let protoMembers=proto,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=void 0}}else if(inst._zod.traits.has(name))return;if(inst._zod.traits.add(name),initializer(inst,def),initialized){let own=Object.getPrototypeOf(inst),ctorProto=inst._zod.constr.prototype,up=own;while(up&&up!==ctorProto)up=Object.getPrototypeOf(up);let target=up??own;if(!initialized.has(target))initialized.add(target),members(target,protoMembers)}let proto=_.prototype;for(let k in proto){if(!Object.prototype.hasOwnProperty.call(proto,k))continue;if(!(k in inst))inst[k]=proto[k].bind(inst)}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){let inst=params?.Parent?newError(Definition):this;init(inst,def);let deferred=inst._zod.deferred;if(deferred){for(let fn of deferred)fn();inst._zod.deferred=void 0}let pp=globalThis.__zod_globalConfig?.postProcessor;if(pp)pp(inst);return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}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(){let internals=this._zod;return internals.message??(internals.message=JSON.stringify(internals.def,jsonStringifyReplacer,2)),internals.message}function _setMessage(value){this._zod.message=value}var _messageDesc={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},_issuesDesc={value:void 0,enumerable:!1},_installedToString=new WeakSet([Object.prototype,Error.prototype]),initializer=(inst,def)=>{inst.name="$ZodError",_issuesDesc.value=def,Object.defineProperty(inst,"issues",_issuesDesc),_issuesDesc.value=void 0,Object.defineProperty(inst,"message",_messageDesc);let proto=Object.getPrototypeOf(inst);if(!_installedToString.has(proto))_installedToString.add(proto),Object.defineProperty(proto,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0})}})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,void 0,{Parent:Error});function node(obj,key,make){if(!Object.prototype.hasOwnProperty.call(obj,key))if(key==="__proto__")Object.defineProperty(obj,key,{value:make(),writable:!0,enumerable:!0,configurable:!0});else obj[key]=make();return obj[key]}function flattenError(error,mapper=(issue)=>issue.message){let fieldErrors={},formErrors=[];for(let 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){let fieldErrors={_errors:[]},processError=(error,path=[])=>{for(let 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{let fullpath=[...path,...issue.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;while(i<fullpath.length){let el=fullpath[i],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:!0,writable:!0,configurable:!0});let node=curr[el];if(terminal)node._errors.push(mapper(issue));curr=node,i++}}}};return processError(error),fieldErrors}function finalizeParams(callee,params){return{callee:params?.callee??callee,Err:params?.Err}}var _parse=(_Err)=>{let fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee??fn),e}return result.value};return fn};var _parseAsync=(_Err)=>{let fn=async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){let e=new(params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee??fn),e}return result.value};return fn};var _safeParse=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError);function failure(Err,issues,ctx){let error;return{success:!1,get error(){if(!error)error=new Err(issues.map((iss)=>finalizeIssue(iss,ctx,config()))),issues=void 0,ctx=void 0;return error},set error(e){error=e,issues=void 0,ctx=void 0}}}var _safeParseAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}};var COMPILE_INVALID=Symbol.for("zod.compile.invalid"),COMPILE_FALLBACK=Symbol.for("zod.compile.fallback"),validate2=(schema,value,_ctx)=>{let validator=schema._zod.bag.validator;if(validator!==void 0){if(validator(value)!==COMPILE_INVALID)return!0;if(validator.definite===!0&&_ctx===void 0)return!1}return validateFallback(schema,value,_ctx)};function validateFallback(schema,value,_ctx){let ctx=_ctx?{..._ctx,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},fallbackRun=schema._zod.bag.fallbackRun,result;if(fallbackRun)ctx[COMPILE_FALLBACK]=!0,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)=>{let ctx=_ctx?{..._ctx,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length===0},_encode=(_Err)=>{let parse=_parse(_Err),fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return parse(schema,value,ctx,finalizeParams(fn,_params))};return fn};var _decode=(_Err)=>{let parse=_parse(_Err),fn=(schema,value,_ctx,_params)=>parse(schema,value,_ctx,finalizeParams(fn,_params));return fn};var _encodeAsync=(_Err)=>{let parseAsync=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return await parseAsync(schema,value,ctx,finalizeParams(fn,_params))};return fn};var _decodeAsync=(_Err)=>{let parseAsync=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>await parseAsync(schema,value,_ctx,finalizeParams(fn,_params));return fn};var _safeEncode=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)};var _safeDecode=(_Err)=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx);var _safeEncodeAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)};var _safeDecodeAsync=(_Err)=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx);var cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,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 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})$/,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 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 _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])$/,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 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])$/,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])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/;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){return typeof args.precision==="number"?args.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":args.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${args.precision}}`:args.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let opts=["Z"];if(args.offset)opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let qualified=`${timeSource({precision:args.precision,seconds:!0})}(?:${opts.join("|")})`,timeRegex=args.local?`${qualified}|${timeSource({precision:args.precision})}`:qualified;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var anyString=/^[\s\S]{0,}$/;var integer=/^-?\d+$/,number3=/^-?\d+(?:\.\d+)?$/,boolean2=/^(?:true|false)$/i,_null=/^null$/i;var lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/;var $ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a;inst._zod??(inst._zod={}),inst._zod.def=def,(_a=inst._zod).onattach??(_a.onattach=[])});var _whenHasLength=(payload)=>{let val=payload.value;return!nullish(val)&&val.length!==void 0},numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let 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})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let 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})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=(payload)=>{if(typeof payload.value!==typeof def.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof payload.value==="bigint"?def.value!==BigInt(0)&&payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.check=(payload)=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,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:!0,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:!0,continue:!def.abort});return}}if(input<minimum)payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,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)=>{let input=payload.value,units=input.length;if((typeof input==="string"&&units>def.maximum?codePointLength(input):units)<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=_whenHasLength),inst._zod.check=(payload)=>{let input=payload.value,units=input.length;if((typeof input==="string"&&units>=def.minimum&&units<def.minimum*2?codePointLength(input):units)>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=_whenHasLength),inst._zod.check=(payload)=>{let input=payload.value,units=input.length,length=typeof input==="string"&&units>=def.length&&units<=def.length*2?codePointLength(input):units;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a,_b;if($ZodCheck.init(inst,def),def.pattern)(_a=inst._zod).check??(_a.check=(payload)=>{if(def.pattern.lastIndex=0,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=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(def.pattern.lastIndex=0,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})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),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})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let 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})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let 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})}});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}let lines=arg.split(`
|
|
23
23
|
`).filter((x)=>x),minIndent=Math.min(...lines.map((x)=>x.length-x.trimStart().length)),dedented=lines.map((x)=>x.slice(minIndent)).map((x)=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,content=this?.content??[""];return new F(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
@@ -75,8 +75,8 @@ ${content.join(`
|
|
|
75
75
|
}
|
|
76
76
|
`)}return doc.write("payload.value = newResult;"),doc.write("return payload;"),doc.compile()},fastpass,isObject=isObject2,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;if(jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0){if(!fastpass)fastpass=generateFastpass(def.shape);if(payload=fastpass(payload,ctx),!catchall)return payload;return handleCatchall([],input,payload,ctx,value,inst,ctx?.abortEarly===!0)}return superParse(payload,ctx)}});function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter((r)=>!aborted(r));if(nonaborted.length===1)return final.value=nonaborted[0].value,nonaborted[0];return final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))}),final}var $ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",(zod)=>zod.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":zod.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),defineLazyInternal(inst,"optout",(zod)=>zod.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),defineLazyInternal(inst,"values",(zod)=>{if(zod.def.options.every((o)=>o._zod.values))return new Set(zod.def.options.flatMap((option)=>Array.from(option._zod.values)));return}),defineLazyInternal(inst,"pattern",(zod)=>{if(zod.def.options.every((o)=>o._zod.pattern)){let patterns=zod.def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${patterns.map((p)=>cleanRegex(p.source)).join("|")})$`)}return});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results)=>handleUnionResults(results,payload,inst,ctx))}});function discriminatorMap(def){let map=new Map;for(let option of def.options){let values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let value of values)if(map.has(value)){if(value!==void 0)throw Error(`Duplicate discriminator value "${String(value)}"`);map.set(value,null)}else map.set(value,option)}return map}var $ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazyInternal(inst,"propValues",(zod)=>{let propValues={},undefinedCount=0;for(let option of zod.def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);if(pv[zod.def.discriminator]?.has(void 0))undefinedCount++;for(let[k,v]of Object.entries(pv)){if(!Object.prototype.hasOwnProperty.call(propValues,k))assignProp(propValues,k,new Set);for(let val of v)propValues[k].add(val)}}if(!zod.def.unionFallback&&undefinedCount>1)propValues[zod.def.discriminator]?.delete(void 0);return propValues}),def.options.forEach((option,i)=>{let propShape=rawShape(option._zod.def);if(propShape&&!Object.prototype.hasOwnProperty.call(propShape,def.discriminator))throw Error(`Invalid discriminated union option at index "${i}"`)});let disc=cached2(()=>discriminatorMap(def));inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject2(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let value=input?.[def.discriminator],opt=disc.value.get(value);if(opt&&(value!==void 0||ctx.direction!=="backward"))return opt._zod.run(payload,ctx);if(def.unionFallback||ctx.direction==="backward")return _super(payload,ctx);return payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()).filter((value)=>disc.value.get(value)!==null),input,path:[def.discriminator],inst}),payload}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);if(left instanceof Promise||right instanceof Promise)return Promise.all([left,right]).then(([left,right])=>handleIntersectionResults(payload,left,right));return handleIntersectionResults(payload,left,right)}});function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a===+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter((key)=>bKeys.indexOf(key)!==-1),newObj={...a,...b};if(Object.prototype.hasOwnProperty.call(newObj,"__proto__"))delete newObj.__proto__;for(let key of sharedKeys){if(key==="__proto__")continue;let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue,keyIssues=new Map,collect=(iss,side)=>{let keys;if(iss.code==="unrecognized_keys"&&!iss.path?.length)unrecIssue??(unrecIssue=iss),keys=iss.keys;else if(iss.code==="invalid_key"&&iss.origin==="record"&&iss.path?.length===1){let k=String(iss.path[0]);if(!keyIssues.has(k))keyIssues.set(k,iss);keys=[k]}else return!1;for(let k of keys){if(!unrecKeys.has(k))unrecKeys.set(k,{});unrecKeys.get(k)[side]=!0}return!0};for(let iss of left.issues)if(!collect(iss,"l"))result.issues.push(iss);for(let iss of right.issues)if(!collect(iss,"r"))result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length){let aggregated=unrecIssue?bothKeys.filter((k)=>unrecIssue.keys.includes(k)):[];if(aggregated.length)result.issues.push({...unrecIssue,keys:aggregated});for(let k of bothKeys)if(!aggregated.includes(k)&&keyIssues.has(k))result.issues.push(keyIssues.get(k))}let merged=mergeValues(left.value,right.value);if(!merged.valid){if(aborted(result))return result;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}return result.value=merged.data,result}var $ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def);let memo=globalConfig.memoizer;memo?.attach(inst),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values&&!def.partial){payload.value=memo?memo.alloc(inst,payload,{},ctx):{};let recordKeys=new Set;for(let key of values)if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){if(recordKeys.add(typeof key==="number"?key.toString():key),key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value;if(outKey==="__proto__")continue;let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result)=>{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[outKey]=result.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[outKey]=result.value}}let unrecognized;for(let key in input)if(!recordKeys.has(key))if(def.mode==="loose"){if(key==="__proto__")continue;payload.value[key]=input[key]}else unrecognized=unrecognized??[],unrecognized.push(key);if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}else{payload.value=memo?memo.alloc(inst,payload,{},ctx):{};let unrecognized;for(let key of Reflect.ownKeys(input)){if(key==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof key==="string"&&number3.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(retryResult.issues.length===0)keyResult=retryResult}if(keyResult.issues.length){if(def.mode==="loose")payload.value[key]=input[key];else if(values)unrecognized=unrecognized??[],unrecognized.push(key);else payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value;if(outKey==="__proto__")continue;let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result)=>{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[outKey]=result.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[outKey]=result.value}}if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});var $ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,defineLazyInternal(inst,"pattern",(zod)=>{let patternValues=getEnumValues(zod.def.entries).filter((k)=>propertyKeyTypes.has(typeof k));return new RegExp(patternValues.length?`^(${patternValues.map((o)=>escapeRegex(o.toString())).join("|")})$`:"^[^\\s\\S]$")}),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(valuesSet.has(input))return payload;return payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{$ZodType.init(inst,def);let values=new Set(def.values);inst._zod.values=values,defineLazyInternal(inst,"pattern",(zod)=>{let vals=zod.def.values;return new RegExp(vals.length?`^(${vals.map((o)=>typeof o==="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(values.has(input))return payload;return payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}});var $ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",globalConfig.memoizer?.guard(inst),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then((output)=>(payload.value=output,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});function handleOptionalResult(payload,result){return payload.value=result.issues.length?void 0:result.value,payload}var $ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",(zod)=>zod.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),inst._zod.optout="optional",defineLazyInternal(inst,"values",(zod)=>{let values=zod.def.innerType._zod.values;return values?new Set([...values,void 0]):void 0}),defineLazyInternal(inst,"pattern",(zod)=>{let pattern=zod.def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===void 0){if(def.innerType._zod.optin!=="defaulted")return payload;let result=def.innerType._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)return result.then((result)=>handleOptionalResult(payload,result));return handleOptionalResult(payload,result)}return def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazyInternal(inst,"values",(zod)=>zod.def.innerType._zod.values),defineLazyInternal(inst,"pattern",(zod)=>zod.def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",(zod)=>zod.def.innerType._zod.optin),defineLazyInternal(inst,"optout",(zod)=>zod.def.innerType._zod.optout),defineLazyInternal(inst,"pattern",(zod)=>{let pattern=zod.def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazyInternal(inst,"values",(zod)=>zod.def.innerType._zod.values?new Set([...zod.def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="defaulted",defineLazyInternal(inst,"values",(zod)=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result)=>handleDefaultResult(result,def));return handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){if(payload.value===void 0)payload.value=def.defaultValue;return payload}var $ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="defaulted",defineLazyInternal(inst,"values",(zod)=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)payload.value=def.defaultValue;return def.innerType._zod.run(payload,ctx)}}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"values",(zod)=>{let v=zod.def.innerType._zod.values;return v?new Set([...v].filter((x)=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result)=>handleNonOptionalResult(result,inst));return handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){if(!payload.issues.length&&payload.value===void 0)payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst});return payload}function handleCatchResult(payload,result,def,ctx){if(!result.issues.length){if(payload.value=result.value,result.memo)payload.memo=!0;return payload}return payload.value=def.catchValue({...result,value:payload.value,error:{issues:result.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload}var $ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",(zod)=>zod.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),defineLazyInternal(inst,"optout",(zod)=>zod.def.innerType._zod.optout),defineLazyInternal(inst,"values",(zod)=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)return result.then((result)=>handleCatchResult(payload,result,def,ctx));return handleCatchResult(payload,result,def,ctx)}});var $ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"values",(zod)=>zod.def.in._zod.values),defineLazyInternal(inst,"optin",(zod)=>zod.def.in._zod.optin),defineLazyInternal(inst,"optout",(zod)=>zod.def.out._zod.optout),defineLazyInternal(inst,"propValues",(zod)=>zod.def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right)=>handlePipeResult(right,def.in,ctx));return handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left)=>handlePipeResult(left,def.out,ctx));return handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){if(left.issues.some((iss)=>iss.code!=="unrecognized_keys"))return left.aborted=!0,left;return next._zod.run({value:left.value,issues:left.issues},ctx)}var $ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)}),$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"propValues",(zod)=>zod.def.innerType._zod.propValues),defineLazyInternal(inst,"values",(zod)=>zod.def.innerType._zod.values),defineLazyInternal(inst,"optin",(zod)=>zod.def.innerType?._zod?.optin),defineLazyInternal(inst,"optout",(zod)=>zod.def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then(handleReadonlyResult);return handleReadonlyResult(result)}});function handleReadonlyResult(payload){if(!payload.memo)payload.value=Object.freeze(payload.value);return payload}var $ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=(payload)=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then((r)=>handleRefineResult(r,payload,input,inst));handleRefineResult(r,payload,input,inst);return}});function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};if(inst._zod.def.params)_iss.params=inst._zod.def.params;payload.issues.push(issue(_iss))}}class $ZodCyclicError extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var STATE="~memo",NO_ISSUES=[];function isRef(value){return value!==null&&typeof value==="object"}function cloneIssues(issues){return issues.map((iss)=>iss.path?{...iss,path:iss.path.slice()}:{...iss})}var recursive=new WeakMap,NONE=0,ASSUMED=1,PROVEN=2;function isRecursive(inst,stack,resolve){let cached=recursive.get(inst);if(cached!==void 0)return cached?PROVEN:NONE;if(stack.has(inst))return PROVEN;stack.add(inst);let result=NONE,check=(child)=>{if(result!==PROVEN&&child?._zod){let answer=isRecursive(child,stack,resolve);if(answer>result)result=answer}},shape=(sh,spread)=>{let answer=NONE;for(let key of Reflect.ownKeys(sh)){let desc=Object.getOwnPropertyDescriptor(sh,key);if(spread&&!desc.enumerable)continue;let child=desc.get?ASSUMED:desc.value?._zod?isRecursive(desc.value,stack,resolve):NONE;if(child>answer)answer=child}return answer},merge=(answer)=>{if(answer>result)result=answer},def=inst._zod.def,kind=def.type;switch(kind){case"object":{let raw=rawShape(def);merge(raw?shape(raw,!0):ASSUMED),check(def.catchall);break}case"array":check(def.element);break;case"tuple":for(let el of def.items)check(el);check(def.rest);break;case"record":case"map":check(def.keyType),check(def.valueType);break;case"set":check(def.valueType);break;case"union":for(let el of def.options)check(el);break;case"intersection":check(def.left),check(def.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":check(def.innerType);break;case"pipe":check(def.in),check(def.out);break;case"function":check(def.input),check(def.output);break;case"lazy":{let inner=def._cachedInner??(resolve?inst._zod.innerType:void 0);merge(inner?isRecursive(inner,stack,!1):ASSUMED);break}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":break;default:for(let key in def){let desc=Object.getOwnPropertyDescriptor(def,key);if(!desc||desc.get)continue;let value=desc.value;if(!value||typeof value!=="object")continue;if(value._zod)check(value);else if(Array.isArray(value))for(let el of value)check(el)}}return stack.delete(inst),settle(inst,result)}function settle(inst,answer){if(answer!==ASSUMED)recursive.set(inst,answer===PROVEN);return answer}function bucketFor(state,inst){let bucket=state.buckets.get(inst);if(!bucket)bucket=new WeakMap,state.buckets.set(inst,bucket);return bucket}var handoff,open=[],memo={alloc(_inst,payload,empty){let bucket=handoff;if(!bucket)return empty;handoff=void 0;let entry={value:empty,issues:null};return bucket.set(payload.value,entry),open.push(entry),empty},guard(inst){var _a;(_a=inst._zod).deferred??(_a.deferred=[]),inst._zod.deferred.push(()=>{let base=inst._zod.parse,wrapped=(payload,ctx)=>{if(ctx.direction!=="backward"&&isBackEdge(ctx,payload.value))throw new $ZodCyclicError;return base(payload,ctx)};if(inst._zod.parse=wrapped,inst._zod.run===base)inst._zod.run=wrapped})},attach(inst){var _a;let isRecursiveInst,rechecked=!1,lastCtx,lastBucket;(_a=inst._zod).deferred??(_a.deferred=[]),inst._zod.deferred.push(()=>{let base=inst._zod.parse,wrapped=(payload,ctx)=>{if(isRecursiveInst===void 0){let walked=isRecursive(inst,new Set,!1);if(walked===NONE){if(inst._zod.parse=base,inst._zod.run===wrapped)inst._zod.run=base;return base(payload,ctx)}if(walked===PROVEN||rechecked)isRecursiveInst=!0;else rechecked=!0}let input=payload.value;if(!isRef(input))return base(payload,ctx);let state=ctx[STATE];if(!state)state={buckets:new WeakMap,backEdges:void 0},ctx[STATE]=state;let bucket;if(lastCtx===ctx)bucket=lastBucket;else bucket=bucketFor(state,inst),lastCtx=ctx,lastBucket=bucket;let hit=bucket.get(input);if(hit){if(payload.value=hit.value,hit.issues){if(hit.issues.length)payload.issues.push(...cloneIssues(hit.issues))}else payload.memo=!0,state.backEdges??(state.backEdges=new WeakSet),state.backEdges.add(hit.value);return payload}handoff=bucket;let depth=open.length,result=base(payload,ctx);handoff=void 0;let entry=open.length>depth?open.pop():void 0;if(result instanceof Promise)return result.then((r)=>{if(entry)entry.issues=r.issues.length?cloneIssues(r.issues):NO_ISSUES;return r});if(entry)entry.issues=result.issues.length?cloneIssues(result.issues):NO_ISSUES;return result};if(inst._zod.parse=wrapped,inst._zod.run===base)inst._zod.run=wrapped})}};function memoizer(){return memo}function isBackEdge(ctx,value){let backEdges=ctx[STATE]?.backEdges;return backEdges!==void 0&&isRef(value)&&backEdges.has(value)}var error=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};function getTypeName(type,input){if(type==="number"&&typeof input==="number"&&!Number.isFinite(input))return String(input);return TypeDictionary[type]??type}return(issue)=>{switch(issue.code){case"invalid_type":{let expected=getTypeName(issue.expected),receivedType=parsedType(issue.input),received=getTypeName(receivedType,issue.input);return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":if(issue.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;return`Invalid option: expected one of ${joinValues(issue.values,"|")}`;case"too_big":{let adj=issue.exact?"exactly ":issue.inclusive?"<=":"<",sizing=getSizing(issue.origin);if(sizing)return`Too big: expected ${issue.origin??"value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit??"elements"}`;return`Too big: expected ${issue.origin??"value"} to be ${adj}${issue.maximum.toString()}`}case"too_small":{let adj=issue.exact?"exactly ":issue.inclusive?">=":">",sizing=getSizing(issue.origin);if(sizing)return`Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;return`Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`}case"invalid_format":{let _issue=issue;if(_issue.format==="starts_with")return`Invalid string: must start with "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue.keys.length>1?"s":""}: ${joinValues(issue.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue.origin}`;case"invalid_union":if(issue.options&&Array.isArray(issue.options)&&issue.options.length>0)return`Invalid discriminator value. Expected ${issue.options.map((o)=>`'${o}'`).join(" | ")}`;if(issue.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${issue.origin}`;default:return"Invalid input"}}};function en_default(){return{localeError:error()}}var _a2;class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];if(this._map.set(schema,meta),meta&&typeof meta==="object"&&"id"in meta)this._idmap.set(meta.id,schema);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);if(meta&&typeof meta==="object"&&"id"in meta)this._idmap.delete(meta.id);return this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry(){return new $ZodRegistry}(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;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 _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,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:!0,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...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 _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}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 _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 _custom(Class,fn,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class({type:"custom",check:"custom",fn,...norm})}function _refine(Class,fn,_params){return new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check((payload)=>(payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;if(_issue.code??(_issue.code="custom"),!("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))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}function assignProps(target,...sources){for(let source of sources)for(let 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:void 0,sharedEmitDoneFor:void 0,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??void 0}}function handleUnrepresentable(schema,ctx,json,params,message){let result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw Error(message);return Object.assign(json,result),!0}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen){if(seen.count++,_params.schemaPath.includes(schema))seen.cycle=_params.path;return seen.schema}let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0}}let 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);return delete result.schema._prefault,ctx.seen.get(schema).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw 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])}}let makeURI=(entry)=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??((id)=>id);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}let uriPrefix="#",defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id)return{ref:uriPrefix};let defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}},extractToDef=(entry)=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);if(seen.def={...seen.schema},defId)seen.defId=defId;let schema=seen.schema;for(let key in schema)delete schema[key];schema.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
|
|
77
77
|
|
|
78
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.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){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let 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"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;if(extra===void 0||extra===!1||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){let objects=[];for(let member of members){if(typeof member!=="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required=new Set;for(let object of objects){for(let key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===void 0)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object.required??[])required.add(key)}let folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object of objects){let 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){let allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json)return;let unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union=unions[0],keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;let rest=allOf.filter((m)=>m!==union),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){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema=seen.def??seen.schema,_cached={...schema},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),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);if(assignProps(schema,_cached),zodSchema._zod.parent===ref)for(let key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema[key]}if(refSchema.$ref&&refSeen.def)for(let 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]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema.$ref=parentSeen.schema.$ref,parentSeen.def)for(let 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(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json of[seen.schema,seen.def]){let allOf=json?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}for(let allOf of ctx.intersections)for(let json of carriers.get(allOf)??[])foldIntersection(json)}}let 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){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==void 0&&result.id===rootMetaId)delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let 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{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;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!0;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===void 0||value>agg[key])agg[key]=value},narrowMax=(agg,key,value)=>{if(agg[key]===void 0||value<agg[key])agg[key]=value},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{if(agg.multipleOf??(agg.multipleOf=[]),!agg.multipleOf.includes(value))agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{if(agg.format=format,format.includes("int"))agg.isInt=!0},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},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)=>{if(setFormat(agg,def.format),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=!0},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;if(bag.minimum!==void 0)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==void 0)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==void 0)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==void 0)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==void 0)addDivisor(agg,bag.multipleOf);if(bag.format!==void 0){if(agg.format??(agg.format=bag.format),bag.format.includes("int"))agg.isInt=!0}if(bag.mime)intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=(p)=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time"||laxFormat)delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let 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}))]}},numberProcessor=(schema,ctx,_json,params)=>{let json=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin)if(legacy)json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;else if(typeof minimum==="number")json.minimum=minimum;if(exMax)if(legacy)json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;else if(typeof maximum==="number")json.maximum=maximum;if(multipleOf){let divisors=new Set;for(let 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`);let[first,...rest]=divisors;if(first!==void 0)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{};var enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,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},literalProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;if(def.values.length===0){json.not={};return}let vals=[];for(let val of def.values)if(val===void 0){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){let val=vals[0];if(json.type=val===null?"null":typeof val,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 customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom 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 arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{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){let 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)=>{let json=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema"))return;json.type="object",json.properties={};for(let key in shape)assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)requiredKeys.push(key)}if(requiredKeys.length>0)json.required=requiredKeys;if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,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},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf,ctx.intersections.push(allOf)};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);let def=bySchema.get(json)?.def;if(!def)return json;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}let types=Array.isArray(json.type)?json.type:[json.type],numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer"),values=json.enum??(json.const!==void 0?[json.const]:void 0);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;let{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;if(rest.type="string",!values)rest.pattern=(types.includes("number")?number3:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}var recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let 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"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues.map(String)}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;return unrepresentable=!0,null});if(!unrepresentable)return JSON.parse(serialized);return handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0};var optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType};var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key,{value,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let 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:!0,enumerable:!1,get(){return this.issues.length===0}})};var ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse3=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_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,inst),{check(...chks){let 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:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){return reg.add(this,meta),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional3(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional3(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array2(this)},or(arg){return union2([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform3(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).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 parseAsync(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate2(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 encodeAsync(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode(this,data,params)},safeDecode(data,params){return safeDecode(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,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())}})),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 string4(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.isFinite=!0},derived({minValue:(inst)=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{let{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 number4(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)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});function boolean3(params){return _boolean(ZodBoolean,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,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,json,params)=>anyProcessor(inst,ctx,json,params)});function any2(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});function unknown2(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});function never3(params){return _never(ZodNever,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,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 array2(element,params){return _array(ZodArray,element,params)}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),installLazyProp(inst,"shape",(self)=>self._zod.def.shape,!1)},{keyof(){return _enum(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:unknown2()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown2()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never3()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge2(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit2(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){let def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown2(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});function union2(options,params){return new ZodUnion({type:"union",options,...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,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record3(keyType,valueType,params){if(!valueType||!valueType._zod)return new ZodRecord({type:"record",keyType:string4(),valueType:keyType,...normalizeParams(valueType)});return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;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,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw 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 ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,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{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;if(_issue.code??(_issue.code="custom"),!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst),payload.issues.push(issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output)=>(payload.value=output,payload));return payload.value=output,payload}});function transform3(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,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function optional3(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,json,params)=>optionalProcessor(inst,ctx,json,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,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(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,json,params)=>prefaultProcessor(inst,ctx,json,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,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform3(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"};var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function number5(params){return _coercedNumber(ZodNumber,params)}var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=custom((v)=>v!==null&&(typeof v==="object"||typeof v==="function")),ProgressTokenSchema=union2([string4(),number4().int()]),CursorSchema=string4(),TaskCreationParamsSchema=looseObject({ttl:number4().optional(),pollInterval:number4().optional()}),TaskMetadataSchema=object({ttl:number4().optional()}),RelatedTaskMetadataSchema=object({taskId:string4()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=(value)=>TaskAugmentedRequestParamsSchema.safeParse(value).success,RequestSchema=object({method:string4(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string4(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union2([string4(),number4().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=(value)=>JSONRPCRequestSchema.safeParse(value).success,JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=(value)=>JSONRPCNotificationSchema.safeParse(value).success,JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=(value)=>JSONRPCResultResponseSchema.safeParse(value).success;var ErrorCode;(function(ErrorCode){ErrorCode[ErrorCode.ConnectionClosed=-32000]="ConnectionClosed",ErrorCode[ErrorCode.RequestTimeout=-32001]="RequestTimeout",ErrorCode[ErrorCode.ParseError=-32700]="ParseError",ErrorCode[ErrorCode.InvalidRequest=-32600]="InvalidRequest",ErrorCode[ErrorCode.MethodNotFound=-32601]="MethodNotFound",ErrorCode[ErrorCode.InvalidParams=-32602]="InvalidParams",ErrorCode[ErrorCode.InternalError=-32603]="InternalError",ErrorCode[ErrorCode.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number4().int(),message:string4(),data:unknown2().optional()})}).strict();var isJSONRPCErrorResponse=(value)=>JSONRPCErrorResponseSchema.safeParse(value).success;var JSONRPCMessageSchema=union2([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union2([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string4().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string4(),mimeType:string4().optional(),sizes:array2(string4()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array2(IconSchema).optional()}),BaseMetadataSchema=object({name:string4(),title:string4().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string4(),websiteUrl:string4().optional(),description:string4().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean3().optional()}),record3(string4(),unknown2())),ElicitationCapabilitySchema=preprocess((value)=>{if(value&&typeof value==="object"&&!Array.isArray(value)){if(Object.keys(value).length===0)return{form:{}}}return value},intersection(object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record3(string4(),unknown2()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record3(string4(),AssertObjectSchema).optional(),sampling:object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean3().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record3(string4(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string4(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=object({experimental:record3(string4(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object({listChanged:boolean3().optional()}).optional(),resources:object({subscribe:boolean3().optional(),listChanged:boolean3().optional()}).optional(),tools:object({listChanged:boolean3().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record3(string4(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string4(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string4().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),isInitializedNotification=(value)=>InitializedNotificationSchema.safeParse(value).success,PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number4(),total:optional3(number4()),message:optional3(string4())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string4(),status:TaskStatusSchema,ttl:union2([number4(),_null3()]),createdAt:string4(),lastUpdatedAt:string4(),pollInterval:optional3(number4()),statusMessage:optional3(string4())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string4()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string4()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array2(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string4()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object({uri:string4(),mimeType:optional3(string4()),_meta:record3(string4(),unknown2()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string4()}),Base64Schema=string4().refine((val)=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array2(RoleSchema).optional(),priority:number4().min(0).max(1).optional(),lastModified:datetime2({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string4(),description:optional3(string4()),mimeType:optional3(string4()),size:optional3(number4()),annotations:AnnotationsSchema.optional(),_meta:optional3(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string4(),description:optional3(string4()),mimeType:optional3(string4()),annotations:AnnotationsSchema.optional(),_meta:optional3(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array2(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array2(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string4()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array2(union2([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string4()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string4(),description:optional3(string4()),required:optional3(boolean3())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional3(string4()),arguments:optional3(array2(PromptArgumentSchema)),_meta:optional3(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array2(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string4(),arguments:record3(string4(),string4()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string4(),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string4(),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string4(),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string4(),id:string4(),input:record3(string4(),unknown2()),_meta:record3(string4(),unknown2()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union2([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union2([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string4().optional(),messages:array2(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string4().optional(),readOnlyHint:boolean3().optional(),destructiveHint:boolean3().optional(),idempotentHint:boolean3().optional(),openWorldHint:boolean3().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string4().optional(),inputSchema:object({type:literal("object"),properties:record3(string4(),AssertObjectSchema).optional(),required:array2(string4()).optional()}).catchall(unknown2()),outputSchema:object({type:literal("object"),properties:record3(string4(),AssertObjectSchema).optional(),required:array2(string4()).optional()}).catchall(unknown2()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array2(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array2(ContentBlockSchema).default([]),structuredContent:record3(string4(),unknown2()).optional(),isError:boolean3().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown2()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string4(),arguments:record3(string4(),unknown2()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean3().default(!0),debounceMs:number4().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string4().optional(),data:unknown2()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string4().optional()}),ModelPreferencesSchema=object({hints:array2(ModelHintSchema).optional(),costPriority:number4().min(0).max(1).optional(),speedPriority:number4().min(0).max(1).optional(),intelligencePriority:number4().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string4().describe("The unique identifier for the corresponding tool call."),content:array2(ContentBlockSchema).default([]),structuredContent:object({}).loose().optional(),isError:boolean3().optional(),_meta:record3(string4(),unknown2()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union2([SamplingMessageContentBlockSchema,array2(SamplingMessageContentBlockSchema)]),_meta:record3(string4(),unknown2()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array2(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string4().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number4().optional(),maxTokens:number4().int(),stopSequences:array2(string4()).optional(),metadata:AssertObjectSchema.optional(),tools:array2(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string4(),stopReason:optional3(_enum(["endTurn","stopSequence","maxTokens"]).or(string4())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string4(),stopReason:optional3(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string4())),role:RoleSchema,content:union2([SamplingMessageContentBlockSchema,array2(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string4().optional(),description:string4().optional(),default:boolean3().optional()}),StringSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),minLength:number4().optional(),maxLength:number4().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string4().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string4().optional(),description:string4().optional(),minimum:number4().optional(),maximum:number4().optional(),default:number4().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),enum:array2(string4()),default:string4().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),oneOf:array2(object({const:string4(),title:string4()})),default:string4().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),enum:array2(string4()),enumNames:array2(string4()).optional(),default:string4().optional()}),SingleSelectEnumSchemaSchema=union2([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string4().optional(),description:string4().optional(),minItems:number4().optional(),maxItems:number4().optional(),items:object({type:literal("string"),enum:array2(string4())}),default:array2(string4()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string4().optional(),description:string4().optional(),minItems:number4().optional(),maxItems:number4().optional(),items:object({anyOf:array2(object({const:string4(),title:string4()}))}),default:array2(string4()).optional()}),MultiSelectEnumSchemaSchema=union2([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union2([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union2([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string4(),requestedSchema:object({type:literal("object"),properties:record3(string4(),PrimitiveSchemaDefinitionSchema),required:array2(string4()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string4(),elicitationId:string4(),url:string4().url()}),ElicitRequestParamsSchema=union2([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string4()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess((val)=>val===null?void 0:val,record3(string4(),union2([string4(),number4(),boolean3(),array2(string4())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string4()});var PromptReferenceSchema=object({type:literal("ref/prompt"),name:string4()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union2([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string4(),value:string4()}),context:object({arguments:record3(string4(),string4()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});var CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array2(string4()).max(100),total:optional3(number4().int()),hasMore:optional3(boolean3())})}),RootSchema=object({uri:string4().startsWith("file://"),name:string4().optional(),_meta:record3(string4(),unknown2()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array2(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union2([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union2([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union2([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union2([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union2([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union2([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);class McpError extends Error{constructor(code,message,data){super(`MCP error ${code}: ${message}`);this.code=code,this.data=data,this.name="McpError"}static fromError(code,message,data){if(code===ErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new McpError(code,message,data)}}class UrlElicitationRequiredError extends McpError{constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}}var SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine((url)=>{let u=new URL(url);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string4().url(),authorization_servers:array2(SafeUrlSchema).optional(),jwks_uri:string4().url().optional(),scopes_supported:array2(string4()).optional(),bearer_methods_supported:array2(string4()).optional(),resource_signing_alg_values_supported:array2(string4()).optional(),resource_name:string4().optional(),resource_documentation:string4().optional(),resource_policy_uri:string4().url().optional(),resource_tos_uri:string4().url().optional(),tls_client_certificate_bound_access_tokens:boolean3().optional(),authorization_details_types_supported:array2(string4()).optional(),dpop_signing_alg_values_supported:array2(string4()).optional(),dpop_bound_access_tokens_required:boolean3().optional()}),OAuthMetadataSchema=looseObject({issuer:string4(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array2(string4()).optional(),response_types_supported:array2(string4()),response_modes_supported:array2(string4()).optional(),grant_types_supported:array2(string4()).optional(),token_endpoint_auth_methods_supported:array2(string4()).optional(),token_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array2(string4()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),introspection_endpoint:string4().optional(),introspection_endpoint_auth_methods_supported:array2(string4()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),code_challenge_methods_supported:array2(string4()).optional(),client_id_metadata_document_supported:boolean3().optional()}),OpenIdProviderMetadataSchema=looseObject({issuer:string4(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array2(string4()).optional(),response_types_supported:array2(string4()),response_modes_supported:array2(string4()).optional(),grant_types_supported:array2(string4()).optional(),acr_values_supported:array2(string4()).optional(),subject_types_supported:array2(string4()),id_token_signing_alg_values_supported:array2(string4()),id_token_encryption_alg_values_supported:array2(string4()).optional(),id_token_encryption_enc_values_supported:array2(string4()).optional(),userinfo_signing_alg_values_supported:array2(string4()).optional(),userinfo_encryption_alg_values_supported:array2(string4()).optional(),userinfo_encryption_enc_values_supported:array2(string4()).optional(),request_object_signing_alg_values_supported:array2(string4()).optional(),request_object_encryption_alg_values_supported:array2(string4()).optional(),request_object_encryption_enc_values_supported:array2(string4()).optional(),token_endpoint_auth_methods_supported:array2(string4()).optional(),token_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),display_values_supported:array2(string4()).optional(),claim_types_supported:array2(string4()).optional(),claims_supported:array2(string4()).optional(),service_documentation:string4().optional(),claims_locales_supported:array2(string4()).optional(),ui_locales_supported:array2(string4()).optional(),claims_parameter_supported:boolean3().optional(),request_parameter_supported:boolean3().optional(),request_uri_parameter_supported:boolean3().optional(),require_request_uri_registration:boolean3().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean3().optional()}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string4(),id_token:string4().optional(),token_type:string4(),expires_in:number5().optional(),scope:string4().optional(),refresh_token:string4().optional(),issuer:string4().optional().catch(void 0)}).strip(),OAuthErrorResponseSchema=object({error:string4(),error_description:string4().optional(),error_uri:string4().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{return})),OAuthClientMetadataSchema=object({redirect_uris:array2(SafeUrlSchema),token_endpoint_auth_method:string4().optional(),grant_types:array2(string4()).optional(),response_types:array2(string4()).optional(),client_name:string4().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string4().optional(),contacts:array2(string4()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string4().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any2().optional(),software_id:string4().optional(),software_version:string4().optional(),software_statement:string4().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string4(),client_secret:string4().optional(),client_id_issued_at:number4().optional(),client_secret_expires_at:number4().optional(),issuer:string4().optional().catch(void 0)}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string4(),error_description:string4().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string4(),token_type_hint:string4().optional()}).strip();function resourceUrlFromServerUrl(url){let resourceURL=typeof url==="string"?new URL(url):new URL(url.href);return resourceURL.hash="",resourceURL}function checkResourceAllowed({requestedResource,configuredResource}){let requested=typeof requestedResource==="string"?new URL(requestedResource):new URL(requestedResource.href),configured=typeof configuredResource==="string"?new URL(configuredResource):new URL(configuredResource.href);if(requested.origin!==configured.origin)return!1;if(requested.pathname.length<configured.pathname.length)return!1;let requestedPath=requested.pathname.endsWith("/")?requested.pathname:requested.pathname+"/",configuredPath=configured.pathname.endsWith("/")?configured.pathname:configured.pathname+"/";return requestedPath.startsWith(configuredPath)}class OAuthError extends Error{constructor(message,errorUri){super(message);this.errorUri=errorUri,this.name=this.constructor.name}toResponseObject(){let response={error:this.errorCode,error_description:this.message};if(this.errorUri)response.error_uri=this.errorUri;return response}get errorCode(){return this.constructor.errorCode}}class InvalidRequestError extends OAuthError{}InvalidRequestError.errorCode="invalid_request";class InvalidClientError extends OAuthError{}InvalidClientError.errorCode="invalid_client";class InvalidGrantError extends OAuthError{}InvalidGrantError.errorCode="invalid_grant";class UnauthorizedClientError extends OAuthError{}UnauthorizedClientError.errorCode="unauthorized_client";class UnsupportedGrantTypeError extends OAuthError{}UnsupportedGrantTypeError.errorCode="unsupported_grant_type";class InvalidScopeError extends OAuthError{}InvalidScopeError.errorCode="invalid_scope";class AccessDeniedError extends OAuthError{}AccessDeniedError.errorCode="access_denied";class ServerError extends OAuthError{}ServerError.errorCode="server_error";class TemporarilyUnavailableError extends OAuthError{}TemporarilyUnavailableError.errorCode="temporarily_unavailable";class UnsupportedResponseTypeError extends OAuthError{}UnsupportedResponseTypeError.errorCode="unsupported_response_type";class UnsupportedTokenTypeError extends OAuthError{}UnsupportedTokenTypeError.errorCode="unsupported_token_type";class InvalidTokenError extends OAuthError{}InvalidTokenError.errorCode="invalid_token";class MethodNotAllowedError extends OAuthError{}MethodNotAllowedError.errorCode="method_not_allowed";class TooManyRequestsError extends OAuthError{}TooManyRequestsError.errorCode="too_many_requests";class InvalidClientMetadataError extends OAuthError{}InvalidClientMetadataError.errorCode="invalid_client_metadata";class InsufficientScopeError extends OAuthError{}InsufficientScopeError.errorCode="insufficient_scope";class InvalidTargetError extends OAuthError{}InvalidTargetError.errorCode="invalid_target";var OAUTH_ERRORS={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError.errorCode]:ServerError,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError,[InvalidTargetError.errorCode]:InvalidTargetError};function normalizeHeaders(headers){if(!headers)return{};if(headers instanceof Headers)return Object.fromEntries(headers.entries());if(Array.isArray(headers))return Object.fromEntries(headers);return{...headers}}function createFetchWithInit(baseFetch=fetch,baseInit){if(!baseInit)return baseFetch;return async(url,init)=>{let mergedInit={...baseInit,...init,headers:init?.headers?{...normalizeHeaders(baseInit.headers),...normalizeHeaders(init.headers)}:baseInit.headers};return baseFetch(url,mergedInit)}}var MAX_REDIRECTS=5,REDIRECT_STATUSES=[301,302,303,307,308];function isWithinOrigin(from,to){if(from.protocol===to.protocol&&from.hostname===to.hostname&&from.port===to.port)return!0;return from.hostname===to.hostname&&from.protocol==="http:"&&from.port===""&&to.protocol==="https:"&&to.port===""}function redirectTarget(response,requestUrl){let location=REDIRECT_STATUSES.includes(response.status)?response.headers.get("location"):null;try{return location?new URL(location,requestUrl):void 0}catch{return}}function followWithinOrigin(baseFetch,url,init,response,followed=0){let target=redirectTarget(response,url),keepsMethod=response.status===307||response.status===308||(init?.method??"GET").toUpperCase()==="GET";if(!target||followed===MAX_REDIRECTS||!keepsMethod)return;let from=new URL(url);if((target.username||target.password)&&(target.username!==from.username||target.password!==from.password)||!isWithinOrigin(from,target))return;return Promise.resolve(response.body?.cancel()).then(()=>baseFetch(target,{...init,redirect:"manual"})).then((next)=>followWithinOrigin(baseFetch,target,init,next,followed+1)??next)}var followingFetches=new WeakSet;function fetchLeavingRedirects(baseFetch){let following=(url,init)=>(baseFetch??fetch)(url,init);return followingFetches.add(following),following}function fetchWithinOrigin(baseFetch=fetch){if(followingFetches.has(baseFetch))return baseFetch;return(url,init)=>{if(init?.redirect==="error"||init?.redirect==="manual")return baseFetch(url,init);return Promise.resolve(baseFetch(url,{...init,redirect:"manual"})).then((response)=>followWithinOrigin(baseFetch,url,init,response)??response)}}function unfollowedRedirect(response,requestUrl){if(response.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let from=response.url||requestUrl,target=redirectTarget(response,from);if(!target)return;if(target.username=target.password=target.search=target.hash="",target.protocol==="http:"&&new URL(from).protocol==="https:")return target.protocol="https:",`Redirect to plain http not followed; try ${target.href} instead`;return`Redirect to ${target.href} not followed`}class UnauthorizedError extends Error{constructor(message){super(message??"Unauthorized")}}function isClientAuthMethod(method){return["client_secret_basic","client_secret_post","none"].includes(method)}var AUTHORIZATION_CODE_RESPONSE_TYPE="code",AUTHORIZATION_CODE_CHALLENGE_METHOD="S256";function selectClientAuthMethod(clientInformation,supportedMethods){let hasClientSecret=clientInformation.client_secret!==void 0;if("token_endpoint_auth_method"in clientInformation&&clientInformation.token_endpoint_auth_method&&isClientAuthMethod(clientInformation.token_endpoint_auth_method)&&(supportedMethods.length===0||supportedMethods.includes(clientInformation.token_endpoint_auth_method)))return clientInformation.token_endpoint_auth_method;if(supportedMethods.length===0)return hasClientSecret?"client_secret_basic":"none";if(hasClientSecret&&supportedMethods.includes("client_secret_basic"))return"client_secret_basic";if(hasClientSecret&&supportedMethods.includes("client_secret_post"))return"client_secret_post";if(supportedMethods.includes("none"))return"none";return hasClientSecret?"client_secret_post":"none"}function applyClientAuthentication(method,clientInformation,headers,params){let{client_id,client_secret}=clientInformation;switch(method){case"client_secret_basic":applyBasicAuth(client_id,client_secret,headers);return;case"client_secret_post":applyPostAuth(client_id,client_secret,params);return;case"none":applyPublicAuth(client_id,params);return;default:throw Error(`Unsupported client authentication method: ${method}`)}}function applyBasicAuth(clientId,clientSecret,headers){if(!clientSecret)throw Error("client_secret_basic authentication requires a client_secret");let credentials=btoa(`${clientId}:${clientSecret}`);headers.set("Authorization",`Basic ${credentials}`)}function applyPostAuth(clientId,clientSecret,params){if(params.set("client_id",clientId),clientSecret)params.set("client_secret",clientSecret)}function applyPublicAuth(clientId,params){params.set("client_id",clientId)}async function parseErrorResponse(input){let statusCode=input instanceof Response?input.status:void 0,body=input instanceof Response?await input.text():input;try{let result=OAuthErrorResponseSchema.parse(JSON.parse(body)),{error,error_description,error_uri}=result;return new(OAUTH_ERRORS[error]||ServerError)(error_description||"",error_uri)}catch(error){let redirect=input instanceof Response?unfollowedRedirect(input,input.url):void 0,errorMessage=`${statusCode?`HTTP ${statusCode}: `:""}${redirect??`Invalid OAuth error response: ${error}. Raw body: ${body}`}`;return new ServerError(errorMessage)}}function issuersMatch(a,b){let[x,y]=[a,b];try{[x,y]=[new URL(a).href,new URL(b).href]}catch{}return x===y||x.endsWith("/")&&x.slice(0,-1)===y||y.endsWith("/")&&y.slice(0,-1)===x}function discardIfIssuerMismatch(stored,issuer){if(!stored)return;if(typeof stored.issuer!=="string")return stored.issuer==null?stored:{...stored,issuer:void 0};return issuersMatch(stored.issuer,issuer)?stored:void 0}var TokenResponseSchema=OAuthTokensSchema.omit({issuer:!0}),RegistrationResponseSchema=OAuthClientInformationFullSchema.omit({issuer:!0});function boundElsewhereError(stored,issuer){return Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function auth(provider,options){try{return await authInternal(provider,options)}catch(error){if(error instanceof InvalidClientError||error instanceof UnauthorizedClientError)return await provider.invalidateCredentials?.("all"),await authInternal(provider,options);else if(error instanceof InvalidGrantError)return await provider.invalidateCredentials?.("tokens"),await authInternal(provider,options);throw error}}async function authInternal(provider,{serverUrl,authorizationCode,scope,resourceMetadataUrl,fetchFn}){let cachedState=await provider.discoveryState?.(),resourceMetadata,authorizationServerUrl,metadata,effectiveResourceMetadataUrl=resourceMetadataUrl;if(!effectiveResourceMetadataUrl&&cachedState?.resourceMetadataUrl)effectiveResourceMetadataUrl=new URL(cachedState.resourceMetadataUrl);if(cachedState?.authorizationServerUrl){if(authorizationServerUrl=cachedState.authorizationServerUrl,resourceMetadata=cachedState.resourceMetadata,metadata=cachedState.authorizationServerMetadata??await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn}),!resourceMetadata)try{resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl},fetchFn)}catch{}if(metadata!==cachedState.authorizationServerMetadata||resourceMetadata!==cachedState.resourceMetadata)await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}else{let serverInfo=await discoverOAuthServerInfo(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl,fetchFn});authorizationServerUrl=serverInfo.authorizationServerUrl,metadata=serverInfo.authorizationServerMetadata,resourceMetadata=serverInfo.resourceMetadata,await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}let issuer=String(authorizationServerUrl),selectedResource=await selectResourceURL(serverUrl,provider,resourceMetadata),resource=selectedResource&&resourceMetadata&&!provider.validateResourceURL?resourceMetadata.resource:selectedResource,resolvedScope=scope||resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,storedClientInformation=await Promise.resolve(provider.clientInformation()),clientInformation=discardIfIssuerMismatch(storedClientInformation,issuer),canRegisterAgain=provider.saveClientInformation!==void 0&&!!provider.redirectUrl;if(storedClientInformation&&!clientInformation&&!canRegisterAgain)throw boundElsewhereError(storedClientInformation,issuer);let unstampedClientInformation=clientInformation?.issuer==null?clientInformation:void 0,bindClientInformation=async()=>{try{if(unstampedClientInformation)await provider.saveClientInformation?.({...unstampedClientInformation,issuer})}catch{}};if(!clientInformation){if(authorizationCode!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let supportsUrlBasedClientId=metadata?.client_id_metadata_document_supported===!0,clientMetadataUrl=provider.clientMetadataUrl;if(clientMetadataUrl&&!isHttpsUrl(clientMetadataUrl))throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);if(supportsUrlBasedClientId&&clientMetadataUrl)clientInformation={client_id:clientMetadataUrl,issuer},await provider.saveClientInformation?.(clientInformation);else{if(!provider.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");clientInformation={...await registerClient(authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope:resolvedScope,fetchFn}),issuer},await provider.saveClientInformation(clientInformation)}}let nonInteractiveFlow=!provider.redirectUrl;if(authorizationCode!==void 0||nonInteractiveFlow){let tokens=await fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,fetchFn});return await bindClientInformation(),await provider.saveTokens({...tokens,issuer}),"AUTHORIZED"}let tokens=discardIfIssuerMismatch(await provider.tokens(),issuer);if(tokens?.refresh_token&&tokens.issuer==null)console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");if(tokens?.refresh_token)try{let newTokens=await refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken:tokens.refresh_token,resource,addClientAuthentication:provider.addClientAuthentication,fetchFn});return await bindClientInformation(),await provider.saveTokens({...newTokens,issuer}),"AUTHORIZED"}catch(error){if(!(error instanceof OAuthError)||error instanceof ServerError);else throw error}let state=provider.state?await provider.state():void 0,{authorizationUrl,codeVerifier}=await startAuthorization(authorizationServerUrl,{metadata,clientInformation,state,redirectUrl:provider.redirectUrl,scope:resolvedScope,resource});return await provider.saveCodeVerifier(codeVerifier),await provider.redirectToAuthorization(authorizationUrl),"REDIRECT"}function isHttpsUrl(value){if(!value)return!1;try{let url=new URL(value);return url.protocol==="https:"&&url.pathname!=="/"}catch{return!1}}async function selectResourceURL(serverUrl,provider,resourceMetadata){let defaultResource=resourceUrlFromServerUrl(serverUrl);if(provider.validateResourceURL)return await provider.validateResourceURL(defaultResource,resourceMetadata?.resource);if(!resourceMetadata)return;if(!checkResourceAllowed({requestedResource:defaultResource,configuredResource:resourceMetadata.resource}))throw Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);return new URL(resourceMetadata.resource)}function extractWWWAuthenticateParams(res){let authenticateHeader=res.headers.get("WWW-Authenticate");if(!authenticateHeader)return{};let[type,scheme]=authenticateHeader.split(" ");if(type.toLowerCase()!=="bearer"||!scheme)return{};let resourceMetadataMatch=extractFieldFromWwwAuth(res,"resource_metadata")||void 0,resourceMetadataUrl;if(resourceMetadataMatch)try{resourceMetadataUrl=new URL(resourceMetadataMatch)}catch{}let scope=extractFieldFromWwwAuth(res,"scope")||void 0,error=extractFieldFromWwwAuth(res,"error")||void 0;return{resourceMetadataUrl,scope,error}}function extractFieldFromWwwAuth(response,fieldName){let wwwAuthHeader=response.headers.get("WWW-Authenticate");if(!wwwAuthHeader)return null;let pattern=new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`),match=wwwAuthHeader.match(pattern);if(match)return match[1]||match[2];return null}async function discoverOAuthProtectedResourceMetadata(serverUrl,opts,fetchFn=fetch){let response=await discoverMetadataWithFallback(serverUrl,"oauth-protected-resource",fetchFn,{protocolVersion:opts?.protocolVersion,metadataUrl:opts?.resourceMetadataUrl});if(!response||response.status===404)throw await response?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!response.ok)throw await response.body?.cancel(),Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);return OAuthProtectedResourceMetadataSchema.parse(await response.json())}async function fetchWithCorsRetry(url,headers,fetchFn=fetch){try{return await fetchWithinOrigin(fetchFn)(url,{headers})}catch(error){if(error instanceof TypeError)if(headers)return fetchWithCorsRetry(url,void 0,fetchFn);else return;throw error}}function buildWellKnownPath(wellKnownPrefix,pathname="",options={}){if(pathname.endsWith("/"))pathname=pathname.slice(0,-1);return options.prependPathname?`${pathname}/.well-known/${wellKnownPrefix}`:`/.well-known/${wellKnownPrefix}${pathname}`}async function tryMetadataDiscovery(url,protocolVersion,fetchFn=fetch){return await fetchWithCorsRetry(url,{"MCP-Protocol-Version":protocolVersion},fetchFn)}function shouldAttemptFallback(response,pathname){return!response||!response.ok&&response.status<500&&pathname!=="/"}async function discoverMetadataWithFallback(serverUrl,wellKnownType,fetchFn,opts){let issuer=new URL(serverUrl),protocolVersion=opts?.protocolVersion??LATEST_PROTOCOL_VERSION,url;if(opts?.metadataUrl)url=new URL(opts.metadataUrl);else{let wellKnownPath=buildWellKnownPath(wellKnownType,issuer.pathname);url=new URL(wellKnownPath,opts?.metadataServerUrl??issuer),url.search=issuer.search}let response=await tryMetadataDiscovery(url,protocolVersion,fetchFn);if(!opts?.metadataUrl&&shouldAttemptFallback(response,issuer.pathname)){let rootUrl=new URL(`/.well-known/${wellKnownType}`,issuer);response=await tryMetadataDiscovery(rootUrl,protocolVersion,fetchFn)}return response}function buildDiscoveryUrls(authorizationServerUrl){let url=typeof authorizationServerUrl==="string"?new URL(authorizationServerUrl):authorizationServerUrl,hasPath=url.pathname!=="/",urlsToTry=[];if(!hasPath)return urlsToTry.push({url:new URL("/.well-known/oauth-authorization-server",url.origin),type:"oauth"}),urlsToTry.push({url:new URL("/.well-known/openid-configuration",url.origin),type:"oidc"}),urlsToTry;let pathname=url.pathname;if(pathname.endsWith("/"))pathname=pathname.slice(0,-1);return urlsToTry.push({url:new URL(`/.well-known/oauth-authorization-server${pathname}`,url.origin),type:"oauth"}),urlsToTry.push({url:new URL(`/.well-known/openid-configuration${pathname}`,url.origin),type:"oidc"}),urlsToTry.push({url:new URL(`${pathname}/.well-known/openid-configuration`,url.origin),type:"oidc"}),urlsToTry}async function discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn=fetch,protocolVersion=LATEST_PROTOCOL_VERSION}={}){let headers={"MCP-Protocol-Version":protocolVersion,Accept:"application/json"},urlsToTry=buildDiscoveryUrls(authorizationServerUrl);for(let{url:endpointUrl,type}of urlsToTry){let response=await fetchWithCorsRetry(endpointUrl,headers,fetchFn);if(!response)continue;if(!response.ok){if(await response.body?.cancel(),response.status<500)continue;throw Error(`HTTP ${response.status} trying to load ${type==="oauth"?"OAuth":"OpenID provider"} metadata from ${endpointUrl}`)}if(type==="oauth")return OAuthMetadataSchema.parse(await response.json());else return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json())}return}async function discoverOAuthServerInfo(serverUrl,opts){let resourceMetadata,authorizationServerUrl;try{if(resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:opts?.resourceMetadataUrl},opts?.fetchFn),resourceMetadata.authorization_servers&&resourceMetadata.authorization_servers.length>0)authorizationServerUrl=resourceMetadata.authorization_servers[0]}catch{}if(!authorizationServerUrl)authorizationServerUrl=String(new URL("/",serverUrl));let authorizationServerMetadata=await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn:opts?.fetchFn});return{authorizationServerUrl,authorizationServerMetadata,resourceMetadata}}function resourceIndicatorToString(resource){return typeof resource==="string"?resource:resource.href}async function startAuthorization(authorizationServerUrl,{metadata,clientInformation,redirectUrl,scope,state,resource}){let authorizationUrl;if(metadata){if(authorizationUrl=new URL(metadata.authorization_endpoint),!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))throw Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);if(metadata.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))throw Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`)}else authorizationUrl=new URL("/authorize",authorizationServerUrl);let challenge=await pkceChallenge(),{code_verifier:codeVerifier,code_challenge:codeChallenge}=challenge;if(authorizationUrl.searchParams.set("response_type",AUTHORIZATION_CODE_RESPONSE_TYPE),authorizationUrl.searchParams.set("client_id",clientInformation.client_id),authorizationUrl.searchParams.set("code_challenge",codeChallenge),authorizationUrl.searchParams.set("code_challenge_method",AUTHORIZATION_CODE_CHALLENGE_METHOD),authorizationUrl.searchParams.set("redirect_uri",String(redirectUrl)),state)authorizationUrl.searchParams.set("state",state);if(scope)authorizationUrl.searchParams.set("scope",scope);if(scope?.includes("offline_access"))authorizationUrl.searchParams.append("prompt","consent");if(resource)authorizationUrl.searchParams.set("resource",resourceIndicatorToString(resource));return{authorizationUrl,codeVerifier}}function prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,redirectUri){return new URLSearchParams({grant_type:"authorization_code",code:authorizationCode,code_verifier:codeVerifier,redirect_uri:String(redirectUri)})}async function executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn}){let tokenUrl=metadata?.token_endpoint?new URL(metadata.token_endpoint):new URL("/token",authorizationServerUrl),headers=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(resource)tokenRequestParams.set("resource",resourceIndicatorToString(resource));if(addClientAuthentication)await addClientAuthentication(headers,tokenRequestParams,tokenUrl,metadata);else if(clientInformation){let supportedMethods=metadata?.token_endpoint_auth_methods_supported??[],authMethod=selectClientAuthMethod(clientInformation,supportedMethods);applyClientAuthentication(authMethod,clientInformation,headers,tokenRequestParams)}let response=await fetchWithinOrigin(fetchFn??fetch)(tokenUrl,{method:"POST",headers,body:tokenRequestParams});if(!response.ok)throw await parseErrorResponse(response);return TokenResponseSchema.parse(await response.json())}async function refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken,resource,addClientAuthentication,fetchFn}){let tokenRequestParams=new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken}),tokens=await executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn});return{refresh_token:refreshToken,...tokens}}async function fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,fetchFn}={}){let readClientInformation=async()=>{let storedClientInformation=await provider.clientInformation(),checked=discardIfIssuerMismatch(storedClientInformation,String(authorizationServerUrl));if(storedClientInformation&&!checked)throw boundElsewhereError(storedClientInformation,String(authorizationServerUrl));return checked},clientInformation=await readClientInformation(),scope=provider.clientMetadata.scope,tokenRequestParams;if(provider.prepareTokenRequest)tokenRequestParams=await provider.prepareTokenRequest(scope);if(!tokenRequestParams){if(!authorizationCode)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!provider.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let codeVerifier=await provider.codeVerifier();tokenRequestParams=prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,provider.redirectUrl)}return clientInformation??(clientInformation=await readClientInformation()),executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication:provider.addClientAuthentication,resource,fetchFn})}async function registerClient(authorizationServerUrl,{metadata,clientMetadata,scope,fetchFn}){let registrationUrl;if(metadata){if(!metadata.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");registrationUrl=new URL(metadata.registration_endpoint)}else registrationUrl=new URL("/register",authorizationServerUrl);let response=await fetchWithinOrigin(fetchFn??fetch)(registrationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...clientMetadata,...scope!==void 0?{scope}:{}})});if(!response.ok)throw await parseErrorResponse(response);return RegistrationResponseSchema.parse(await response.json())}import{randomBytes}from"node:crypto";import{link as link2,mkdir,open as open2,readFile,rename,rm,stat,utimes}from"node:fs/promises";import{hostname}from"node:os";import{dirname}from"node:path";import{inspect}from"node:util";class AccessFileError extends Error{reason;file;constructor(reason,file,cause){super(describe2(reason,file,cause),cause===void 0?void 0:{cause});this.reason=reason;this.file=file}}function describe2(reason,file,cause){let detail=cause instanceof Error?cause.message:cause===void 0?"":typeof cause==="string"?cause:inspect(cause);switch(reason){case"unreadable":return`Couldn't read the companion's access file ${file}${detail===""?"":` (${detail})`}. It was left as it is: fix its permissions, or remove it and connect again.`;case"unwritable":return`Couldn't save the companion's access in ${file}${detail===""?"":` (${detail})`}.`;case"locked":return`Another companion process kept ${file} locked. If none is running, remove ${lockFor(file)}.`}}var LOCK_STALE_MS=1e4,LOCK_WAIT_MS=15000,LOST_LOCK_ATTEMPTS=5,lockFor=(file)=>`${file}.lock`,errorCode=(error)=>error instanceof Error?Reflect.get(error,"code"):void 0,pause=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms));async function readAccessFile(file,parse){let text;try{text=await readFile(file,"utf8")}catch(error){if(errorCode(error)==="ENOENT")return;throw new AccessFileError("unreadable",file,error)}let json;try{json=JSON.parse(text)}catch(error){throw new AccessFileError("unreadable",file,error)}if(typeof json!=="object"||json===null||Array.isArray(json))throw new AccessFileError("unreadable",file,"it doesn't hold a JSON object");return parse(json)}async function updateAccessFile(file,parse,change){try{await mkdir(dirname(file),{recursive:!0,mode:448})}catch(error){throw new AccessFileError("unwritable",file,error)}for(let attempt=0;attempt<LOST_LOCK_ATTEMPTS;attempt+=1){let lock=await acquire(file);try{let next=change(await readAccessFile(file,parse));if(await commit(file,next,lock))return}finally{await lock.release()}}throw new AccessFileError("locked",file)}async function commit(file,next,lock){if(next===void 0){if(!await lock.isHeld())return!1;return await rm(file,{force:!0}).catch((error)=>{throw new AccessFileError("unwritable",file,error)}),!0}let temporary=`${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{let handle=await open2(temporary,"wx",384);try{await handle.chmod(384),await handle.writeFile(JSON.stringify(next)),await handle.sync()}finally{await handle.close()}if(!await lock.isHeld())return!1;return await rename(temporary,file),!0}catch(error){throw error instanceof AccessFileError?error:new AccessFileError("unwritable",file,error)}finally{await rm(temporary,{force:!0}).catch(()=>{return})}}async function acquire(file){let path=lockFor(file),deadline=Date.now()+LOCK_WAIT_MS;for(let attempt=0;;attempt+=1){let handle=await open2(path,"wx",384).catch((error)=>{if(errorCode(error)!=="EEXIST")throw new AccessFileError("unwritable",file,error);return});if(handle===void 0){if(await breakIfStale(path))continue;if(Date.now()>deadline)throw new AccessFileError("locked",file);await pause(Math.min(5*2**attempt,100)*(0.5+Math.random()));continue}try{await handle.writeFile(JSON.stringify({pid:process.pid,host:hostname()}));let{ino}=await handle.stat(),isHeld=async()=>await stat(path).then((current)=>current.ino===ino,()=>!1);return{isHeld,release:async()=>{if(await isHeld())await rm(path,{force:!0})}}}catch(error){throw await rm(path,{force:!0}),new AccessFileError("unwritable",file,error)}finally{await handle.close()}}}var isRunning=(pid)=>{try{return process.kill(pid,0),!0}catch(error){return errorCode(error)==="EPERM"}};async function breakIfStale(path){let judged=await stat(path).catch(()=>{return});if(judged===void 0)return!0;let holder=await readFile(path,"utf8").then((text)=>JSON.parse(text)).catch(()=>{return}),pid=typeof holder==="object"&&holder!==null?Reflect.get(holder,"pid"):void 0,host=typeof holder==="object"&&holder!==null?Reflect.get(holder,"host"):void 0;if(!(typeof pid==="number"&&host===hostname()&&pid!==process.pid&&!isRunning(pid))&&Date.now()-judged.mtimeMs<=LOCK_STALE_MS)return!1;let aside=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.stale`;try{await rename(path,aside)}catch{return!0}let moved=await stat(aside).catch(()=>{return});if(moved!==void 0&&moved.ino!==judged.ino)await link2(aside,path).catch(()=>{return}),await utimes(path,moved.atime,moved.mtime).catch(()=>{return});return await rm(aside,{force:!0}),!0}var parseGrant=(raw)=>{let fields=typeof raw==="object"&&raw!==null?new Map(Object.entries(raw)):new Map,tokens=OAuthTokensSchema.safeParse(fields.get("tokens")).data,expiresAt=fields.get("expiresAt");return tokens===void 0?void 0:{tokens,...typeof expiresAt==="number"&&Number.isFinite(expiresAt)?{expiresAt}:{}}},EMPTY={grants:{}};function parseStored(raw){let fields=new Map(Object.entries(raw)),full=OAuthClientInformationFullSchema.safeParse(fields.get("client")),client=full.success?full.data:OAuthClientInformationSchema.safeParse(fields.get("client")).data,rawGrants=fields.get("grants"),grants={};if(typeof rawGrants==="object"&&rawGrants!==null)for(let[workspace,value]of Object.entries(rawGrants)){let grant=parseGrant(value);if(grant!==void 0)grants[workspace]=grant}let legacy=parseGrant(raw);if(legacy!==void 0)grants[""]??=legacy;let codeVerifier=fields.get("codeVerifier");return{...client===void 0?{}:{client},grants,...typeof codeVerifier==="string"?{codeVerifier}:{}}}function originFrom(value){let url=new URL(value??COMPANION_DEFAULT_ORIGIN);if(url.protocol!=="https:"&&!["127.0.0.1","localhost"].includes(url.hostname))throw Error("DiffClarity must be reached over HTTPS, except on this machine.");return url.origin}var stateFileFor=(origin)=>join(process.env.XDG_CONFIG_HOME??join(homedir(),".config"),"diffclarity",`companion-${createHash("sha256").update(origin).digest("hex").slice(0,16)}.json`),mcpUrl=(origin)=>new URL("/mcp",origin),addWorkspaceCommand=(origin)=>`${companionCommand("connect",origin)} --add-workspace`,LOOPBACK_REDIRECT="http://127.0.0.1/callback",EXPIRY_MARGIN_MS=60000;class NeedsSignIn extends Error{}var needsSignIn=(origin)=>new NeedsSignIn(`DiffClarity needs you to allow the companion again in this workspace. Run \`${addWorkspaceCommand(origin)}\` and choose it in the browser.`);class StoredAccess{origin;file;openBrowser;machine;redirect;grantWorkspace;given;readRefresh;issuedState;constructor(origin,file=stateFileFor(origin),openBrowser,machine=hostname2(),workspace){this.origin=origin;this.file=file;this.openBrowser=openBrowser;this.machine=machine;this.grantWorkspace=workspace}get workspace(){return this.grantWorkspace}fetchNamingWorkspace=async(url,init)=>{let response=await fetch(url,init);if(this.grantWorkspace!==void 0||!response.ok)return response;let body=await response.clone().json().catch(()=>null),named=typeof body==="object"&&body!==null?Reflect.get(body,GRANT_WORKSPACE_FIELD):void 0;if(typeof named==="string"&&named.length>0)this.grantWorkspace=named;return response};async read(){return await readAccessFile(this.file,parseStored)??EMPTY}async grant(){return this.grantWorkspace===void 0?void 0:(await this.read()).grants[this.grantWorkspace]}async write(change){await updateAccessFile(this.file,parseStored,(stored)=>change(stored??EMPTY))}useRedirect(url){this.redirect=url}get redirectUrl(){return this.redirect??LOOPBACK_REDIRECT}get clientMetadata(){return{client_name:companionClientName(this.machine),redirect_uris:[LOOPBACK_REDIRECT],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}state(){return this.issuedState=randomBytes2(16).toString("hex"),this.issuedState}async clientInformation(){return(await this.read()).client}async saveClientInformation(client){await this.write((stored)=>({...stored,client}))}async tokens(){let tokens=(await this.grant())?.tokens;return this.readRefresh=tokens?.refresh_token,tokens}async saveTokens(tokens){let workspace=this.grantWorkspace??"";this.grantWorkspace=workspace;let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1000;await this.write((stored)=>({...stored,grants:{...stored.grants,[workspace]:{tokens,...expiresAt===void 0?{}:{expiresAt}}}}))}async redirectToAuthorization(url){if((await this.tokens())?.refresh_token!==void 0)throw Error("DiffClarity didn't renew the companion's access. It may be unreachable.");if(this.openBrowser===void 0)throw needsSignIn(this.origin);this.openBrowser(url)}async saveCodeVerifier(codeVerifier){await this.write((stored)=>({...stored,codeVerifier}))}async codeVerifier(){let{codeVerifier}=await this.read();if(codeVerifier===void 0)throw Error(`The sign-in was started elsewhere. Run \`${companionCommand("connect",this.origin)}\` again.`);return codeVerifier}async invalidateCredentials(scope){if(scope==="discovery")return;let workspace=this.grantWorkspace;if(scope==="tokens"&&workspace===void 0)return;let readRefresh=this.readRefresh;await this.write((stored)=>{let{client,grants,codeVerifier}=stored;if(scope==="tokens"&&readRefresh!==void 0&&grants[workspace??""]?.tokens.refresh_token!==readRefresh)return stored;return{...scope!=="all"&&scope!=="client"&&client!==void 0?{client}:{},grants:scope==="all"?{}:scope==="tokens"?Object.fromEntries(Object.entries(grants).filter(([key])=>key!==workspace)):grants,...scope!=="all"&&scope!=="verifier"&&codeVerifier!==void 0?{codeVerifier}:{}}})}async renew(){if(await auth(this,{serverUrl:mcpUrl(this.origin)})!=="AUTHORIZED")throw needsSignIn(this.origin)}async accessToken(isRefused=!1){let stored=await this.grant(),current=stored?.tokens.access_token,isFresh=stored?.expiresAt===void 0||stored.expiresAt-EXPIRY_MARGIN_MS>Date.now();if(current&&isFresh&&(!isRefused||this.given!==void 0&¤t!==this.given))return this.given=current,current;await this.renew();let renewed=(await this.tokens())?.access_token;if(!renewed)throw Error("DiffClarity didn't issue an access token.");return this.given=renewed,renewed}async forget(){await updateAccessFile(this.file,parseStored,(stored)=>stored?.client===void 0?void 0:{client:stored.client,grants:{}})}}async function savedWorkspaces(file){return Object.keys((await readAccessFile(file,parseStored)??EMPTY).grants)}function openInBrowser(url){let[command,...args]=process.platform==="darwin"?["open",url.href]:process.platform==="win32"?["cmd","/c","start","",url.href]:["xdg-open",url.href];if(command===void 0)return;let child=spawn(command,args,{stdio:"ignore",detached:!0});child.on("error",()=>{return}),child.unref()}async function signIn(origin,state,log,options={}){let machine=options.machine??hostname2(),kept=[],saved=await savedWorkspaces(state);for(let workspace of saved){let quiet=new StoredAccess(origin,state,void 0,machine,workspace),renewal=await quiet.renew().then(()=>null,(error)=>error instanceof Error?error:Error(String(error)));if(renewal===null){kept.push(quiet);continue}if(renewal instanceof AccessFileError)throw renewal;if(!(renewal instanceof NeedsSignIn)){log(`Couldn't renew the access saved in ${state} (${renewal.message}) Trying it anyway.`),kept.push(quiet);continue}log("DiffClarity no longer allows the companion in one of the workspaces it was allowed in; it stops answering there.")}if(kept.length>0){if(log(`Signed in with the access saved in ${state}, for ${kept.length===1?"the workspace":`the ${kept.length} workspaces`} you allowed it in.${options.addWorkspace===!0?"":` To answer in another workspace too, run \`${addWorkspaceCommand(origin)}\`.`}`),options.addWorkspace!==!0)return kept}let open=options.open??openInBrowser,finish=()=>{return},fail=()=>{return},received=new Promise((resolve,reject)=>{finish=resolve,fail=reject}),access,server=createServer((request,response)=>{let url=new URL(request.url??"/","http://127.0.0.1");if(url.pathname!=="/callback"){response.writeHead(404).end();return}if(access?.issuedState===void 0||url.searchParams.get("state")!==access.issuedState){response.writeHead(400).end();return}let code=url.searchParams.get("code"),error=url.searchParams.get("error");if(response.writeHead(200,{"content-type":"text/html; charset=utf-8","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'"}).end(callbackPage(code!==null&&code!=="",origin)),code)finish(code);else fail(Error(error==="access_denied"?"You didn't allow the companion.":`Sign-in failed${error?`: ${error}`:""}.`))});await new Promise((resolve)=>server.listen(0,"127.0.0.1",resolve));try{let address=server.address();if(address===null||typeof address==="string")throw Error("Couldn't listen for the browser's answer.");access=new StoredAccess(origin,state,(url)=>{log(`Allow the companion in your browser, in the workspace it should answer for. If it didn't open, visit:
|
|
79
|
-
${url.href}`),options.onBrowser?.(),open(url)},machine),access.useRedirect(
|
|
78
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.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){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let 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"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;if(extra===void 0||extra===!1||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){let objects=[];for(let member of members){if(typeof member!=="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required=new Set;for(let object of objects){for(let key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===void 0)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object.required??[])required.add(key)}let folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object of objects){let 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){let allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json)return;let unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union=unions[0],keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;let rest=allOf.filter((m)=>m!==union),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){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema=seen.def??seen.schema,_cached={...schema},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),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);if(assignProps(schema,_cached),zodSchema._zod.parent===ref)for(let key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema[key]}if(refSchema.$ref&&refSeen.def)for(let 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]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema.$ref=parentSeen.schema.$ref,parentSeen.def)for(let 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(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json of[seen.schema,seen.def]){let allOf=json?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}for(let allOf of ctx.intersections)for(let json of carriers.get(allOf)??[])foldIntersection(json)}}let 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){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==void 0&&result.id===rootMetaId)delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let 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{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;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!0;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===void 0||value>agg[key])agg[key]=value},narrowMax=(agg,key,value)=>{if(agg[key]===void 0||value<agg[key])agg[key]=value},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{if(agg.multipleOf??(agg.multipleOf=[]),!agg.multipleOf.includes(value))agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{if(agg.format=format,format.includes("int"))agg.isInt=!0},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},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)=>{if(setFormat(agg,def.format),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=!0},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;if(bag.minimum!==void 0)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==void 0)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==void 0)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==void 0)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==void 0)addDivisor(agg,bag.multipleOf);if(bag.format!==void 0){if(agg.format??(agg.format=bag.format),bag.format.includes("int"))agg.isInt=!0}if(bag.mime)intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=(p)=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time"||laxFormat)delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let 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}))]}},numberProcessor=(schema,ctx,_json,params)=>{let json=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin)if(legacy)json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;else if(typeof minimum==="number")json.minimum=minimum;if(exMax)if(legacy)json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;else if(typeof maximum==="number")json.maximum=maximum;if(multipleOf){let divisors=new Set;for(let 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`);let[first,...rest]=divisors;if(first!==void 0)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{};var enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,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},literalProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;if(def.values.length===0){json.not={};return}let vals=[];for(let val of def.values)if(val===void 0){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){let val=vals[0];if(json.type=val===null?"null":typeof val,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 customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom 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 arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{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){let 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)=>{let json=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema"))return;json.type="object",json.properties={};for(let key in shape)assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)requiredKeys.push(key)}if(requiredKeys.length>0)json.required=requiredKeys;if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,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},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf,ctx.intersections.push(allOf)};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);let def=bySchema.get(json)?.def;if(!def)return json;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}let types=Array.isArray(json.type)?json.type:[json.type],numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer"),values=json.enum??(json.const!==void 0?[json.const]:void 0);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;let{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;if(rest.type="string",!values)rest.pattern=(types.includes("number")?number3:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}var recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let 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"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues.map(String)}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;return unrepresentable=!0,null});if(!unrepresentable)return JSON.parse(serialized);return handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0};var optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType};var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key,{value,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let 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:!0,enumerable:!1,get(){return this.issues.length===0}})};var ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse3=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_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,inst),{check(...chks){let 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:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){return reg.add(this,meta),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional3(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional3(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array2(this)},or(arg){return union2([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform3(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).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 parseAsync(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate2(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 encodeAsync(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode(this,data,params)},safeDecode(data,params){return safeDecode(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,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())}})),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 string4(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.isFinite=!0},derived({minValue:(inst)=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{let{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 number4(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)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});function boolean3(params){return _boolean(ZodBoolean,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,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,json,params)=>anyProcessor(inst,ctx,json,params)});function any2(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});function unknown2(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});function never3(params){return _never(ZodNever,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,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 array2(element,params){return _array(ZodArray,element,params)}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),installLazyProp(inst,"shape",(self)=>self._zod.def.shape,!1)},{keyof(){return _enum(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:unknown2()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown2()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never3()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge2(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit2(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){let def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown2(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});function union2(options,params){return new ZodUnion({type:"union",options,...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,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record3(keyType,valueType,params){if(!valueType||!valueType._zod)return new ZodRecord({type:"record",keyType:string4(),valueType:keyType,...normalizeParams(valueType)});return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;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,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw 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 ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,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{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;if(_issue.code??(_issue.code="custom"),!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst),payload.issues.push(issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output)=>(payload.value=output,payload));return payload.value=output,payload}});function transform3(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,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function optional3(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,json,params)=>optionalProcessor(inst,ctx,json,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,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(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,json,params)=>prefaultProcessor(inst,ctx,json,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,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform3(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"};var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function number5(params){return _coercedNumber(ZodNumber,params)}var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=custom((v)=>v!==null&&(typeof v==="object"||typeof v==="function")),ProgressTokenSchema=union2([string4(),number4().int()]),CursorSchema=string4(),TaskCreationParamsSchema=looseObject({ttl:number4().optional(),pollInterval:number4().optional()}),TaskMetadataSchema=object({ttl:number4().optional()}),RelatedTaskMetadataSchema=object({taskId:string4()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=(value)=>TaskAugmentedRequestParamsSchema.safeParse(value).success,RequestSchema=object({method:string4(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string4(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union2([string4(),number4().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=(value)=>JSONRPCRequestSchema.safeParse(value).success,JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=(value)=>JSONRPCNotificationSchema.safeParse(value).success,JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=(value)=>JSONRPCResultResponseSchema.safeParse(value).success;var ErrorCode;(function(ErrorCode){ErrorCode[ErrorCode.ConnectionClosed=-32000]="ConnectionClosed",ErrorCode[ErrorCode.RequestTimeout=-32001]="RequestTimeout",ErrorCode[ErrorCode.ParseError=-32700]="ParseError",ErrorCode[ErrorCode.InvalidRequest=-32600]="InvalidRequest",ErrorCode[ErrorCode.MethodNotFound=-32601]="MethodNotFound",ErrorCode[ErrorCode.InvalidParams=-32602]="InvalidParams",ErrorCode[ErrorCode.InternalError=-32603]="InternalError",ErrorCode[ErrorCode.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number4().int(),message:string4(),data:unknown2().optional()})}).strict();var isJSONRPCErrorResponse=(value)=>JSONRPCErrorResponseSchema.safeParse(value).success;var JSONRPCMessageSchema=union2([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union2([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string4().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string4(),mimeType:string4().optional(),sizes:array2(string4()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array2(IconSchema).optional()}),BaseMetadataSchema=object({name:string4(),title:string4().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string4(),websiteUrl:string4().optional(),description:string4().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean3().optional()}),record3(string4(),unknown2())),ElicitationCapabilitySchema=preprocess((value)=>{if(value&&typeof value==="object"&&!Array.isArray(value)){if(Object.keys(value).length===0)return{form:{}}}return value},intersection(object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record3(string4(),unknown2()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record3(string4(),AssertObjectSchema).optional(),sampling:object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean3().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record3(string4(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string4(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=object({experimental:record3(string4(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object({listChanged:boolean3().optional()}).optional(),resources:object({subscribe:boolean3().optional(),listChanged:boolean3().optional()}).optional(),tools:object({listChanged:boolean3().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record3(string4(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string4(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string4().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),isInitializedNotification=(value)=>InitializedNotificationSchema.safeParse(value).success,PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number4(),total:optional3(number4()),message:optional3(string4())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string4(),status:TaskStatusSchema,ttl:union2([number4(),_null3()]),createdAt:string4(),lastUpdatedAt:string4(),pollInterval:optional3(number4()),statusMessage:optional3(string4())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string4()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string4()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array2(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string4()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object({uri:string4(),mimeType:optional3(string4()),_meta:record3(string4(),unknown2()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string4()}),Base64Schema=string4().refine((val)=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array2(RoleSchema).optional(),priority:number4().min(0).max(1).optional(),lastModified:datetime2({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string4(),description:optional3(string4()),mimeType:optional3(string4()),size:optional3(number4()),annotations:AnnotationsSchema.optional(),_meta:optional3(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string4(),description:optional3(string4()),mimeType:optional3(string4()),annotations:AnnotationsSchema.optional(),_meta:optional3(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array2(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array2(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string4()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array2(union2([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string4()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string4(),description:optional3(string4()),required:optional3(boolean3())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional3(string4()),arguments:optional3(array2(PromptArgumentSchema)),_meta:optional3(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array2(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string4(),arguments:record3(string4(),string4()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string4(),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string4(),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string4(),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string4(),id:string4(),input:record3(string4(),unknown2()),_meta:record3(string4(),unknown2()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union2([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union2([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string4().optional(),messages:array2(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string4().optional(),readOnlyHint:boolean3().optional(),destructiveHint:boolean3().optional(),idempotentHint:boolean3().optional(),openWorldHint:boolean3().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string4().optional(),inputSchema:object({type:literal("object"),properties:record3(string4(),AssertObjectSchema).optional(),required:array2(string4()).optional()}).catchall(unknown2()),outputSchema:object({type:literal("object"),properties:record3(string4(),AssertObjectSchema).optional(),required:array2(string4()).optional()}).catchall(unknown2()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record3(string4(),unknown2()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array2(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array2(ContentBlockSchema).default([]),structuredContent:record3(string4(),unknown2()).optional(),isError:boolean3().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown2()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string4(),arguments:record3(string4(),unknown2()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean3().default(!0),debounceMs:number4().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string4().optional(),data:unknown2()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string4().optional()}),ModelPreferencesSchema=object({hints:array2(ModelHintSchema).optional(),costPriority:number4().min(0).max(1).optional(),speedPriority:number4().min(0).max(1).optional(),intelligencePriority:number4().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string4().describe("The unique identifier for the corresponding tool call."),content:array2(ContentBlockSchema).default([]),structuredContent:object({}).loose().optional(),isError:boolean3().optional(),_meta:record3(string4(),unknown2()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union2([SamplingMessageContentBlockSchema,array2(SamplingMessageContentBlockSchema)]),_meta:record3(string4(),unknown2()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array2(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string4().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number4().optional(),maxTokens:number4().int(),stopSequences:array2(string4()).optional(),metadata:AssertObjectSchema.optional(),tools:array2(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string4(),stopReason:optional3(_enum(["endTurn","stopSequence","maxTokens"]).or(string4())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string4(),stopReason:optional3(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string4())),role:RoleSchema,content:union2([SamplingMessageContentBlockSchema,array2(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string4().optional(),description:string4().optional(),default:boolean3().optional()}),StringSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),minLength:number4().optional(),maxLength:number4().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string4().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string4().optional(),description:string4().optional(),minimum:number4().optional(),maximum:number4().optional(),default:number4().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),enum:array2(string4()),default:string4().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),oneOf:array2(object({const:string4(),title:string4()})),default:string4().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string4().optional(),description:string4().optional(),enum:array2(string4()),enumNames:array2(string4()).optional(),default:string4().optional()}),SingleSelectEnumSchemaSchema=union2([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string4().optional(),description:string4().optional(),minItems:number4().optional(),maxItems:number4().optional(),items:object({type:literal("string"),enum:array2(string4())}),default:array2(string4()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string4().optional(),description:string4().optional(),minItems:number4().optional(),maxItems:number4().optional(),items:object({anyOf:array2(object({const:string4(),title:string4()}))}),default:array2(string4()).optional()}),MultiSelectEnumSchemaSchema=union2([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union2([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union2([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string4(),requestedSchema:object({type:literal("object"),properties:record3(string4(),PrimitiveSchemaDefinitionSchema),required:array2(string4()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string4(),elicitationId:string4(),url:string4().url()}),ElicitRequestParamsSchema=union2([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string4()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess((val)=>val===null?void 0:val,record3(string4(),union2([string4(),number4(),boolean3(),array2(string4())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string4()});var PromptReferenceSchema=object({type:literal("ref/prompt"),name:string4()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union2([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string4(),value:string4()}),context:object({arguments:record3(string4(),string4()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});var CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array2(string4()).max(100),total:optional3(number4().int()),hasMore:optional3(boolean3())})}),RootSchema=object({uri:string4().startsWith("file://"),name:string4().optional(),_meta:record3(string4(),unknown2()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array2(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union2([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union2([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union2([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union2([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union2([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union2([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);class McpError extends Error{constructor(code,message,data){super(`MCP error ${code}: ${message}`);this.code=code,this.data=data,this.name="McpError"}static fromError(code,message,data){if(code===ErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new McpError(code,message,data)}}class UrlElicitationRequiredError extends McpError{constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}}var SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine((url)=>{let u=new URL(url);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string4().url(),authorization_servers:array2(SafeUrlSchema).optional(),jwks_uri:string4().url().optional(),scopes_supported:array2(string4()).optional(),bearer_methods_supported:array2(string4()).optional(),resource_signing_alg_values_supported:array2(string4()).optional(),resource_name:string4().optional(),resource_documentation:string4().optional(),resource_policy_uri:string4().url().optional(),resource_tos_uri:string4().url().optional(),tls_client_certificate_bound_access_tokens:boolean3().optional(),authorization_details_types_supported:array2(string4()).optional(),dpop_signing_alg_values_supported:array2(string4()).optional(),dpop_bound_access_tokens_required:boolean3().optional()}),OAuthMetadataSchema=looseObject({issuer:string4(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array2(string4()).optional(),response_types_supported:array2(string4()),response_modes_supported:array2(string4()).optional(),grant_types_supported:array2(string4()).optional(),token_endpoint_auth_methods_supported:array2(string4()).optional(),token_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array2(string4()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),introspection_endpoint:string4().optional(),introspection_endpoint_auth_methods_supported:array2(string4()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),code_challenge_methods_supported:array2(string4()).optional(),client_id_metadata_document_supported:boolean3().optional()}),OpenIdProviderMetadataSchema=looseObject({issuer:string4(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array2(string4()).optional(),response_types_supported:array2(string4()),response_modes_supported:array2(string4()).optional(),grant_types_supported:array2(string4()).optional(),acr_values_supported:array2(string4()).optional(),subject_types_supported:array2(string4()),id_token_signing_alg_values_supported:array2(string4()),id_token_encryption_alg_values_supported:array2(string4()).optional(),id_token_encryption_enc_values_supported:array2(string4()).optional(),userinfo_signing_alg_values_supported:array2(string4()).optional(),userinfo_encryption_alg_values_supported:array2(string4()).optional(),userinfo_encryption_enc_values_supported:array2(string4()).optional(),request_object_signing_alg_values_supported:array2(string4()).optional(),request_object_encryption_alg_values_supported:array2(string4()).optional(),request_object_encryption_enc_values_supported:array2(string4()).optional(),token_endpoint_auth_methods_supported:array2(string4()).optional(),token_endpoint_auth_signing_alg_values_supported:array2(string4()).optional(),display_values_supported:array2(string4()).optional(),claim_types_supported:array2(string4()).optional(),claims_supported:array2(string4()).optional(),service_documentation:string4().optional(),claims_locales_supported:array2(string4()).optional(),ui_locales_supported:array2(string4()).optional(),claims_parameter_supported:boolean3().optional(),request_parameter_supported:boolean3().optional(),request_uri_parameter_supported:boolean3().optional(),require_request_uri_registration:boolean3().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean3().optional()}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string4(),id_token:string4().optional(),token_type:string4(),expires_in:number5().optional(),scope:string4().optional(),refresh_token:string4().optional(),issuer:string4().optional().catch(void 0)}).strip(),OAuthErrorResponseSchema=object({error:string4(),error_description:string4().optional(),error_uri:string4().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{return})),OAuthClientMetadataSchema=object({redirect_uris:array2(SafeUrlSchema),token_endpoint_auth_method:string4().optional(),grant_types:array2(string4()).optional(),response_types:array2(string4()).optional(),client_name:string4().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string4().optional(),contacts:array2(string4()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string4().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any2().optional(),software_id:string4().optional(),software_version:string4().optional(),software_statement:string4().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string4(),client_secret:string4().optional(),client_id_issued_at:number4().optional(),client_secret_expires_at:number4().optional(),issuer:string4().optional().catch(void 0)}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string4(),error_description:string4().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string4(),token_type_hint:string4().optional()}).strip();function resourceUrlFromServerUrl(url){let resourceURL=typeof url==="string"?new URL(url):new URL(url.href);return resourceURL.hash="",resourceURL}function checkResourceAllowed({requestedResource,configuredResource}){let requested=typeof requestedResource==="string"?new URL(requestedResource):new URL(requestedResource.href),configured=typeof configuredResource==="string"?new URL(configuredResource):new URL(configuredResource.href);if(requested.origin!==configured.origin)return!1;if(requested.pathname.length<configured.pathname.length)return!1;let requestedPath=requested.pathname.endsWith("/")?requested.pathname:requested.pathname+"/",configuredPath=configured.pathname.endsWith("/")?configured.pathname:configured.pathname+"/";return requestedPath.startsWith(configuredPath)}class OAuthError extends Error{constructor(message,errorUri){super(message);this.errorUri=errorUri,this.name=this.constructor.name}toResponseObject(){let response={error:this.errorCode,error_description:this.message};if(this.errorUri)response.error_uri=this.errorUri;return response}get errorCode(){return this.constructor.errorCode}}class InvalidRequestError extends OAuthError{}InvalidRequestError.errorCode="invalid_request";class InvalidClientError extends OAuthError{}InvalidClientError.errorCode="invalid_client";class InvalidGrantError extends OAuthError{}InvalidGrantError.errorCode="invalid_grant";class UnauthorizedClientError extends OAuthError{}UnauthorizedClientError.errorCode="unauthorized_client";class UnsupportedGrantTypeError extends OAuthError{}UnsupportedGrantTypeError.errorCode="unsupported_grant_type";class InvalidScopeError extends OAuthError{}InvalidScopeError.errorCode="invalid_scope";class AccessDeniedError extends OAuthError{}AccessDeniedError.errorCode="access_denied";class ServerError extends OAuthError{}ServerError.errorCode="server_error";class TemporarilyUnavailableError extends OAuthError{}TemporarilyUnavailableError.errorCode="temporarily_unavailable";class UnsupportedResponseTypeError extends OAuthError{}UnsupportedResponseTypeError.errorCode="unsupported_response_type";class UnsupportedTokenTypeError extends OAuthError{}UnsupportedTokenTypeError.errorCode="unsupported_token_type";class InvalidTokenError extends OAuthError{}InvalidTokenError.errorCode="invalid_token";class MethodNotAllowedError extends OAuthError{}MethodNotAllowedError.errorCode="method_not_allowed";class TooManyRequestsError extends OAuthError{}TooManyRequestsError.errorCode="too_many_requests";class InvalidClientMetadataError extends OAuthError{}InvalidClientMetadataError.errorCode="invalid_client_metadata";class InsufficientScopeError extends OAuthError{}InsufficientScopeError.errorCode="insufficient_scope";class InvalidTargetError extends OAuthError{}InvalidTargetError.errorCode="invalid_target";var OAUTH_ERRORS={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError.errorCode]:ServerError,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError,[InvalidTargetError.errorCode]:InvalidTargetError};function normalizeHeaders(headers){if(!headers)return{};if(headers instanceof Headers)return Object.fromEntries(headers.entries());if(Array.isArray(headers))return Object.fromEntries(headers);return{...headers}}function createFetchWithInit(baseFetch=fetch,baseInit){if(!baseInit)return baseFetch;return async(url,init)=>{let mergedInit={...baseInit,...init,headers:init?.headers?{...normalizeHeaders(baseInit.headers),...normalizeHeaders(init.headers)}:baseInit.headers};return baseFetch(url,mergedInit)}}var MAX_REDIRECTS=5,REDIRECT_STATUSES=[301,302,303,307,308];function isWithinOrigin(from,to){if(from.protocol===to.protocol&&from.hostname===to.hostname&&from.port===to.port)return!0;return from.hostname===to.hostname&&from.protocol==="http:"&&from.port===""&&to.protocol==="https:"&&to.port===""}function redirectTarget(response,requestUrl){let location=REDIRECT_STATUSES.includes(response.status)?response.headers.get("location"):null;try{return location?new URL(location,requestUrl):void 0}catch{return}}function followWithinOrigin(baseFetch,url,init,response,followed=0){let target=redirectTarget(response,url),keepsMethod=response.status===307||response.status===308||(init?.method??"GET").toUpperCase()==="GET";if(!target||followed===MAX_REDIRECTS||!keepsMethod)return;let from=new URL(url);if((target.username||target.password)&&(target.username!==from.username||target.password!==from.password)||!isWithinOrigin(from,target))return;return Promise.resolve(response.body?.cancel()).then(()=>baseFetch(target,{...init,redirect:"manual"})).then((next)=>followWithinOrigin(baseFetch,target,init,next,followed+1)??next)}var followingFetches=new WeakSet;function fetchLeavingRedirects(baseFetch){let following=(url,init)=>(baseFetch??fetch)(url,init);return followingFetches.add(following),following}function fetchWithinOrigin(baseFetch=fetch){if(followingFetches.has(baseFetch))return baseFetch;return(url,init)=>{if(init?.redirect==="error"||init?.redirect==="manual")return baseFetch(url,init);return Promise.resolve(baseFetch(url,{...init,redirect:"manual"})).then((response)=>followWithinOrigin(baseFetch,url,init,response)??response)}}function unfollowedRedirect(response,requestUrl){if(response.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let from=response.url||requestUrl,target=redirectTarget(response,from);if(!target)return;if(target.username=target.password=target.search=target.hash="",target.protocol==="http:"&&new URL(from).protocol==="https:")return target.protocol="https:",`Redirect to plain http not followed; try ${target.href} instead`;return`Redirect to ${target.href} not followed`}class UnauthorizedError extends Error{constructor(message){super(message??"Unauthorized")}}function isClientAuthMethod(method){return["client_secret_basic","client_secret_post","none"].includes(method)}var AUTHORIZATION_CODE_RESPONSE_TYPE="code",AUTHORIZATION_CODE_CHALLENGE_METHOD="S256";function selectClientAuthMethod(clientInformation,supportedMethods){let hasClientSecret=clientInformation.client_secret!==void 0;if("token_endpoint_auth_method"in clientInformation&&clientInformation.token_endpoint_auth_method&&isClientAuthMethod(clientInformation.token_endpoint_auth_method)&&(supportedMethods.length===0||supportedMethods.includes(clientInformation.token_endpoint_auth_method)))return clientInformation.token_endpoint_auth_method;if(supportedMethods.length===0)return hasClientSecret?"client_secret_basic":"none";if(hasClientSecret&&supportedMethods.includes("client_secret_basic"))return"client_secret_basic";if(hasClientSecret&&supportedMethods.includes("client_secret_post"))return"client_secret_post";if(supportedMethods.includes("none"))return"none";return hasClientSecret?"client_secret_post":"none"}function applyClientAuthentication(method,clientInformation,headers,params){let{client_id,client_secret}=clientInformation;switch(method){case"client_secret_basic":applyBasicAuth(client_id,client_secret,headers);return;case"client_secret_post":applyPostAuth(client_id,client_secret,params);return;case"none":applyPublicAuth(client_id,params);return;default:throw Error(`Unsupported client authentication method: ${method}`)}}function applyBasicAuth(clientId,clientSecret,headers){if(!clientSecret)throw Error("client_secret_basic authentication requires a client_secret");let credentials=btoa(`${clientId}:${clientSecret}`);headers.set("Authorization",`Basic ${credentials}`)}function applyPostAuth(clientId,clientSecret,params){if(params.set("client_id",clientId),clientSecret)params.set("client_secret",clientSecret)}function applyPublicAuth(clientId,params){params.set("client_id",clientId)}async function parseErrorResponse(input){let statusCode=input instanceof Response?input.status:void 0,body=input instanceof Response?await input.text():input;try{let result=OAuthErrorResponseSchema.parse(JSON.parse(body)),{error,error_description,error_uri}=result;return new(OAUTH_ERRORS[error]||ServerError)(error_description||"",error_uri)}catch(error){let redirect=input instanceof Response?unfollowedRedirect(input,input.url):void 0,errorMessage=`${statusCode?`HTTP ${statusCode}: `:""}${redirect??`Invalid OAuth error response: ${error}. Raw body: ${body}`}`;return new ServerError(errorMessage)}}function issuersMatch(a,b){let[x,y]=[a,b];try{[x,y]=[new URL(a).href,new URL(b).href]}catch{}return x===y||x.endsWith("/")&&x.slice(0,-1)===y||y.endsWith("/")&&y.slice(0,-1)===x}function discardIfIssuerMismatch(stored,issuer){if(!stored)return;if(typeof stored.issuer!=="string")return stored.issuer==null?stored:{...stored,issuer:void 0};return issuersMatch(stored.issuer,issuer)?stored:void 0}var TokenResponseSchema=OAuthTokensSchema.omit({issuer:!0}),RegistrationResponseSchema=OAuthClientInformationFullSchema.omit({issuer:!0});function boundElsewhereError(stored,issuer){return Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function auth(provider,options){try{return await authInternal(provider,options)}catch(error){if(error instanceof InvalidClientError||error instanceof UnauthorizedClientError)return await provider.invalidateCredentials?.("all"),await authInternal(provider,options);else if(error instanceof InvalidGrantError)return await provider.invalidateCredentials?.("tokens"),await authInternal(provider,options);throw error}}async function authInternal(provider,{serverUrl,authorizationCode,scope,resourceMetadataUrl,fetchFn}){let cachedState=await provider.discoveryState?.(),resourceMetadata,authorizationServerUrl,metadata,effectiveResourceMetadataUrl=resourceMetadataUrl;if(!effectiveResourceMetadataUrl&&cachedState?.resourceMetadataUrl)effectiveResourceMetadataUrl=new URL(cachedState.resourceMetadataUrl);if(cachedState?.authorizationServerUrl){if(authorizationServerUrl=cachedState.authorizationServerUrl,resourceMetadata=cachedState.resourceMetadata,metadata=cachedState.authorizationServerMetadata??await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn}),!resourceMetadata)try{resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl},fetchFn)}catch{}if(metadata!==cachedState.authorizationServerMetadata||resourceMetadata!==cachedState.resourceMetadata)await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}else{let serverInfo=await discoverOAuthServerInfo(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl,fetchFn});authorizationServerUrl=serverInfo.authorizationServerUrl,metadata=serverInfo.authorizationServerMetadata,resourceMetadata=serverInfo.resourceMetadata,await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}let issuer=String(authorizationServerUrl),selectedResource=await selectResourceURL(serverUrl,provider,resourceMetadata),resource=selectedResource&&resourceMetadata&&!provider.validateResourceURL?resourceMetadata.resource:selectedResource,resolvedScope=scope||resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,storedClientInformation=await Promise.resolve(provider.clientInformation()),clientInformation=discardIfIssuerMismatch(storedClientInformation,issuer),canRegisterAgain=provider.saveClientInformation!==void 0&&!!provider.redirectUrl;if(storedClientInformation&&!clientInformation&&!canRegisterAgain)throw boundElsewhereError(storedClientInformation,issuer);let unstampedClientInformation=clientInformation?.issuer==null?clientInformation:void 0,bindClientInformation=async()=>{try{if(unstampedClientInformation)await provider.saveClientInformation?.({...unstampedClientInformation,issuer})}catch{}};if(!clientInformation){if(authorizationCode!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let supportsUrlBasedClientId=metadata?.client_id_metadata_document_supported===!0,clientMetadataUrl=provider.clientMetadataUrl;if(clientMetadataUrl&&!isHttpsUrl(clientMetadataUrl))throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);if(supportsUrlBasedClientId&&clientMetadataUrl)clientInformation={client_id:clientMetadataUrl,issuer},await provider.saveClientInformation?.(clientInformation);else{if(!provider.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");clientInformation={...await registerClient(authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope:resolvedScope,fetchFn}),issuer},await provider.saveClientInformation(clientInformation)}}let nonInteractiveFlow=!provider.redirectUrl;if(authorizationCode!==void 0||nonInteractiveFlow){let tokens=await fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,fetchFn});return await bindClientInformation(),await provider.saveTokens({...tokens,issuer}),"AUTHORIZED"}let tokens=discardIfIssuerMismatch(await provider.tokens(),issuer);if(tokens?.refresh_token&&tokens.issuer==null)console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");if(tokens?.refresh_token)try{let newTokens=await refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken:tokens.refresh_token,resource,addClientAuthentication:provider.addClientAuthentication,fetchFn});return await bindClientInformation(),await provider.saveTokens({...newTokens,issuer}),"AUTHORIZED"}catch(error){if(!(error instanceof OAuthError)||error instanceof ServerError);else throw error}let state=provider.state?await provider.state():void 0,{authorizationUrl,codeVerifier}=await startAuthorization(authorizationServerUrl,{metadata,clientInformation,state,redirectUrl:provider.redirectUrl,scope:resolvedScope,resource});return await provider.saveCodeVerifier(codeVerifier),await provider.redirectToAuthorization(authorizationUrl),"REDIRECT"}function isHttpsUrl(value){if(!value)return!1;try{let url=new URL(value);return url.protocol==="https:"&&url.pathname!=="/"}catch{return!1}}async function selectResourceURL(serverUrl,provider,resourceMetadata){let defaultResource=resourceUrlFromServerUrl(serverUrl);if(provider.validateResourceURL)return await provider.validateResourceURL(defaultResource,resourceMetadata?.resource);if(!resourceMetadata)return;if(!checkResourceAllowed({requestedResource:defaultResource,configuredResource:resourceMetadata.resource}))throw Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);return new URL(resourceMetadata.resource)}function extractWWWAuthenticateParams(res){let authenticateHeader=res.headers.get("WWW-Authenticate");if(!authenticateHeader)return{};let[type,scheme]=authenticateHeader.split(" ");if(type.toLowerCase()!=="bearer"||!scheme)return{};let resourceMetadataMatch=extractFieldFromWwwAuth(res,"resource_metadata")||void 0,resourceMetadataUrl;if(resourceMetadataMatch)try{resourceMetadataUrl=new URL(resourceMetadataMatch)}catch{}let scope=extractFieldFromWwwAuth(res,"scope")||void 0,error=extractFieldFromWwwAuth(res,"error")||void 0;return{resourceMetadataUrl,scope,error}}function extractFieldFromWwwAuth(response,fieldName){let wwwAuthHeader=response.headers.get("WWW-Authenticate");if(!wwwAuthHeader)return null;let pattern=new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`),match=wwwAuthHeader.match(pattern);if(match)return match[1]||match[2];return null}async function discoverOAuthProtectedResourceMetadata(serverUrl,opts,fetchFn=fetch){let response=await discoverMetadataWithFallback(serverUrl,"oauth-protected-resource",fetchFn,{protocolVersion:opts?.protocolVersion,metadataUrl:opts?.resourceMetadataUrl});if(!response||response.status===404)throw await response?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!response.ok)throw await response.body?.cancel(),Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);return OAuthProtectedResourceMetadataSchema.parse(await response.json())}async function fetchWithCorsRetry(url,headers,fetchFn=fetch){try{return await fetchWithinOrigin(fetchFn)(url,{headers})}catch(error){if(error instanceof TypeError)if(headers)return fetchWithCorsRetry(url,void 0,fetchFn);else return;throw error}}function buildWellKnownPath(wellKnownPrefix,pathname="",options={}){if(pathname.endsWith("/"))pathname=pathname.slice(0,-1);return options.prependPathname?`${pathname}/.well-known/${wellKnownPrefix}`:`/.well-known/${wellKnownPrefix}${pathname}`}async function tryMetadataDiscovery(url,protocolVersion,fetchFn=fetch){return await fetchWithCorsRetry(url,{"MCP-Protocol-Version":protocolVersion},fetchFn)}function shouldAttemptFallback(response,pathname){return!response||!response.ok&&response.status<500&&pathname!=="/"}async function discoverMetadataWithFallback(serverUrl,wellKnownType,fetchFn,opts){let issuer=new URL(serverUrl),protocolVersion=opts?.protocolVersion??LATEST_PROTOCOL_VERSION,url;if(opts?.metadataUrl)url=new URL(opts.metadataUrl);else{let wellKnownPath=buildWellKnownPath(wellKnownType,issuer.pathname);url=new URL(wellKnownPath,opts?.metadataServerUrl??issuer),url.search=issuer.search}let response=await tryMetadataDiscovery(url,protocolVersion,fetchFn);if(!opts?.metadataUrl&&shouldAttemptFallback(response,issuer.pathname)){let rootUrl=new URL(`/.well-known/${wellKnownType}`,issuer);response=await tryMetadataDiscovery(rootUrl,protocolVersion,fetchFn)}return response}function buildDiscoveryUrls(authorizationServerUrl){let url=typeof authorizationServerUrl==="string"?new URL(authorizationServerUrl):authorizationServerUrl,hasPath=url.pathname!=="/",urlsToTry=[];if(!hasPath)return urlsToTry.push({url:new URL("/.well-known/oauth-authorization-server",url.origin),type:"oauth"}),urlsToTry.push({url:new URL("/.well-known/openid-configuration",url.origin),type:"oidc"}),urlsToTry;let pathname=url.pathname;if(pathname.endsWith("/"))pathname=pathname.slice(0,-1);return urlsToTry.push({url:new URL(`/.well-known/oauth-authorization-server${pathname}`,url.origin),type:"oauth"}),urlsToTry.push({url:new URL(`/.well-known/openid-configuration${pathname}`,url.origin),type:"oidc"}),urlsToTry.push({url:new URL(`${pathname}/.well-known/openid-configuration`,url.origin),type:"oidc"}),urlsToTry}async function discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn=fetch,protocolVersion=LATEST_PROTOCOL_VERSION}={}){let headers={"MCP-Protocol-Version":protocolVersion,Accept:"application/json"},urlsToTry=buildDiscoveryUrls(authorizationServerUrl);for(let{url:endpointUrl,type}of urlsToTry){let response=await fetchWithCorsRetry(endpointUrl,headers,fetchFn);if(!response)continue;if(!response.ok){if(await response.body?.cancel(),response.status<500)continue;throw Error(`HTTP ${response.status} trying to load ${type==="oauth"?"OAuth":"OpenID provider"} metadata from ${endpointUrl}`)}if(type==="oauth")return OAuthMetadataSchema.parse(await response.json());else return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json())}return}async function discoverOAuthServerInfo(serverUrl,opts){let resourceMetadata,authorizationServerUrl;try{if(resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:opts?.resourceMetadataUrl},opts?.fetchFn),resourceMetadata.authorization_servers&&resourceMetadata.authorization_servers.length>0)authorizationServerUrl=resourceMetadata.authorization_servers[0]}catch{}if(!authorizationServerUrl)authorizationServerUrl=String(new URL("/",serverUrl));let authorizationServerMetadata=await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn:opts?.fetchFn});return{authorizationServerUrl,authorizationServerMetadata,resourceMetadata}}function resourceIndicatorToString(resource){return typeof resource==="string"?resource:resource.href}async function startAuthorization(authorizationServerUrl,{metadata,clientInformation,redirectUrl,scope,state,resource}){let authorizationUrl;if(metadata){if(authorizationUrl=new URL(metadata.authorization_endpoint),!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))throw Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);if(metadata.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))throw Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`)}else authorizationUrl=new URL("/authorize",authorizationServerUrl);let challenge=await pkceChallenge(),{code_verifier:codeVerifier,code_challenge:codeChallenge}=challenge;if(authorizationUrl.searchParams.set("response_type",AUTHORIZATION_CODE_RESPONSE_TYPE),authorizationUrl.searchParams.set("client_id",clientInformation.client_id),authorizationUrl.searchParams.set("code_challenge",codeChallenge),authorizationUrl.searchParams.set("code_challenge_method",AUTHORIZATION_CODE_CHALLENGE_METHOD),authorizationUrl.searchParams.set("redirect_uri",String(redirectUrl)),state)authorizationUrl.searchParams.set("state",state);if(scope)authorizationUrl.searchParams.set("scope",scope);if(scope?.includes("offline_access"))authorizationUrl.searchParams.append("prompt","consent");if(resource)authorizationUrl.searchParams.set("resource",resourceIndicatorToString(resource));return{authorizationUrl,codeVerifier}}function prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,redirectUri){return new URLSearchParams({grant_type:"authorization_code",code:authorizationCode,code_verifier:codeVerifier,redirect_uri:String(redirectUri)})}async function executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn}){let tokenUrl=metadata?.token_endpoint?new URL(metadata.token_endpoint):new URL("/token",authorizationServerUrl),headers=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(resource)tokenRequestParams.set("resource",resourceIndicatorToString(resource));if(addClientAuthentication)await addClientAuthentication(headers,tokenRequestParams,tokenUrl,metadata);else if(clientInformation){let supportedMethods=metadata?.token_endpoint_auth_methods_supported??[],authMethod=selectClientAuthMethod(clientInformation,supportedMethods);applyClientAuthentication(authMethod,clientInformation,headers,tokenRequestParams)}let response=await fetchWithinOrigin(fetchFn??fetch)(tokenUrl,{method:"POST",headers,body:tokenRequestParams});if(!response.ok)throw await parseErrorResponse(response);return TokenResponseSchema.parse(await response.json())}async function refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken,resource,addClientAuthentication,fetchFn}){let tokenRequestParams=new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken}),tokens=await executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn});return{refresh_token:refreshToken,...tokens}}async function fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,fetchFn}={}){let readClientInformation=async()=>{let storedClientInformation=await provider.clientInformation(),checked=discardIfIssuerMismatch(storedClientInformation,String(authorizationServerUrl));if(storedClientInformation&&!checked)throw boundElsewhereError(storedClientInformation,String(authorizationServerUrl));return checked},clientInformation=await readClientInformation(),scope=provider.clientMetadata.scope,tokenRequestParams;if(provider.prepareTokenRequest)tokenRequestParams=await provider.prepareTokenRequest(scope);if(!tokenRequestParams){if(!authorizationCode)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!provider.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let codeVerifier=await provider.codeVerifier();tokenRequestParams=prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,provider.redirectUrl)}return clientInformation??(clientInformation=await readClientInformation()),executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication:provider.addClientAuthentication,resource,fetchFn})}async function registerClient(authorizationServerUrl,{metadata,clientMetadata,scope,fetchFn}){let registrationUrl;if(metadata){if(!metadata.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");registrationUrl=new URL(metadata.registration_endpoint)}else registrationUrl=new URL("/register",authorizationServerUrl);let response=await fetchWithinOrigin(fetchFn??fetch)(registrationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...clientMetadata,...scope!==void 0?{scope}:{}})});if(!response.ok)throw await parseErrorResponse(response);return RegistrationResponseSchema.parse(await response.json())}import{randomBytes}from"node:crypto";import{link as link2,mkdir,open as open2,readFile,rename,rm,stat,utimes}from"node:fs/promises";import{hostname}from"node:os";import{dirname}from"node:path";import{inspect}from"node:util";class AccessFileError extends Error{reason;file;constructor(reason,file,cause){super(describe2(reason,file,cause),cause===void 0?void 0:{cause});this.reason=reason;this.file=file}}function describe2(reason,file,cause){let detail=cause instanceof Error?cause.message:cause===void 0?"":typeof cause==="string"?cause:inspect(cause);switch(reason){case"unreadable":return`Couldn't read the companion's access file ${file}${detail===""?"":` (${detail})`}. It was left as it is: fix its permissions, or remove it and connect again.`;case"unwritable":return`Couldn't save the companion's access in ${file}${detail===""?"":` (${detail})`}.`;case"locked":return`Another companion process kept ${file} locked. If none is running, remove ${lockFor(file)}.`}}var LOCK_STALE_MS=1e4,LOCK_WAIT_MS=15000,LOST_LOCK_ATTEMPTS=5,lockFor=(file)=>`${file}.lock`,errorCode=(error)=>error instanceof Error?Reflect.get(error,"code"):void 0,pause=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms));async function readAccessFile(file,parse){let text;try{text=await readFile(file,"utf8")}catch(error){if(errorCode(error)==="ENOENT")return;throw new AccessFileError("unreadable",file,error)}let json;try{json=JSON.parse(text)}catch(error){throw new AccessFileError("unreadable",file,error)}if(typeof json!=="object"||json===null||Array.isArray(json))throw new AccessFileError("unreadable",file,"it doesn't hold a JSON object");return parse(json)}async function updateAccessFile(file,parse,change){try{await mkdir(dirname(file),{recursive:!0,mode:448})}catch(error){throw new AccessFileError("unwritable",file,error)}for(let attempt=0;attempt<LOST_LOCK_ATTEMPTS;attempt+=1){let lock=await acquire(file);try{let next=change(await readAccessFile(file,parse));if(await commit(file,next,lock))return}finally{await lock.release()}}throw new AccessFileError("locked",file)}async function commit(file,next,lock){if(next===void 0){if(!await lock.isHeld())return!1;return await rm(file,{force:!0}).catch((error)=>{throw new AccessFileError("unwritable",file,error)}),!0}let temporary=`${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;try{let handle=await open2(temporary,"wx",384);try{await handle.chmod(384),await handle.writeFile(JSON.stringify(next)),await handle.sync()}finally{await handle.close()}if(!await lock.isHeld())return!1;return await rename(temporary,file),!0}catch(error){throw error instanceof AccessFileError?error:new AccessFileError("unwritable",file,error)}finally{await rm(temporary,{force:!0}).catch(()=>{return})}}async function acquire(file){let path=lockFor(file),deadline=Date.now()+LOCK_WAIT_MS;for(let attempt=0;;attempt+=1){let handle=await open2(path,"wx",384).catch((error)=>{if(errorCode(error)!=="EEXIST")throw new AccessFileError("unwritable",file,error);return});if(handle===void 0){if(await breakIfStale(path))continue;if(Date.now()>deadline)throw new AccessFileError("locked",file);await pause(Math.min(5*2**attempt,100)*(0.5+Math.random()));continue}try{await handle.writeFile(JSON.stringify({pid:process.pid,host:hostname()}));let{ino}=await handle.stat(),isHeld=async()=>await stat(path).then((current)=>current.ino===ino,()=>!1);return{isHeld,release:async()=>{if(await isHeld())await rm(path,{force:!0})}}}catch(error){throw await rm(path,{force:!0}),new AccessFileError("unwritable",file,error)}finally{await handle.close()}}}var isRunning=(pid)=>{try{return process.kill(pid,0),!0}catch(error){return errorCode(error)==="EPERM"}};async function breakIfStale(path){let judged=await stat(path).catch(()=>{return});if(judged===void 0)return!0;let holder=await readFile(path,"utf8").then((text)=>JSON.parse(text)).catch(()=>{return}),pid=typeof holder==="object"&&holder!==null?Reflect.get(holder,"pid"):void 0,host=typeof holder==="object"&&holder!==null?Reflect.get(holder,"host"):void 0;if(!(typeof pid==="number"&&host===hostname()&&pid!==process.pid&&!isRunning(pid))&&Date.now()-judged.mtimeMs<=LOCK_STALE_MS)return!1;let aside=`${path}.${process.pid}.${randomBytes(6).toString("hex")}.stale`;try{await rename(path,aside)}catch{return!0}let moved=await stat(aside).catch(()=>{return});if(moved!==void 0&&moved.ino!==judged.ino)await link2(aside,path).catch(()=>{return}),await utimes(path,moved.atime,moved.mtime).catch(()=>{return});return await rm(aside,{force:!0}),!0}var fieldsOf=(raw)=>typeof raw==="object"&&raw!==null?new Map(Object.entries(raw)):new Map,parseName=(raw)=>{let fields=fieldsOf(raw),name=fields.get("name"),personal=fields.get("personal");return typeof name==="string"&&name.trim().length>0&&typeof personal==="boolean"?{name:name.trim().slice(0,200),personal}:void 0},parseGrant=(raw)=>{let fields=fieldsOf(raw),tokens=OAuthTokensSchema.safeParse(fields.get("tokens")).data,expiresAt=fields.get("expiresAt"),named=parseName(fields.get("named"));return tokens===void 0?void 0:{tokens,...typeof expiresAt==="number"&&Number.isFinite(expiresAt)?{expiresAt}:{},...named===void 0?{}:{named}}},EMPTY={grants:{}};function parseStored(raw){let fields=new Map(Object.entries(raw)),full=OAuthClientInformationFullSchema.safeParse(fields.get("client")),client=full.success?full.data:OAuthClientInformationSchema.safeParse(fields.get("client")).data,rawGrants=fields.get("grants"),grants={};if(typeof rawGrants==="object"&&rawGrants!==null)for(let[workspace,value]of Object.entries(rawGrants)){let grant=parseGrant(value);if(grant!==void 0)grants[workspace]=grant}let legacy=parseGrant(raw);if(legacy!==void 0)grants[""]??=legacy;let codeVerifier=fields.get("codeVerifier");return{...client===void 0?{}:{client},grants,...typeof codeVerifier==="string"?{codeVerifier}:{}}}function originFrom(value){let url=new URL(value??COMPANION_DEFAULT_ORIGIN);if(url.protocol!=="https:"&&!["127.0.0.1","localhost"].includes(url.hostname))throw Error("DiffClarity must be reached over HTTPS, except on this machine.");return url.origin}var stateFileFor=(origin)=>join(process.env.XDG_CONFIG_HOME??join(homedir(),".config"),"diffclarity",`companion-${createHash("sha256").update(origin).digest("hex").slice(0,16)}.json`),mcpUrl=(origin)=>new URL("/mcp",origin),addWorkspaceCommand=(origin)=>`${companionCommand("connect",origin)} --add-workspace`,workspaceLabel=(workspace)=>workspace.named===void 0?workspace.id===""?"the workspace an earlier version allowed it in":`the workspace ${workspace.id}`:workspace.named.personal?"your personal workspace":`“${workspace.named.name}”`,workspaceTag=(workspace)=>workspace.named===void 0?workspace.id===""?"earlier workspace":workspace.id.slice(0,12):workspace.named.personal?"Personal":workspace.named.name,workspaceList=(workspaces)=>{let labels=workspaces.map(workspaceLabel);return labels.length<=1?labels[0]??"no workspace":`${labels.slice(0,-1).join(", ")} and ${labels.at(-1)??""}`},LOOPBACK_REDIRECT="http://127.0.0.1/callback",EXPIRY_MARGIN_MS=60000;class NeedsSignIn extends Error{}var needsSignIn=(origin)=>new NeedsSignIn(`DiffClarity needs you to allow the companion again in this workspace. Run \`${addWorkspaceCommand(origin)}\` and choose it in the browser.`);class StoredAccess{origin;file;openBrowser;machine;redirect;grantWorkspace;grantNamed;given;readRefresh;issuedState;constructor(origin,file=stateFileFor(origin),openBrowser,machine=hostname2(),workspace){this.origin=origin;this.file=file;this.openBrowser=openBrowser;this.machine=machine;this.grantWorkspace=workspace}get workspace(){return this.grantWorkspace}async rememberName(workspace){let key=this.grantWorkspace;if(key===void 0||key!==""&&key!==workspace.id)return;let named={name:workspace.name,personal:workspace.personal};await this.write((stored)=>{let grant=stored.grants[key];if(grant===void 0||grant.named?.name===named.name&&grant.named.personal===named.personal)return stored;return{...stored,grants:{...stored.grants,[key]:{...grant,named}}}})}fetchNamingWorkspace=async(url,init)=>{let response=await fetch(url,init);if(this.grantWorkspace!==void 0||!response.ok)return response;let fields=fieldsOf(await response.clone().json().catch(()=>null)),workspace=fields.get(GRANT_WORKSPACE_FIELD);if(typeof workspace==="string"&&workspace.length>0)this.grantWorkspace=workspace,this.grantNamed=parseName({name:fields.get(GRANT_WORKSPACE_NAME_FIELD),personal:fields.get(GRANT_WORKSPACE_PERSONAL_FIELD)});return response};async read(){return await readAccessFile(this.file,parseStored)??EMPTY}async grant(){return this.grantWorkspace===void 0?void 0:(await this.read()).grants[this.grantWorkspace]}async write(change){await updateAccessFile(this.file,parseStored,(stored)=>change(stored??EMPTY))}useRedirect(url){this.redirect=url}get redirectUrl(){return this.redirect??LOOPBACK_REDIRECT}get clientMetadata(){return{client_name:companionClientName(this.machine),redirect_uris:[LOOPBACK_REDIRECT],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}state(){return this.issuedState=randomBytes2(16).toString("hex"),this.issuedState}async clientInformation(){return(await this.read()).client}async saveClientInformation(client){await this.write((stored)=>({...stored,client}))}async tokens(){let tokens=(await this.grant())?.tokens;return this.readRefresh=tokens?.refresh_token,tokens}async saveTokens(tokens){let workspace=this.grantWorkspace??"";this.grantWorkspace=workspace;let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1000;await this.write((stored)=>{let named=this.grantNamed??stored.grants[workspace]?.named;return{...stored,grants:{...stored.grants,[workspace]:{tokens,...expiresAt===void 0?{}:{expiresAt},...named===void 0?{}:{named}}}}})}async redirectToAuthorization(url){if((await this.tokens())?.refresh_token!==void 0)throw Error("DiffClarity didn't renew the companion's access. It may be unreachable.");if(this.openBrowser===void 0)throw needsSignIn(this.origin);url.searchParams.set(SEVERAL_WORKSPACES_PARAM,SEVERAL_WORKSPACES_VALUE),this.openBrowser(url)}async saveCodeVerifier(codeVerifier){await this.write((stored)=>({...stored,codeVerifier}))}async codeVerifier(){let{codeVerifier}=await this.read();if(codeVerifier===void 0)throw Error(`The sign-in was started elsewhere. Run \`${companionCommand("connect",this.origin)}\` again.`);return codeVerifier}async invalidateCredentials(scope){if(scope==="discovery")return;let workspace=this.grantWorkspace;if(scope==="tokens"&&workspace===void 0)return;let readRefresh=this.readRefresh;await this.write((stored)=>{let{client,grants,codeVerifier}=stored;if(scope==="tokens"&&readRefresh!==void 0&&grants[workspace??""]?.tokens.refresh_token!==readRefresh)return stored;return{...scope!=="all"&&scope!=="client"&&client!==void 0?{client}:{},grants:scope==="all"?{}:scope==="tokens"?Object.fromEntries(Object.entries(grants).filter(([key])=>key!==workspace)):grants,...scope!=="all"&&scope!=="verifier"&&codeVerifier!==void 0?{codeVerifier}:{}}})}async renew(){if(await auth(this,{serverUrl:mcpUrl(this.origin)})!=="AUTHORIZED")throw needsSignIn(this.origin)}async accessToken(isRefused=!1){let stored=await this.grant(),current=stored?.tokens.access_token,isFresh=stored?.expiresAt===void 0||stored.expiresAt-EXPIRY_MARGIN_MS>Date.now();if(current&&isFresh&&(!isRefused||this.given!==void 0&¤t!==this.given))return this.given=current,current;await this.renew();let renewed=(await this.tokens())?.access_token;if(!renewed)throw Error("DiffClarity didn't issue an access token.");return this.given=renewed,renewed}async forget(){await updateAccessFile(this.file,parseStored,(stored)=>stored?.client===void 0?void 0:{client:stored.client,grants:{}})}}async function savedWorkspaces(file){return Object.entries((await readAccessFile(file,parseStored)??EMPTY).grants).map(([id,grant])=>grant.named===void 0?{id}:{id,named:grant.named})}function openInBrowser(url){let[command,...args]=process.platform==="darwin"?["open",url.href]:process.platform==="win32"?["cmd","/c","start","",url.href]:["xdg-open",url.href];if(command===void 0)return;let child=spawn(command,args,{stdio:"ignore",detached:!0});child.on("error",()=>{return}),child.unref()}var everyWorkspace=(saved)=>({kind:"answer-in",workspaces:saved.map((workspace)=>workspace.id)});async function signIn(origin,state,log,options={}){let machine=options.machine??hostname2(),choose=options.choose??everyWorkspace,justAllowed=new Set,isAdding=options.addWorkspace===!0;for(;;){if(isAdding||(await savedWorkspaces(state)).length===0){for(let workspace of await allowInBrowser(origin,state,log,machine,options))justAllowed.add(workspace);isAdding=!1}let saved=await savedWorkspaces(state),choice=await choose(saved,[...justAllowed]);if(choice.kind==="allow-more"){isAdding=!0;continue}let chosen=saved.filter((workspace)=>choice.workspaces.includes(workspace.id)),kept=[];for(let workspace of chosen){let quiet=new StoredAccess(origin,state,void 0,machine,workspace.id);if(justAllowed.has(workspace.id)){kept.push(quiet);continue}let renewal=await quiet.renew().then(()=>null,(error)=>error instanceof Error?error:Error(String(error)));if(renewal===null){kept.push(quiet);continue}if(renewal instanceof AccessFileError)throw renewal;if(!(renewal instanceof NeedsSignIn)){log(`Couldn't renew the access saved in ${state} for ${workspaceLabel(workspace)} (${renewal.message}) Trying it anyway.`),kept.push(quiet);continue}log(`DiffClarity no longer allows the companion in ${workspaceLabel(workspace)}, so it doesn't answer there. To allow it there again, run \`${addWorkspaceCommand(origin)}\`.`)}if(kept.length>0){let renewed=chosen.filter((workspace)=>!justAllowed.has(workspace.id)&&kept.some((access)=>access.workspace===workspace.id));if(renewed.length>0)log(`Signed in with the access saved in ${state}, for ${renewed.length===1?workspaceLabel(renewed[0]??{id:""}):`${renewed.length} workspaces`}.`);return kept}isAdding=!0}}async function allowInBrowser(origin,state,log,machine,options){let open=options.open??openInBrowser,finish=()=>{return},fail=()=>{return},received=new Promise((resolve,reject)=>{finish=resolve,fail=reject}),access,server=createServer((request,response)=>{let url=new URL(request.url??"/","http://127.0.0.1");if(url.pathname!=="/callback"){response.writeHead(404).end();return}if(access?.issuedState===void 0||url.searchParams.get("state")!==access.issuedState){response.writeHead(400).end();return}let code=url.searchParams.get("code"),error=url.searchParams.get("error"),codes=code?[code,...url.searchParams.getAll(GRANT_MORE_CODES_PARAM).filter((more)=>more.length>0)]:[];if(response.writeHead(200,{"content-type":"text/html; charset=utf-8","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'"}).end(callbackPage(codes.length,origin)),codes.length>0)finish([...new Set(codes)]);else fail(Error(error==="access_denied"?"You didn't allow the companion.":`Sign-in failed${error?`: ${error}`:""}.`))});await new Promise((resolve)=>server.listen(0,"127.0.0.1",resolve));try{let address=server.address();if(address===null||typeof address==="string")throw Error("Couldn't listen for the browser's answer.");let redirect=`http://127.0.0.1:${address.port}/callback`;access=new StoredAccess(origin,state,(url)=>{log(`Allow the companion in your browser, and tick each workspace it should answer in. If it didn't open, visit:
|
|
79
|
+
${url.href}`),options.onBrowser?.(),open(url)},machine),access.useRedirect(redirect);let first=access;if(await auth(first,{serverUrl:mcpUrl(origin),fetchFn:first.fetchNamingWorkspace})==="AUTHORIZED")return[first.workspace??""];let timeout=setTimeout(()=>fail(Error("Nobody allowed the companion within 10 minutes.")),600000),codes=await received.finally(()=>clearTimeout(timeout)),allowed=[],failures=[];for(let[index,code]of codes.entries()){let exchanging=index===0?first:new StoredAccess(origin,state,void 0,machine);exchanging.useRedirect(redirect);try{if(await auth(exchanging,{serverUrl:mcpUrl(origin),authorizationCode:code,fetchFn:exchanging.fetchNamingWorkspace})==="AUTHORIZED"&&exchanging.workspace!==void 0)allowed.push(exchanging.workspace);else failures.push("DiffClarity didn't accept it.")}catch(error){if(error instanceof AccessFileError)throw error;failures.push(error instanceof Error?error.message:String(error))}}if(allowed.length===0)throw Error(`DiffClarity didn't accept the sign-in${failures[0]===void 0?"":`: ${failures[0]}`}`);if(failures.length>0)log(`DiffClarity didn't accept the companion in ${failures.length===1?"one of the workspaces":`${failures.length} of the workspaces`} you ticked (${failures.join("; ")}). Run \`${addWorkspaceCommand(origin)}\` to try again.`);return log(allowed.length===1?"Allowed in the workspace you ticked.":`Allowed in the ${allowed.length} workspaces you ticked.`),allowed}finally{server.close()}}var callbackPage=(allowedIn,origin)=>{let isAllowed=allowedIn>0,[title,text]=isAllowed?["Companion allowed",`${allowedIn>1?`It may answer in the ${allowedIn} workspaces you ticked. `:""}It connects now; you can close this tab.`]:["Companion not allowed","Nothing was connected. Run the companion again to try once more. You can close this tab."];return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title} · DiffClarity</title>
|
|
80
80
|
<style>
|
|
81
81
|
:root { color-scheme: light dark; --fg: #1f2328; --muted: #59636e; --border: #d1d9e0; --canvas: #ffffff; --page: #f6f8fa; --accent: #0969da; --done: #187733; --stop: #cf222e; }
|
|
82
82
|
@media (prefers-color-scheme: dark) { :root { --fg: #f0f6fc; --muted: #9198a1; --border: #3d444d; --canvas: #151b23; --page: #0d1117; --accent: #4493f8; --done: #3fb950; --stop: #f85149; } }
|
|
@@ -97,12 +97,16 @@ a.open:hover { filter: brightness(1.08); }
|
|
|
97
97
|
<p>${text}</p>
|
|
98
98
|
<a class="open" href="${new URL(origin).origin}">Open DiffClarity</a>
|
|
99
99
|
</main>
|
|
100
|
-
</html>`};
|
|
100
|
+
</html>`};var fold=(text)=>text.normalize("NFKC").trim().toLocaleLowerCase("en");function namedWorkspaces(saved,values,addCommand){let found=[];for(let value of values){let wanted=fold(value),byId=saved.filter((workspace)=>workspace.id===value.trim()),matches=byId.length>0?byId:saved.filter((workspace)=>workspace.named!==void 0&&(fold(workspace.named.name)===wanted||workspace.named.personal&&wanted==="personal")),[only,...others]=matches;if(only===void 0)return{kind:"refused",message:`The companion isn't allowed in a workspace named “${value}”${saved.length===0?"":`; it is allowed in ${listWithIds(saved)}`}. Name one of those, or run \`${addCommand}\` to allow it in another.`};if(others.length>0)return{kind:"refused",message:`More than one workspace is named “${value}”: ${listWithIds(matches)}. Name it by its id.`};if(!found.includes(only.id))found.push(only.id)}return{kind:"found",workspaces:found}}var listWithIds=(workspaces)=>workspaces.map((workspace)=>workspace.named===void 0?workspaceLabel(workspace):`${workspaceLabel(workspace)} (${workspace.id})`).join(", ");function workspaceLines(saved,origin,addCommand){if(saved.length===0)return[`The companion isn't allowed in any workspace on ${origin} yet. Run \`${addCommand}\` to allow it.`];return[`The companion is allowed in ${saved.length===1?"one workspace":`${saved.length} workspaces`} on ${origin}:`,...saved.map((workspace)=>` ${workspace.named===void 0?`${workspace.id===""?"(allowed by an earlier version)":workspace.id} name not known yet: it learns it when it connects there`:`${workspace.named.personal?`Personal (${workspace.named.name})`:workspace.named.name} ${workspace.id}`}`),"Choose among them with --workspace <name or id>, once for each."]}var pickerOf=(workspaces,ticked)=>{let known=ticked.filter((id)=>workspaces.some((workspace)=>workspace.id===id));return{workspaces,ticked:known.length>0?known:workspaces.map((workspace)=>workspace.id),cursor:0,notice:""}};function pick2(picker,key){let{workspaces,ticked,cursor}=picker,count=workspaces.length,at=workspaces[cursor],go=(next)=>({kind:"picking",picker:{...picker,notice:"",...next}});switch(key){case"up":return go({cursor:(cursor-1+count)%count});case"down":return go({cursor:(cursor+1)%count});case"toggle":return at===void 0?go({}):go({ticked:ticked.includes(at.id)?ticked.filter((id)=>id!==at.id):[...ticked,at.id]});case"all":return go({ticked:ticked.length===count?[]:workspaces.map((workspace)=>workspace.id)});case"confirm":{let chosen=workspaces.flatMap((workspace)=>ticked.includes(workspace.id)?[workspace.id]:[]);return chosen.length===0?go({notice:"Tick at least one workspace, or press q to stop."}):{kind:"chosen",workspaces:chosen}}case"allow-more":return{kind:"allow-more",ticked};case"cancel":return{kind:"cancelled"}}}function keysOf(chunk){let keys=[];for(let index=0;index<chunk.length;index+=1){let rest=chunk.slice(index);if(rest.startsWith("\x1B[A")||rest.startsWith("\x1BOA")){keys.push("up"),index+=2;continue}if(rest.startsWith("\x1B[B")||rest.startsWith("\x1BOB")){keys.push("down"),index+=2;continue}let sequence=/^\u001b[[O][\d;]*[A-Za-z~]/u.exec(rest);if(sequence!==null){index+=sequence[0].length-1;continue}let character=rest[0];if(character==="k")keys.push("up");else if(character==="j")keys.push("down");else if(character===" "||character==="x")keys.push("toggle");else if(character==="a")keys.push("all");else if(character==="+"||character==="n")keys.push("allow-more");else if(character==="\r"||character===`
|
|
101
|
+
`)keys.push("confirm");else if(character==="q"||character==="\x03"||character==="\x04"||character==="\x1B")keys.push("cancel")}return keys}function pickerLines(picker,isColour){let dim=(text)=>isColour?`\x1B[2m${text}\x1B[22m`:text,bold=(text)=>isColour?`\x1B[1m${text}\x1B[22m`:text;return["Answer in which workspaces this time?",...picker.workspaces.map((workspace,index)=>{let isHere=index===picker.cursor,box=picker.ticked.includes(workspace.id)?"[x]":"[ ]",line=`${isHere?"›":" "} ${box} ${workspaceTag(workspace)}${workspace.named===void 0?dim(" (name not known yet)"):""}`;return isHere?bold(line):line}),dim("↑↓ move · space tick · a all or none · + allow it in more workspaces · enter connect · q stop"),...picker.notice.length===0?[]:[picker.notice]]}function pickInTerminal(input,output,start,isColour){return new Promise((resolve)=>{let picker=start,drawn=0,draw=()=>{let lines=pickerLines(picker,isColour);output.write(`${drawn>0?`\x1B[${drawn}F`:""}\x1B[0J${lines.join(`
|
|
102
|
+
`)}
|
|
103
|
+
`),drawn=lines.length},finish=(step)=>{if(input.off("data",onData),input.setRawMode?.(!1),input.pause(),output.write(`\x1B[${drawn}F\x1B[0J`),step.kind==="chosen"){let chosen=picker.workspaces.filter((workspace)=>step.workspaces.includes(workspace.id));output.write(`Answering in ${workspaceList(chosen)} this time.
|
|
104
|
+
`)}resolve(step)},onData=(chunk)=>{for(let key of keysOf(typeof chunk==="string"?chunk:chunk.toString("utf8"))){let step=pick2(picker,key);if(step.kind!=="picking"){finish(step);return}picker=step.picker}draw()};input.setRawMode?.(!0),input.on("data",onData),input.resume(),draw()})}import{spawn as spawn5}from"node:child_process";import{spawn as spawn2}from"node:child_process";var MODEL_LIST_LIMIT_MS=30000,decodeModels=decodeUnknownSync(ArraySchema(AgentModel)),CLAUDE_EFFORTS=["low","medium","high","xhigh","max"],CLAUDE_MODELS=[["fable","Fable"],["opus","Opus"],["sonnet","Sonnet"],["haiku","Haiku"]];function outputOf(command,args){return new Promise((resolve)=>{let child=spawn2(command,args,{stdio:["ignore","pipe","ignore"]}),output="",timer=setTimeout(()=>child.kill(),MODEL_LIST_LIMIT_MS);child.stdout.setEncoding("utf8").on("data",(chunk)=>{output+=chunk}),child.on("error",()=>{clearTimeout(timer),resolve(null)}),child.on("close",(code)=>{clearTimeout(timer),resolve(code===0?output:null)})})}var CodexCatalog=Struct({models:ArraySchema(Struct({slug:String4,display_name:optional2(String4),visibility:optional2(String4),supported_reasoning_levels:optional2(ArraySchema(Struct({effort:String4})))}))}),parseJson2=(text)=>{try{return JSON.parse(text)}catch{return}};async function modelsOf(kind,command){switch(kind){case"claude":{let models=decodeModels(CLAUDE_MODELS.map(([id,label])=>({id,label,efforts:CLAUDE_EFFORTS})));return{models,efforts:models[0]?.efforts??[]}}case"codex":{let catalog=decodeUnknownOption2(CodexCatalog)(parseJson2(await outputOf(command,["debug","models"])??""));if(catalog._tag==="None")return{models:[],efforts:[]};let listed=catalog.value.models.filter((model)=>model.visibility===void 0||model.visibility==="list"),models=decodeModels(listed.flatMap((model)=>{let decoded=decodeUnknownOption2(AgentModel)({id:model.slug,label:(model.display_name??model.slug).replace(/\s*\[[^\]]*\]$/u,"").slice(0,120),efforts:(model.supported_reasoning_levels??[]).map((level)=>level.effort).slice(0,12)});return decoded._tag==="Some"?[decoded.value]:[]})),shared=models.reduce((common,model)=>common===null?model.efforts:common.filter((effort)=>model.efforts.includes(effort)),null);return{models,efforts:shared??[]}}case"opencode":{let lines=(await outputOf(command,["models"])??"").split(`
|
|
101
105
|
`).map((line)=>line.trim()).filter((line)=>line.includes("/"));return{models:decodeModels(lines.flatMap((id)=>{let decoded=decodeUnknownOption2(AgentModel)({id,label:id,efforts:[]});return decoded._tag==="Some"?[decoded.value]:[]}).slice(0,1000)),efforts:[]}}}}import{spawn as spawn4}from"node:child_process";import{chmod,mkdir as mkdir2}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{join as join2}from"node:path";import{spawn as spawn3}from"node:child_process";import{randomBytes as randomBytes3}from"node:crypto";import{realpath}from"node:fs/promises";var inOwnGroup=process.platform!=="win32",signalGroup=(child,name)=>{try{if(child.pid!==void 0&&inOwnGroup)process.kill(-child.pid,name);else child.kill(name)}catch{}},stopGroup=(child)=>{signalGroup(child,"SIGTERM"),setTimeout(()=>{if(child.exitCode===null&&child.signalCode===null)signalGroup(child,"SIGKILL")},5000).unref()};var LISTEN_LIMIT_MS=20000,CONNECT_LIMIT_MS=30000,POLL_MS=250,opencodeConfig=(mcp)=>({$schema:"https://opencode.ai/config.json",mcp:{servers:{diffclarity:{type:"local",command:[mcp.command,...mcp.args],environment:mcp.env,codemode:!1}}},permissions:[{action:"*",resource:"*",effect:"deny"},{action:"diffclarity_*",resource:"*",effect:"allow"}],policies:[{action:"integration.use",resource:"mcp:*",effect:"deny"},{action:"integration.use",resource:"mcp:diffclarity",effect:"allow"},{action:"integration.use",resource:"skill:*",effect:"deny"}]}),serverEnvironment=(password)=>({OPENCODE_SERVER_PASSWORD:password}),delay2=(ms,signal)=>new Promise((resolve)=>{let timer=setTimeout(resolve,ms);signal.addEventListener("abort",()=>{clearTimeout(timer),resolve()},{once:!0})}),McpServers=Struct({data:ArraySchema(Struct({name:String4,status:Struct({status:String4,error:optional2(String4)})}))});async function diffclarityStatus(url,password,directory,signal){let response=await fetch(`${url}/api/mcp?${new URLSearchParams({"location[directory]":directory})}`,{headers:{authorization:`Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`},signal});if(!response.ok)return`HTTP ${response.status}`;let servers=decodeUnknownOption2(McpServers)(await response.json()),status=servers._tag==="Some"?servers.value.data.find((server)=>server.name==="diffclarity")?.status:void 0;if(status===void 0)return"pending";return status.error===void 0?status.status:`${status.status}: ${status.error}`}async function startOpencodeServer(command,directory,mcp,environment,signal){let password=randomBytes3(24).toString("base64url"),env=serverEnvironment(password),server=spawn3(command,["serve","--hostname","127.0.0.1","--port","0"],{cwd:directory,env:{...environment,...env,OPENCODE_CONFIG_CONTENT:JSON.stringify(opencodeConfig(mcp))},stdio:["ignore","pipe","pipe"],detached:inOwnGroup}),stop=()=>stopGroup(server);try{let output="",url=await new Promise((resolve,reject)=>{let timer=setTimeout(()=>reject(Error("opencode's server didn't start in time.")),LISTEN_LIMIT_MS),onOutput=(chunk)=>{output=(output+chunk).slice(-4000);let listening=/listening on (http:\/\/127\.0\.0\.1:\d+)/u.exec(output);if(listening?.[1])clearTimeout(timer),resolve(listening[1])};server.stdout.setEncoding("utf8").on("data",onOutput),server.stderr.setEncoding("utf8").on("data",onOutput),server.on("error",(error)=>{clearTimeout(timer),reject(error)}),server.on("exit",()=>{clearTimeout(timer),reject(Error(`opencode's server stopped. ${output.trim().split(`
|
|
102
106
|
`).slice(-2).join(" ").slice(0,400)}`))}),signal.addEventListener("abort",()=>{clearTimeout(timer),reject(Error("Stopped."))},{once:!0})}),location=await realpath(directory),until=Date.now()+CONNECT_LIMIT_MS,status="pending";while(!signal.aborted&&Date.now()<until){if(status=await diffclarityStatus(url,password,location,signal).catch((error)=>error instanceof Error?error.message:String(error)),status==="connected")return{url,env,stop};if(status.startsWith("failed")||status.startsWith("needs_auth"))break;await delay2(POLL_MS,signal)}throw Error(signal.aborted?"Stopped.":`opencode couldn't start DiffClarity's tools (${status}).`)}catch(error){throw stop(),error}}var RUN_LIMIT_MS=600000,agentEnvironment=(directory)=>({...Object.fromEntries(Object.entries(process.env).flatMap(([key,value])=>value===void 0||key.startsWith("DIFFCLARITY_")?[]:[[key,value]])),PWD:directory}),agentDirectory=async()=>{let directory=join2(process.env.XDG_CACHE_HOME??join2(homedir2(),".cache"),"diffclarity","agent");return await mkdir2(directory,{recursive:!0,mode:448}),await chmod(directory,448),directory};async function runAgent(work,mcp,emit,signal){let label=agentLabel(work.agent),opencode;try{let directory=await agentDirectory(),environment=agentEnvironment(directory);opencode=work.agent==="opencode"?await startOpencodeServer(COMMANDS.opencode,directory,mcp,environment,signal):void 0;let{cmd,env,stdin}=agentCommand(work,directory,mcp,opencode),[command,...args]=cmd;if(command===void 0)throw Error("No agent command");if(signal.aborted)return;let agent=spawn4(command,args,{cwd:directory,env:{...environment,...env},stdio:["pipe","pipe","pipe"],detached:inOwnGroup}),hasExited=!1,stop=()=>{if(!hasExited)stopGroup(agent)};agent.stdin.on("error",()=>{return}),agent.stdin.end(stdin);let parse=eventParser(work.agent),isFailed=!1,isAnswered=!1,take=(line)=>{for(let event of parse(line))isFailed||=event.kind==="failed",isAnswered||=event.kind==="answer"||event.kind==="text",emit(event)};signal.addEventListener("abort",stop,{once:!0});let limit=setTimeout(stop,RUN_LIMIT_MS),stderr="";agent.stderr.setEncoding("utf8").on("data",(chunk)=>{stderr=(stderr+chunk).slice(-8000)});let buffered="";agent.stdout.setEncoding("utf8").on("data",(chunk)=>{buffered+=chunk;let lines=buffered.split(`
|
|
103
107
|
`);buffered=lines.pop()??"",lines.forEach(take)});let code=await new Promise((resolve)=>{agent.on("error",(error)=>{stderr+=error.message,resolve(null)}),agent.on("close",resolve)});if(hasExited=!0,take(buffered),signalGroup(agent,"SIGTERM"),clearTimeout(limit),signal.removeEventListener("abort",stop),signal.aborted)return;if(code!==0&&!isFailed){let detail=stderr.split(`
|
|
104
|
-
`).filter((line)=>line.trim().length>0&&!line.startsWith("WARNING")).slice(-3).join(" ").slice(0,600);emit({kind:"failed",message:`${label} ${code===null?"couldn't be started":`exited with code ${code}`}.${detail?` ${detail}`:""}`})}else if(!isAnswered&&!isFailed)emit({kind:"failed",message:`${label} finished without an answer.`})}catch(error){if(signal.aborted)return;emit({kind:"failed",message:error instanceof Error&&error.message.length>0?error.message:`${label} couldn't be started.`})}finally{opencode?.stop()}}var version2="0.
|
|
105
|
-
`).find((candidate)=>candidate.trim().length>0&&!candidate.startsWith("WARNING"))?.trim()??"";resolve(code===0?/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/u.exec(line)?.[0]??(line.slice(0,80)||"unknown version"):null)})})}var isSupported=(kind,version)=>kind!=="opencode"||Number(version.split(".")[0])>=2;async function detectAgents(){return(await Promise.all(AGENT_KINDS.map(async(kind)=>{let version=await versionOf(COMMANDS[kind]);return version===null||!isSupported(kind,version)?[]:[{kind,version,...await modelsOf(kind,COMMANDS[kind])}]}))).flat()}async function answer(reporter,work,agents,mcp,log,stopped){let agent=agents.find((candidate)=>candidate.kind===work.agent);if(agent===void 0||!isOffered(agent,work.model,work.effort)){log(`Refused a question for a model or effort ${agentLabel(work.agent)} doesn't offer here.`),reporter.report([{kind:"failed",message:`${agentLabel(work.agent)} on this machine doesn't offer that model or effort.`}],!0);return}let stop=new AbortController,onStopped=()=>{if(!stop.signal.aborted)log("Stopped: the reviewer closed the question.");stop.abort()};if(stopped?.aborted)return;stopped?.addEventListener("abort",onStopped,{once:!0});let pending=[],lastReport=Date.now(),flush=(isDone)=>{let events=pending;pending=[],lastReport=Date.now(),reporter.report(events,isDone)};flush(!1);let timer=setInterval(()=>{if(pending.length>0||Date.now()-lastReport>=HEARTBEAT_MS)flush(!1)},REPORT_EVERY_MS);log(`${agentLabel(work.agent)} is answering a question about ${work.snapshotId.slice(0,18)}…`);try{await runAgent(work,mcp,(event)=>{pending.push(event)},stop.signal)}finally{clearInterval(timer),stopped?.removeEventListener("abort",onStopped)}if(!stop.signal.aborted)flush(!0);log(`${agentLabel(work.agent)} finished.`)}var decodeFrame=decodeUnknownOption2(fromJsonString2(HubFrame)),encodeFrame=encodeSync(fromJsonString2(CompanionFrame)),decodeError=decodeUnknownOption2(Struct({error:Struct({message:String4})})),TIMING={openMs:20000,welcomeMs:15000,probeMs:1e4,retryMs:RETRY_MS,maxRetryMs:60000},OPEN=1,CLOSED=3,webTransport={open:(url,headers,events)=>{let socket=Reflect.construct(WebSocket,[url,{headers}]),isOpened=!1;return socket.addEventListener("open",()=>{isOpened=!0,events.onOpen()}),socket.addEventListener("message",(event)=>events.onMessage(event.data)),socket.addEventListener("error",(event)=>{let message=Reflect.get(event,"message");if(events.onError(typeof message==="string"?message:""),socket.readyState===CLOSED||!isOpened)events.onClose(1006,"")}),socket.addEventListener("close",(event)=>events.onClose(event.code,event.reason)),{send:(text)=>socket.send(text),close:(code,reason)=>socket.close(code,reason),isOpen:()=>socket.readyState===OPEN}},probe:(url,headers,signal)=>fetch(url,{headers,signal,redirect:"manual"})},duration2=(ms)=>ms>=1000?`${Math.round(ms/100)/10} s`:`${ms} ms`,closeDetail=(code,reason)=>`code ${code}${reason.length>0?`: ${reason}`:""}`,workspaceLabel=(workspace)=>workspace.personal?"your personal workspace":`the workspace “${workspace.name}”`;async function readRefusal(transport,url,token,ms,signal,socketError){let plain=new URL(url);plain.protocol=plain.protocol==="wss:"?"https:":"http:";try{let response=await transport.probe(plain,{authorization:`Bearer ${token}`},AbortSignal.any([signal,AbortSignal.timeout(ms)])),text=await response.text().catch(()=>""),parsed=(()=>{try{return decodeError(JSON.parse(text))}catch{return decodeError(void 0)}})(),message=parsed._tag==="Some"?parsed.value.error.message:response.statusText,status=response.status,said=message.length>0?`: ${message}`:"";if(status>=300&&status<400)return{status,line:`DiffClarity redirected the connection (HTTP ${status} to ${response.headers.get("location")??"another page"}). Something in front of DiffClarity, such as a sign-in page, is catching the companion's requests.`};if(status===400)return{status,line:`DiffClarity accepted the companion's access but didn't open the WebSocket${socketError.length>0?` (${socketError})`:""}.`};return{status,line:`DiffClarity refused the connection (HTTP ${status}${said}).`}}catch(error){let reason=error instanceof Error?error.message:String(error);return{status:null,line:`Couldn't reach DiffClarity: ${socketError.length>0?socketError:reason}.`}}}async function serve(access,agents,mcp,log,signal,options={}){let transport=options.transport??webTransport,timing=options.timing??TIMING,onActivity=options.onActivity??(()=>{return}),answering=new Map,waiting=[],current=null,isWelcome=!1,send=(text)=>{if(current!==null&&isWelcome&¤t.isOpen())current.send(text);else waiting.push(text)},reporterFor=(runId)=>({report:(events,isDone)=>send(encodeFrame({kind:"report",runId,report:{events:[...events],isDone}}))}),agentNames=agents.map((agent)=>agentLabel(agent.kind)).join(", "),url=new URL(COMPANION_SOCKET_PATH,access.origin);url.protocol=url.protocol==="https:"?"wss:":"ws:";let take=(work)=>{if(answering.has(work.runId))return;let stop=new AbortController,onShutdown=()=>stop.abort();signal.addEventListener("abort",onShutdown,{once:!0}),onActivity({kind:"answering",runId:work.runId,agent:work.agent});let done=answer(reporterFor(work.runId),work,agents,mcp,log,stop.signal).catch((error)=>log(`The agent failed: ${error instanceof Error?error.message:String(error)}`)).finally(()=>{answering.delete(work.runId),signal.removeEventListener("abort",onShutdown),onActivity({kind:"answered",runId:work.runId})});answering.set(work.runId,{stop,done})},stopAnswering=async()=>{for(let entry of answering.values())entry.stop.abort();await Promise.allSettled([...answering.values()].map((entry)=>entry.done))},welcomes=0,connectOnce=(token)=>new Promise((resolve)=>{let phase="opening",socketError="",isEnded=!1,hasWarned=!1,timer,ping,link=null,end=(ending)=>{if(isEnded)return;if(isEnded=!0,clearTimeout(timer),clearInterval(ping),signal.removeEventListener("abort",onAbort),current===link)current=null,isWelcome=!1;resolve(ending)},giveUp=(ending)=>{end(ending);try{link?.close(1000,ending.kind==="stopped"?"The companion stopped.":"The companion gave up waiting.")}catch{}},onAbort=()=>giveUp({kind:"stopped"});signal.addEventListener("abort",onAbort,{once:!0}),timer=setTimeout(()=>giveUp({kind:"no-answer"}),timing.openMs);try{link=openLink()}catch(error){end({kind:"not-opened",message:error instanceof Error?error.message:String(error)})}function openLink(){return transport.open(url,{authorization:`Bearer ${token}`},{onOpen:()=>{if(isEnded||link===null)return;phase="greeting",log("Connection open. Waiting for DiffClarity to confirm it…"),clearTimeout(timer),timer=setTimeout(()=>giveUp({kind:"not-welcomed"}),timing.welcomeMs),ping=setInterval(()=>{if(link?.isOpen())link.send(LIVE_PING)},PING_MS),link.send(encodeFrame({kind:"hello",hello:{version:COMPANION_VERSION,agents}}))},onMessage:(data)=>{if(isEnded||link===null||data===LIVE_PONG)return;let frame=typeof data==="string"?decodeFrame(data):decodeFrame(void 0);if(frame._tag==="None"){if(!hasWarned)log("DiffClarity sent a message this companion doesn't understand. Update the companion.");hasWarned=!0;return}switch(frame.value.kind){case"welcome":{if(phase==="welcomed")return;clearTimeout(timer),phase="welcomed",current=link,isWelcome=!0;for(let text of waiting.splice(0))link.send(text);let workspace=frame.value.workspace,where=workspace!==void 0?` for ${workspaceLabel(workspace)}`:"";welcomes+=1,onActivity({kind:"connected"}),log(welcomes===1?`Connected to ${access.origin}${where} with ${agentNames}. It answers questions asked in reviews of that workspace only. Ask in a review's Assistant panel; keep this running, and press Ctrl+C to stop.`:`Connected again to ${access.origin}${where}.`);return}case"work":take(frame.value.run);return;case"cancel":answering.get(frame.value.runId)?.stop.abort();return}},onError:(message)=>{socketError=message},onClose:(code,reason)=>end(phase==="opening"?{kind:"not-opened",message:socketError.length>0?socketError:closeDetail(code,reason)}:{kind:"closed",wasWelcomed:phase==="welcomed",code,reason})})}}),failures=0,isRefused=!1;log(`Connecting to ${access.origin}…`);while(!signal.aborted){onActivity({kind:"connecting"});let token=null,tokenFailure="";try{token=await access.accessToken(isRefused)}catch(error){if(error instanceof NeedsSignIn)throw await stopAnswering(),error;tokenFailure=error instanceof Error?error.message:String(error)}let ending=token===null?{kind:"no-access",message:tokenFailure}:await connectOnce(token);if(ending.kind==="stopped"||signal.aborted)break;isRefused=!1;let failed=(line)=>{log(line),onActivity({kind:"failing",reason:line})};switch(ending.kind){case"no-access":failed(`Couldn't renew the companion's access: ${ending.message}`);break;case"no-answer":failed(`DiffClarity didn't answer the connection within ${duration2(timing.openMs)}.`);break;case"not-welcomed":failed(`DiffClarity opened the connection but didn't confirm it within ${duration2(timing.welcomeMs)}.`);break;case"closed":if(ending.wasWelcomed)log(`Lost the connection to DiffClarity (${closeDetail(ending.code,ending.reason)}).`),onActivity({kind:"lost"});else failed(`DiffClarity closed the connection before confirming it (${closeDetail(ending.code,ending.reason)}).`);break;case"not-opened":{if(token!==null){let refusal=await readRefusal(transport,url,token,timing.probeMs,signal,ending.message);if(signal.aborted)break;if(failed(refusal.line),isRefused=refusal.status===401,refusal.status===403)throw await stopAnswering(),Error(`DiffClarity refuses this companion's access in this workspace. Run \`${addWorkspaceCommand(access.origin)}\` and allow it there again.`)}break}}if(signal.aborted)break;failures=ending.kind==="closed"&&ending.wasWelcomed?0:failures+1;let pause=Math.min(timing.retryMs*2**Math.max(0,failures-1),timing.maxRetryMs);log(`Trying again in ${duration2(pause)}…`),await new Promise((resolve)=>{let onAbort=()=>{clearTimeout(timer),resolve()},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},pause);signal.addEventListener("abort",onAbort,{once:!0})})}await Promise.allSettled([...answering.values()].map((entry)=>entry.done))}function isZ4Schema(s){return!!s._zod}function safeParse3(schema,data){if(isZ4Schema(schema))return safeParse(schema,data);return schema.safeParse(data)}function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema))rawShape=schema._zod?.def?.shape;else rawShape=schema.shape;if(!rawShape)return;if(typeof rawShape==="function")try{return rawShape()}catch{return}return rawShape}function getLiteralValue(schema){if(isZ4Schema(schema)){let def=schema._zod?.def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue;return}function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!=="string")throw Error("Schema method literal must be a string");return value}function parseWithCompat(schema,data){let result=safeParse3(schema,data);if(!result.success)throw result.error;return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=60000;class Protocol{constructor(_options){if(this._options=_options,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,(notification)=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,(notification)=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,(_request)=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore)this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=async()=>{let taskId=request.params.taskId;if(!await this._taskStore.getTask(taskId,extra.sessionId))throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(this._taskMessageQueue){let queuedMessage;while(queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId)){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage=message,error=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal,extra.sessionId),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId,extra.sessionId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error instanceof Error?error.message:String(error)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId,extra.sessionId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error){if(error instanceof McpError)throw error;throw new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error instanceof Error?error.message:String(error)}`)}})}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(info)clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId)}async connect(transport){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=(error)=>{_onerror?.(error),this._onerror(error)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{if(_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))this._onresponse(message);else if(isJSONRPCRequest(message))this._onrequest(message,extra);else if(isJSONRPCNotification(message))this._onnotification(message);else this._onerror(Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error)}_onerror(error){this.onerror?.(error)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;if(handler===void 0)return;Promise.resolve().then(()=>handler(notification)).catch((error)=>this._onerror(Error(`Uncaught error in notification handler: ${error}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId,sessionId=capturedTransport?.sessionId,store=this._taskStore,relatedTaskFound=!0,relatedTaskLookup;if(relatedTaskId&&store&&this._taskMessageQueue&&sessionId!==void 0)relatedTaskFound=!1,relatedTaskLookup=(async()=>{if(!await store.getTask(relatedTaskId,sessionId))throw new McpError(ErrorCode.InvalidParams,`Task not found: ${relatedTaskId}`);relatedTaskFound=!0})();if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};if(relatedTaskId&&relatedTaskLookup){let queuedError={type:"error",message:errorResponse,timestamp:Date.now()};relatedTaskLookup.then(()=>this._enqueueTaskMessage(relatedTaskId,queuedError,sessionId),()=>capturedTransport?.send(errorResponse)).catch((error)=>this._onerror(Error(`Failed to send an error response: ${error}`)))}else if(relatedTaskId&&this._taskMessageQueue)this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch((error)=>this._onerror(Error(`Failed to enqueue error response: ${error}`)));else capturedTransport?.send(errorResponse).catch((error)=>this._onerror(Error(`Failed to send an error response: ${error}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:async(notification)=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};if(relatedTaskId)notificationOptions.relatedTask={taskId:relatedTaskId};await this.notification(notification,notificationOptions)},sendRequest:async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};if(relatedTaskId&&!requestOptions.relatedTask)requestOptions.relatedTask={taskId:relatedTaskId};let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;if(effectiveTaskId&&taskStore)await taskStore.updateTaskStatus(effectiveTaskId,"input_required");return await this.request(r,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};(relatedTaskLookup??Promise.resolve()).then(()=>{if(relatedTaskLookup&&abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");if(taskCreationParams)this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async(result)=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};if(relatedTaskId&&this._taskMessageQueue)await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId);else await capturedTransport?.send(response)},async(error)=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error.code)?error.code:ErrorCode.InternalError,message:error.message??"Internal error",...error.data!==void 0&&{data:error.data}}};if(relatedTaskId&&this._taskMessageQueue&&relatedTaskFound)await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId);else await capturedTransport?.send(errorResponse)}).catch((error)=>this._onerror(Error(`Failed to send response: ${error}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(request.id)===abortController)this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error=new McpError(response.error.code,response.error.message,response.error.data);resolver(error)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result==="object"){let result=response.result;if(result.task&&typeof result.task==="object"){let task=result.task;if(typeof task.taskId==="string")isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId)}}if(!isTaskResponse)this._progressHandlers.delete(messageId);if(isJSONRPCResultResponse(response))handler(response);else{let error=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");while(!0){let task=await this.getTask({taskId},options);if(yield{type:"taskStatus",task},isTerminal(task.status)){if(task.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};else if(task.status==="failed")yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)};else if(task.status==="cancelled")yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)};return}if(task.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((resolve)=>setTimeout(resolve,pollInterval)),options?.signal?.throwIfAborted()}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve,reject)=>{let earlyReject=(error)=>{reject(error)};if(!this._transport){earlyReject(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(request.method),task)this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};if(options?.onprogress)this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}};if(task)jsonrpcRequest.params={...jsonrpcRequest.params,task};if(relatedTask)jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}};let cancel=(reason)=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch((error)=>this._onerror(Error(`Failed to send cancellation: ${error}`)));let error=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error)};this._responseHandlers.set(messageId,(response)=>{if(options?.signal?.aborted)return;if(response instanceof Error)return reject(response);try{let parseResult=safeParse3(resultSchema,response.result);if(!parseResult.success)reject(parseResult.error);else resolve(parseResult.data)}catch(error){reject(error)}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=(response)=>{let handler=this._responseHandlers.get(messageId);if(handler)handler(response);else this._onerror(Error(`Response handler missing for side-channeled request ${messageId}`))};this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch((error)=>{this._cleanupTimeout(messageId),reject(error)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch((error)=>{this._cleanupTimeout(messageId),reject(error)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask)jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};this._transport?.send(jsonrpcNotification,options).catch((error)=>this._onerror(error))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask)jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,(notification)=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);if(progressToken!==void 0)this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId)}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId??this._transport?.sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);if(resolver)resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId);else this._onerror(Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal,sessionId){let interval=this._options?.defaultTaskPollInterval??1000;try{let task=await this._taskStore?.getTask(taskId,sessionId);if(task?.pollInterval)interval=task.pollInterval}catch{}return new Promise((resolve,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw Error("No task store configured");return{createTask:async(taskParams)=>{if(!request)throw Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},getTask:async(taskId)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},storeTaskResult:async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});if(await this.notification(notification),isTerminal(task.status))this._cleanupTaskProgressHandler(taskId)}},getTaskResult:(taskId)=>taskStore.getTaskResult(taskId,sessionId),updateTaskStatus:async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});if(await this.notification(notification),isTerminal(updatedTask.status))this._cleanupTaskProgressHandler(taskId)}},listTasks:(cursor)=>taskStore.listTasks(cursor,sessionId)}}}function isPlainObject2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];if(isPlainObject2(baseValue)&&isPlainObject2(addValue))result[k]={...baseValue,...addValue};else result[k]=addValue}return result}var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return import_ajv_formats.default(ajv),ajv}class AjvJsonSchemaValidator{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id==="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return(input)=>{if(ajvValidator(input))return{valid:!0,data:input,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}}}class ExperimentalClientTasks{constructor(_client){this._client=_client}async*callToolStream(params,resultSchema=CallToolResultSchema,options){let clientInternal=this._client,optionsWithTask={...options,task:options?.task??(clientInternal.isToolTask(params.name)?{}:void 0)},stream=clientInternal.requestStream({method:"tools/call",params},resultSchema,optionsWithTask),validator=clientInternal.getToolOutputValidator(params.name);for await(let message of stream){if(message.type==="result"&&validator){let result=message.result;if(!result.structuredContent&&!result.isError){yield{type:"error",error:new McpError(ErrorCode.InvalidRequest,`Tool ${params.name} has an output schema but did not return structured content`)};return}if(result.structuredContent)try{let validationResult=validator(result.structuredContent);if(!validationResult.valid){yield{type:"error",error:new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)};return}}catch(error){if(error instanceof McpError){yield{type:"error",error};return}yield{type:"error",error:new McpError(ErrorCode.InvalidParams,`Failed to validate structured content: ${error instanceof Error?error.message:String(error)}`)};return}}yield message}}async getTask(taskId,options){return this._client.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._client.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._client.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._client.cancelTask({taskId},options)}requestStream(request,resultSchema,options){return this._client.requestStream(request,resultSchema,options)}}function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}function applyElicitationDefaults(schema,data){if(!schema||data===null||typeof data!=="object")return;if(schema.type==="object"&&schema.properties&&typeof schema.properties==="object"){let obj=data,props=schema.properties;for(let key of Object.keys(props)){let propSchema=props[key];if(obj[key]===void 0&&Object.prototype.hasOwnProperty.call(propSchema,"default"))obj[key]=propSchema.default;if(obj[key]!==void 0)applyElicitationDefaults(propSchema,obj[key])}}if(Array.isArray(schema.anyOf)){for(let sub of schema.anyOf)if(typeof sub!=="boolean")applyElicitationDefaults(sub,data)}if(Array.isArray(schema.oneOf)){for(let sub of schema.oneOf)if(typeof sub!=="boolean")applyElicitationDefaults(sub,data)}}function getSupportedElicitationModes(capabilities){if(!capabilities)return{supportsFormMode:!1,supportsUrlMode:!1};let hasFormCapability=capabilities.form!==void 0,hasUrlCapability=capabilities.url!==void 0;return{supportsFormMode:hasFormCapability||!hasFormCapability&&!hasUrlCapability,supportsUrlMode:hasUrlCapability}}class Client extends Protocol{constructor(_clientInfo,options){super(options);if(this._clientInfo=_clientInfo,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=options?.capabilities??{},this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,options?.listChanged)this._pendingListChangedConfig=options.listChanged}_setupListChangedHandlers(config){if(config.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",ToolListChangedNotificationSchema,config.tools,async()=>(await this.listTools()).tools);if(config.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",PromptListChangedNotificationSchema,config.prompts,async()=>(await this.listPrompts()).prompts);if(config.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",ResourceListChangedNotificationSchema,config.resources,async()=>(await this.listResources()).resources)}get experimental(){if(!this._experimental)this._experimental={tasks:new ExperimentalClientTasks(this)};return this._experimental}registerCapabilities(capabilities){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw Error("Schema is missing a method literal");let methodValue=getLiteralValue(methodSchema);if(typeof methodValue!=="string")throw Error("Schema method literal must be a string");let method=methodValue;if(method==="elicitation/create"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse3(ElicitRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid elicitation request: ${errorMessage}`)}let{params}=validatedRequest.data;params.mode=params.mode??"form";let{supportsFormMode,supportsUrlMode}=getSupportedElicitationModes(this._capabilities.elicitation);if(params.mode==="form"&&!supportsFormMode)throw new McpError(ErrorCode.InvalidParams,"Client does not support form-mode elicitation requests");if(params.mode==="url"&&!supportsUrlMode)throw new McpError(ErrorCode.InvalidParams,"Client does not support URL-mode elicitation requests");let result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let validationResult=safeParse3(ElicitResultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid elicitation result: ${errorMessage}`)}let validatedResult=validationResult.data,requestedSchema=params.mode==="form"?params.requestedSchema:void 0;if(params.mode==="form"&&validatedResult.action==="accept"&&validatedResult.content&&requestedSchema){if(this._capabilities.elicitation?.form?.applyDefaults)try{applyElicitationDefaults(requestedSchema,validatedResult.content)}catch{}}return validatedResult};return super.setRequestHandler(requestSchema,wrappedHandler)}if(method==="sampling/createMessage"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse3(CreateMessageRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid sampling request: ${errorMessage}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let resultSchema=params.tools||params.toolChoice?CreateMessageResultWithToolsSchema:CreateMessageResultSchema,validationResult=safeParse3(resultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid sampling result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapability(capability,method){if(!this._serverCapabilities?.[capability])throw Error(`Server does not support ${capability} (required for ${method})`)}async connect(transport,options){if(await super.connect(transport),transport.sessionId!==void 0)return;try{let result=await this.request({method:"initialize",params:{protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:this._capabilities,clientInfo:this._clientInfo}},InitializeResultSchema,options);if(result===void 0)throw Error(`Server sent invalid initialize result: ${result}`);if(!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))throw Error(`Server's protocol version is not supported: ${result.protocolVersion}`);if(this._serverCapabilities=result.capabilities,this._serverVersion=result.serverInfo,transport.setProtocolVersion)transport.setProtocolVersion(result.protocolVersion);if(this._instructions=result.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(error){throw this.close(),error}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(method){switch(method){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${method})`);if(method==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${method})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${method})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${method})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(!this._capabilities)return;switch(method){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${method})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${method})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${method})`);break;case"ping":break}}assertTaskCapability(method){assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests,method,"Server")}assertTaskHandlerCapability(method){if(!this._capabilities)return;assertClientRequestTaskCapability(this._capabilities.tasks?.requests,method,"Client")}async ping(options){return this.request({method:"ping"},EmptyResultSchema,options)}async complete(params,options){return this.request({method:"completion/complete",params},CompleteResultSchema,options)}async setLoggingLevel(level,options){return this.request({method:"logging/setLevel",params:{level}},EmptyResultSchema,options)}async getPrompt(params,options){return this.request({method:"prompts/get",params},GetPromptResultSchema,options)}async listPrompts(params,options){return this.request({method:"prompts/list",params},ListPromptsResultSchema,options)}async listResources(params,options){return this.request({method:"resources/list",params},ListResourcesResultSchema,options)}async listResourceTemplates(params,options){return this.request({method:"resources/templates/list",params},ListResourceTemplatesResultSchema,options)}async readResource(params,options){return this.request({method:"resources/read",params},ReadResourceResultSchema,options)}async subscribeResource(params,options){return this.request({method:"resources/subscribe",params},EmptyResultSchema,options)}async unsubscribeResource(params,options){return this.request({method:"resources/unsubscribe",params},EmptyResultSchema,options)}async callTool(params,resultSchema=CallToolResultSchema,options){if(this.isToolTaskRequired(params.name))throw new McpError(ErrorCode.InvalidRequest,`Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let result=await this.request({method:"tools/call",params},resultSchema,options),validator=this.getToolOutputValidator(params.name);if(validator){if(!result.structuredContent&&!result.isError)throw new McpError(ErrorCode.InvalidRequest,`Tool ${params.name} has an output schema but did not return structured content`);if(result.structuredContent)try{let validationResult=validator(result.structuredContent);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)}catch(error){if(error instanceof McpError)throw error;throw new McpError(ErrorCode.InvalidParams,`Failed to validate structured content: ${error instanceof Error?error.message:String(error)}`)}}return result}isToolTask(toolName){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has(toolName)}isToolTaskRequired(toolName){return this._cachedRequiredTaskTools.has(toolName)}cacheToolMetadata(tools){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let tool of tools){if(tool.outputSchema){let toolValidator=this._jsonSchemaValidator.getValidator(tool.outputSchema);this._cachedToolOutputValidators.set(tool.name,toolValidator)}let taskSupport=tool.execution?.taskSupport;if(taskSupport==="required"||taskSupport==="optional")this._cachedKnownTaskTools.add(tool.name);if(taskSupport==="required")this._cachedRequiredTaskTools.add(tool.name)}}getToolOutputValidator(toolName){return this._cachedToolOutputValidators.get(toolName)}async listTools(params,options){let result=await this.request({method:"tools/list",params},ListToolsResultSchema,options);return this.cacheToolMetadata(result.tools),result}_setupListChangedHandler(listType,notificationSchema,options,fetcher){let parseResult=ListChangedOptionsBaseSchema.safeParse(options);if(!parseResult.success)throw Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);if(typeof options.onChanged!=="function")throw Error(`Invalid ${listType} listChanged options: onChanged must be a function`);let{autoRefresh,debounceMs}=parseResult.data,{onChanged}=options,refresh=async()=>{if(!autoRefresh){onChanged(null,null);return}try{let items=await fetcher();onChanged(null,items)}catch(e){let error=e instanceof Error?e:Error(String(e));onChanged(error,null)}},handler=()=>{if(debounceMs){let existingTimer=this._listChangedDebounceTimers.get(listType);if(existingTimer)clearTimeout(existingTimer);let timer=setTimeout(refresh,debounceMs);this._listChangedDebounceTimers.set(listType,timer)}else refresh()};this.setNotificationHandler(notificationSchema,handler)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}/*!
|
|
108
|
+
`).filter((line)=>line.trim().length>0&&!line.startsWith("WARNING")).slice(-3).join(" ").slice(0,600);emit({kind:"failed",message:`${label} ${code===null?"couldn't be started":`exited with code ${code}`}.${detail?` ${detail}`:""}`})}else if(!isAnswered&&!isFailed)emit({kind:"failed",message:`${label} finished without an answer.`})}catch(error){if(signal.aborted)return;emit({kind:"failed",message:error instanceof Error&&error.message.length>0?error.message:`${label} couldn't be started.`})}finally{opencode?.stop()}}var version2="0.4.0";var COMPANION_VERSION=version2;var REPORT_EVERY_MS=400,HEARTBEAT_MS=1e4,RETRY_MS=3000,PING_MS=20000;function versionOf(command){return new Promise((resolve)=>{let child=spawn5(command,["--version"],{stdio:["ignore","pipe","ignore"]}),output="",timer=setTimeout(()=>child.kill(),1e4);child.stdout.setEncoding("utf8").on("data",(chunk)=>{output+=chunk}),child.on("error",()=>{clearTimeout(timer),resolve(null)}),child.on("close",(code)=>{clearTimeout(timer);let line=output.split(`
|
|
109
|
+
`).find((candidate)=>candidate.trim().length>0&&!candidate.startsWith("WARNING"))?.trim()??"";resolve(code===0?/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/u.exec(line)?.[0]??(line.slice(0,80)||"unknown version"):null)})})}var isSupported=(kind,version)=>kind!=="opencode"||Number(version.split(".")[0])>=2;async function detectAgents(){return(await Promise.all(AGENT_KINDS.map(async(kind)=>{let version=await versionOf(COMMANDS[kind]);return version===null||!isSupported(kind,version)?[]:[{kind,version,...await modelsOf(kind,COMMANDS[kind])}]}))).flat()}async function answer(reporter,work,agents,mcp,log,stopped){let agent=agents.find((candidate)=>candidate.kind===work.agent);if(agent===void 0||!isOffered(agent,work.model,work.effort)){log(`Refused a question for a model or effort ${agentLabel(work.agent)} doesn't offer here.`),reporter.report([{kind:"failed",message:`${agentLabel(work.agent)} on this machine doesn't offer that model or effort.`}],!0);return}let stop=new AbortController,onStopped=()=>{if(!stop.signal.aborted)log("Stopped: the reviewer closed the question.");stop.abort()};if(stopped?.aborted)return;stopped?.addEventListener("abort",onStopped,{once:!0});let pending=[],lastReport=Date.now(),flush=(isDone)=>{let events=pending;pending=[],lastReport=Date.now(),reporter.report(events,isDone)};flush(!1);let timer=setInterval(()=>{if(pending.length>0||Date.now()-lastReport>=HEARTBEAT_MS)flush(!1)},REPORT_EVERY_MS);log(`${agentLabel(work.agent)} is answering a question about ${work.snapshotId.slice(0,18)}…`);try{await runAgent(work,mcp,(event)=>{pending.push(event)},stop.signal)}finally{clearInterval(timer),stopped?.removeEventListener("abort",onStopped)}if(!stop.signal.aborted)flush(!0);log(`${agentLabel(work.agent)} finished.`)}var decodeFrame=decodeUnknownOption2(fromJsonString2(HubFrame)),encodeFrame=encodeSync(fromJsonString2(CompanionFrame)),decodeError=decodeUnknownOption2(Struct({error:Struct({message:String4})})),TIMING={openMs:20000,welcomeMs:15000,probeMs:1e4,retryMs:RETRY_MS,maxRetryMs:60000},OPEN=1,CLOSED=3,webTransport={open:(url,headers,events)=>{let socket=Reflect.construct(WebSocket,[url,{headers}]),isOpened=!1;return socket.addEventListener("open",()=>{isOpened=!0,events.onOpen()}),socket.addEventListener("message",(event)=>events.onMessage(event.data)),socket.addEventListener("error",(event)=>{let message=Reflect.get(event,"message");if(events.onError(typeof message==="string"?message:""),socket.readyState===CLOSED||!isOpened)events.onClose(1006,"")}),socket.addEventListener("close",(event)=>events.onClose(event.code,event.reason)),{send:(text)=>socket.send(text),close:(code,reason)=>socket.close(code,reason),isOpen:()=>socket.readyState===OPEN}},probe:(url,headers,signal)=>fetch(url,{headers,signal,redirect:"manual"})},duration2=(ms)=>ms>=1000?`${Math.round(ms/100)/10} s`:`${ms} ms`,closeDetail=(code,reason)=>`code ${code}${reason.length>0?`: ${reason}`:""}`,workspaceLabel2=(workspace)=>workspace.personal?"your personal workspace":`the workspace “${workspace.name}”`;async function readRefusal(transport,url,token,ms,signal,socketError){let plain=new URL(url);plain.protocol=plain.protocol==="wss:"?"https:":"http:";try{let response=await transport.probe(plain,{authorization:`Bearer ${token}`},AbortSignal.any([signal,AbortSignal.timeout(ms)])),text=await response.text().catch(()=>""),parsed=(()=>{try{return decodeError(JSON.parse(text))}catch{return decodeError(void 0)}})(),message=parsed._tag==="Some"?parsed.value.error.message:response.statusText,status=response.status,said=message.length>0?`: ${message}`:"";if(status>=300&&status<400)return{status,line:`DiffClarity redirected the connection (HTTP ${status} to ${response.headers.get("location")??"another page"}). Something in front of DiffClarity, such as a sign-in page, is catching the companion's requests.`};if(status===400)return{status,line:`DiffClarity accepted the companion's access but didn't open the WebSocket${socketError.length>0?` (${socketError})`:""}.`};return{status,line:`DiffClarity refused the connection (HTTP ${status}${said}).`}}catch(error){let reason=error instanceof Error?error.message:String(error);return{status:null,line:`Couldn't reach DiffClarity: ${socketError.length>0?socketError:reason}.`}}}async function serve(access,agents,mcp,log,signal,options={}){let transport=options.transport??webTransport,timing=options.timing??TIMING,onActivity=options.onActivity??(()=>{return}),onWelcome=options.onWelcome??(()=>{return}),answering=new Map,waiting=[],current=null,isWelcome=!1,send=(text)=>{if(current!==null&&isWelcome&¤t.isOpen())current.send(text);else waiting.push(text)},reporterFor=(runId)=>({report:(events,isDone)=>send(encodeFrame({kind:"report",runId,report:{events:[...events],isDone}}))}),agentNames=agents.map((agent)=>agentLabel(agent.kind)).join(", "),url=new URL(COMPANION_SOCKET_PATH,access.origin);url.protocol=url.protocol==="https:"?"wss:":"ws:";let take=(work)=>{if(answering.has(work.runId))return;let stop=new AbortController,onShutdown=()=>stop.abort();signal.addEventListener("abort",onShutdown,{once:!0}),onActivity({kind:"answering",runId:work.runId,agent:work.agent});let done=answer(reporterFor(work.runId),work,agents,mcp,log,stop.signal).catch((error)=>log(`The agent failed: ${error instanceof Error?error.message:String(error)}`)).finally(()=>{answering.delete(work.runId),signal.removeEventListener("abort",onShutdown),onActivity({kind:"answered",runId:work.runId})});answering.set(work.runId,{stop,done})},stopAnswering=async()=>{for(let entry of answering.values())entry.stop.abort();await Promise.allSettled([...answering.values()].map((entry)=>entry.done))},welcomes=0,connectOnce=(token)=>new Promise((resolve)=>{let phase="opening",socketError="",isEnded=!1,hasWarned=!1,timer,ping,link=null,end=(ending)=>{if(isEnded)return;if(isEnded=!0,clearTimeout(timer),clearInterval(ping),signal.removeEventListener("abort",onAbort),current===link)current=null,isWelcome=!1;resolve(ending)},giveUp=(ending)=>{end(ending);try{link?.close(1000,ending.kind==="stopped"?"The companion stopped.":"The companion gave up waiting.")}catch{}},onAbort=()=>giveUp({kind:"stopped"});signal.addEventListener("abort",onAbort,{once:!0}),timer=setTimeout(()=>giveUp({kind:"no-answer"}),timing.openMs);try{link=openLink()}catch(error){end({kind:"not-opened",message:error instanceof Error?error.message:String(error)})}function openLink(){return transport.open(url,{authorization:`Bearer ${token}`},{onOpen:()=>{if(isEnded||link===null)return;phase="greeting",log("Connection open. Waiting for DiffClarity to confirm it…"),clearTimeout(timer),timer=setTimeout(()=>giveUp({kind:"not-welcomed"}),timing.welcomeMs),ping=setInterval(()=>{if(link?.isOpen())link.send(LIVE_PING)},PING_MS),link.send(encodeFrame({kind:"hello",hello:{version:COMPANION_VERSION,agents}}))},onMessage:(data)=>{if(isEnded||link===null||data===LIVE_PONG)return;let frame=typeof data==="string"?decodeFrame(data):decodeFrame(void 0);if(frame._tag==="None"){if(!hasWarned)log("DiffClarity sent a message this companion doesn't understand. Update the companion.");hasWarned=!0;return}switch(frame.value.kind){case"welcome":{if(phase==="welcomed")return;clearTimeout(timer),phase="welcomed",current=link,isWelcome=!0;for(let text of waiting.splice(0))link.send(text);let workspace=frame.value.workspace,where=workspace!==void 0?` for ${workspaceLabel2(workspace)}`:"";if(welcomes+=1,onActivity({kind:"connected"}),log(welcomes>1?`Connected again to ${access.origin}${where}.`:options.isOneOfSeveral===!0?`Connected to ${access.origin}${where} with ${agentNames}.`:`Connected to ${access.origin}${where} with ${agentNames}. It answers questions asked in reviews of that workspace only. Ask in a review's Assistant panel; keep this running, and press Ctrl+C to stop.`),workspace!==void 0)onWelcome(workspace);return}case"work":take(frame.value.run);return;case"cancel":answering.get(frame.value.runId)?.stop.abort();return}},onError:(message)=>{socketError=message},onClose:(code,reason)=>end(phase==="opening"?{kind:"not-opened",message:socketError.length>0?socketError:closeDetail(code,reason)}:{kind:"closed",wasWelcomed:phase==="welcomed",code,reason})})}}),failures=0,isRefused=!1;log(`Connecting to ${access.origin}…`);while(!signal.aborted){onActivity({kind:"connecting"});let token=null,tokenFailure="";try{token=await access.accessToken(isRefused)}catch(error){if(error instanceof NeedsSignIn)throw await stopAnswering(),error;tokenFailure=error instanceof Error?error.message:String(error)}let ending=token===null?{kind:"no-access",message:tokenFailure}:await connectOnce(token);if(ending.kind==="stopped"||signal.aborted)break;isRefused=!1;let failed=(line)=>{log(line),onActivity({kind:"failing",reason:line})};switch(ending.kind){case"no-access":failed(`Couldn't renew the companion's access: ${ending.message}`);break;case"no-answer":failed(`DiffClarity didn't answer the connection within ${duration2(timing.openMs)}.`);break;case"not-welcomed":failed(`DiffClarity opened the connection but didn't confirm it within ${duration2(timing.welcomeMs)}.`);break;case"closed":if(ending.wasWelcomed)log(`Lost the connection to DiffClarity (${closeDetail(ending.code,ending.reason)}).`),onActivity({kind:"lost"});else failed(`DiffClarity closed the connection before confirming it (${closeDetail(ending.code,ending.reason)}).`);break;case"not-opened":{if(token!==null){let refusal=await readRefusal(transport,url,token,timing.probeMs,signal,ending.message);if(signal.aborted)break;if(failed(refusal.line),isRefused=refusal.status===401,refusal.status===403)throw await stopAnswering(),Error(`DiffClarity refuses this companion's access in this workspace. Run \`${addWorkspaceCommand(access.origin)}\` and allow it there again.`)}break}}if(signal.aborted)break;failures=ending.kind==="closed"&&ending.wasWelcomed?0:failures+1;let pause=Math.min(timing.retryMs*2**Math.max(0,failures-1),timing.maxRetryMs);log(`Trying again in ${duration2(pause)}…`),await new Promise((resolve)=>{let onAbort=()=>{clearTimeout(timer),resolve()},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},pause);signal.addEventListener("abort",onAbort,{once:!0})})}await Promise.allSettled([...answering.values()].map((entry)=>entry.done))}function isZ4Schema(s){return!!s._zod}function safeParse3(schema,data){if(isZ4Schema(schema))return safeParse(schema,data);return schema.safeParse(data)}function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema))rawShape=schema._zod?.def?.shape;else rawShape=schema.shape;if(!rawShape)return;if(typeof rawShape==="function")try{return rawShape()}catch{return}return rawShape}function getLiteralValue(schema){if(isZ4Schema(schema)){let def=schema._zod?.def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue;return}function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!=="string")throw Error("Schema method literal must be a string");return value}function parseWithCompat(schema,data){let result=safeParse3(schema,data);if(!result.success)throw result.error;return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=60000;class Protocol{constructor(_options){if(this._options=_options,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,(notification)=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,(notification)=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,(_request)=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore)this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=async()=>{let taskId=request.params.taskId;if(!await this._taskStore.getTask(taskId,extra.sessionId))throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(this._taskMessageQueue){let queuedMessage;while(queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId)){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage=message,error=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal,extra.sessionId),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId,extra.sessionId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error instanceof Error?error.message:String(error)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId,extra.sessionId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error){if(error instanceof McpError)throw error;throw new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error instanceof Error?error.message:String(error)}`)}})}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(info)clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId)}async connect(transport){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=(error)=>{_onerror?.(error),this._onerror(error)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{if(_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message))this._onresponse(message);else if(isJSONRPCRequest(message))this._onrequest(message,extra);else if(isJSONRPCNotification(message))this._onnotification(message);else this._onerror(Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error)}_onerror(error){this.onerror?.(error)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;if(handler===void 0)return;Promise.resolve().then(()=>handler(notification)).catch((error)=>this._onerror(Error(`Uncaught error in notification handler: ${error}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId,sessionId=capturedTransport?.sessionId,store=this._taskStore,relatedTaskFound=!0,relatedTaskLookup;if(relatedTaskId&&store&&this._taskMessageQueue&&sessionId!==void 0)relatedTaskFound=!1,relatedTaskLookup=(async()=>{if(!await store.getTask(relatedTaskId,sessionId))throw new McpError(ErrorCode.InvalidParams,`Task not found: ${relatedTaskId}`);relatedTaskFound=!0})();if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};if(relatedTaskId&&relatedTaskLookup){let queuedError={type:"error",message:errorResponse,timestamp:Date.now()};relatedTaskLookup.then(()=>this._enqueueTaskMessage(relatedTaskId,queuedError,sessionId),()=>capturedTransport?.send(errorResponse)).catch((error)=>this._onerror(Error(`Failed to send an error response: ${error}`)))}else if(relatedTaskId&&this._taskMessageQueue)this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch((error)=>this._onerror(Error(`Failed to enqueue error response: ${error}`)));else capturedTransport?.send(errorResponse).catch((error)=>this._onerror(Error(`Failed to send an error response: ${error}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:async(notification)=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};if(relatedTaskId)notificationOptions.relatedTask={taskId:relatedTaskId};await this.notification(notification,notificationOptions)},sendRequest:async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};if(relatedTaskId&&!requestOptions.relatedTask)requestOptions.relatedTask={taskId:relatedTaskId};let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;if(effectiveTaskId&&taskStore)await taskStore.updateTaskStatus(effectiveTaskId,"input_required");return await this.request(r,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};(relatedTaskLookup??Promise.resolve()).then(()=>{if(relatedTaskLookup&&abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");if(taskCreationParams)this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async(result)=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};if(relatedTaskId&&this._taskMessageQueue)await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId);else await capturedTransport?.send(response)},async(error)=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error.code)?error.code:ErrorCode.InternalError,message:error.message??"Internal error",...error.data!==void 0&&{data:error.data}}};if(relatedTaskId&&this._taskMessageQueue&&relatedTaskFound)await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId);else await capturedTransport?.send(errorResponse)}).catch((error)=>this._onerror(Error(`Failed to send response: ${error}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(request.id)===abortController)this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error=new McpError(response.error.code,response.error.message,response.error.data);resolver(error)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result==="object"){let result=response.result;if(result.task&&typeof result.task==="object"){let task=result.task;if(typeof task.taskId==="string")isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId)}}if(!isTaskResponse)this._progressHandlers.delete(messageId);if(isJSONRPCResultResponse(response))handler(response);else{let error=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");while(!0){let task=await this.getTask({taskId},options);if(yield{type:"taskStatus",task},isTerminal(task.status)){if(task.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};else if(task.status==="failed")yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)};else if(task.status==="cancelled")yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)};return}if(task.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((resolve)=>setTimeout(resolve,pollInterval)),options?.signal?.throwIfAborted()}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve,reject)=>{let earlyReject=(error)=>{reject(error)};if(!this._transport){earlyReject(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(request.method),task)this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};if(options?.onprogress)this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}};if(task)jsonrpcRequest.params={...jsonrpcRequest.params,task};if(relatedTask)jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}};let cancel=(reason)=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch((error)=>this._onerror(Error(`Failed to send cancellation: ${error}`)));let error=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error)};this._responseHandlers.set(messageId,(response)=>{if(options?.signal?.aborted)return;if(response instanceof Error)return reject(response);try{let parseResult=safeParse3(resultSchema,response.result);if(!parseResult.success)reject(parseResult.error);else resolve(parseResult.data)}catch(error){reject(error)}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=(response)=>{let handler=this._responseHandlers.get(messageId);if(handler)handler(response);else this._onerror(Error(`Response handler missing for side-channeled request ${messageId}`))};this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch((error)=>{this._cleanupTimeout(messageId),reject(error)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch((error)=>{this._cleanupTimeout(messageId),reject(error)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask)jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};this._transport?.send(jsonrpcNotification,options).catch((error)=>this._onerror(error))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask)jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,(notification)=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);if(progressToken!==void 0)this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId)}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId??this._transport?.sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);if(resolver)resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId);else this._onerror(Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal,sessionId){let interval=this._options?.defaultTaskPollInterval??1000;try{let task=await this._taskStore?.getTask(taskId,sessionId);if(task?.pollInterval)interval=task.pollInterval}catch{}return new Promise((resolve,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw Error("No task store configured");return{createTask:async(taskParams)=>{if(!request)throw Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},getTask:async(taskId)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},storeTaskResult:async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});if(await this.notification(notification),isTerminal(task.status))this._cleanupTaskProgressHandler(taskId)}},getTaskResult:(taskId)=>taskStore.getTaskResult(taskId,sessionId),updateTaskStatus:async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});if(await this.notification(notification),isTerminal(updatedTask.status))this._cleanupTaskProgressHandler(taskId)}},listTasks:(cursor)=>taskStore.listTasks(cursor,sessionId)}}}function isPlainObject2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];if(isPlainObject2(baseValue)&&isPlainObject2(addValue))result[k]={...baseValue,...addValue};else result[k]=addValue}return result}var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return import_ajv_formats.default(ajv),ajv}class AjvJsonSchemaValidator{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id==="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return(input)=>{if(ajvValidator(input))return{valid:!0,data:input,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}}}class ExperimentalClientTasks{constructor(_client){this._client=_client}async*callToolStream(params,resultSchema=CallToolResultSchema,options){let clientInternal=this._client,optionsWithTask={...options,task:options?.task??(clientInternal.isToolTask(params.name)?{}:void 0)},stream=clientInternal.requestStream({method:"tools/call",params},resultSchema,optionsWithTask),validator=clientInternal.getToolOutputValidator(params.name);for await(let message of stream){if(message.type==="result"&&validator){let result=message.result;if(!result.structuredContent&&!result.isError){yield{type:"error",error:new McpError(ErrorCode.InvalidRequest,`Tool ${params.name} has an output schema but did not return structured content`)};return}if(result.structuredContent)try{let validationResult=validator(result.structuredContent);if(!validationResult.valid){yield{type:"error",error:new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)};return}}catch(error){if(error instanceof McpError){yield{type:"error",error};return}yield{type:"error",error:new McpError(ErrorCode.InvalidParams,`Failed to validate structured content: ${error instanceof Error?error.message:String(error)}`)};return}}yield message}}async getTask(taskId,options){return this._client.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._client.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._client.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._client.cancelTask({taskId},options)}requestStream(request,resultSchema,options){return this._client.requestStream(request,resultSchema,options)}}function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}function applyElicitationDefaults(schema,data){if(!schema||data===null||typeof data!=="object")return;if(schema.type==="object"&&schema.properties&&typeof schema.properties==="object"){let obj=data,props=schema.properties;for(let key of Object.keys(props)){let propSchema=props[key];if(obj[key]===void 0&&Object.prototype.hasOwnProperty.call(propSchema,"default"))obj[key]=propSchema.default;if(obj[key]!==void 0)applyElicitationDefaults(propSchema,obj[key])}}if(Array.isArray(schema.anyOf)){for(let sub of schema.anyOf)if(typeof sub!=="boolean")applyElicitationDefaults(sub,data)}if(Array.isArray(schema.oneOf)){for(let sub of schema.oneOf)if(typeof sub!=="boolean")applyElicitationDefaults(sub,data)}}function getSupportedElicitationModes(capabilities){if(!capabilities)return{supportsFormMode:!1,supportsUrlMode:!1};let hasFormCapability=capabilities.form!==void 0,hasUrlCapability=capabilities.url!==void 0;return{supportsFormMode:hasFormCapability||!hasFormCapability&&!hasUrlCapability,supportsUrlMode:hasUrlCapability}}class Client extends Protocol{constructor(_clientInfo,options){super(options);if(this._clientInfo=_clientInfo,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=options?.capabilities??{},this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,options?.listChanged)this._pendingListChangedConfig=options.listChanged}_setupListChangedHandlers(config){if(config.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",ToolListChangedNotificationSchema,config.tools,async()=>(await this.listTools()).tools);if(config.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",PromptListChangedNotificationSchema,config.prompts,async()=>(await this.listPrompts()).prompts);if(config.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",ResourceListChangedNotificationSchema,config.resources,async()=>(await this.listResources()).resources)}get experimental(){if(!this._experimental)this._experimental={tasks:new ExperimentalClientTasks(this)};return this._experimental}registerCapabilities(capabilities){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw Error("Schema is missing a method literal");let methodValue=getLiteralValue(methodSchema);if(typeof methodValue!=="string")throw Error("Schema method literal must be a string");let method=methodValue;if(method==="elicitation/create"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse3(ElicitRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid elicitation request: ${errorMessage}`)}let{params}=validatedRequest.data;params.mode=params.mode??"form";let{supportsFormMode,supportsUrlMode}=getSupportedElicitationModes(this._capabilities.elicitation);if(params.mode==="form"&&!supportsFormMode)throw new McpError(ErrorCode.InvalidParams,"Client does not support form-mode elicitation requests");if(params.mode==="url"&&!supportsUrlMode)throw new McpError(ErrorCode.InvalidParams,"Client does not support URL-mode elicitation requests");let result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let validationResult=safeParse3(ElicitResultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid elicitation result: ${errorMessage}`)}let validatedResult=validationResult.data,requestedSchema=params.mode==="form"?params.requestedSchema:void 0;if(params.mode==="form"&&validatedResult.action==="accept"&&validatedResult.content&&requestedSchema){if(this._capabilities.elicitation?.form?.applyDefaults)try{applyElicitationDefaults(requestedSchema,validatedResult.content)}catch{}}return validatedResult};return super.setRequestHandler(requestSchema,wrappedHandler)}if(method==="sampling/createMessage"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse3(CreateMessageRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid sampling request: ${errorMessage}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let resultSchema=params.tools||params.toolChoice?CreateMessageResultWithToolsSchema:CreateMessageResultSchema,validationResult=safeParse3(resultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid sampling result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapability(capability,method){if(!this._serverCapabilities?.[capability])throw Error(`Server does not support ${capability} (required for ${method})`)}async connect(transport,options){if(await super.connect(transport),transport.sessionId!==void 0)return;try{let result=await this.request({method:"initialize",params:{protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:this._capabilities,clientInfo:this._clientInfo}},InitializeResultSchema,options);if(result===void 0)throw Error(`Server sent invalid initialize result: ${result}`);if(!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))throw Error(`Server's protocol version is not supported: ${result.protocolVersion}`);if(this._serverCapabilities=result.capabilities,this._serverVersion=result.serverInfo,transport.setProtocolVersion)transport.setProtocolVersion(result.protocolVersion);if(this._instructions=result.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(error){throw this.close(),error}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(method){switch(method){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${method})`);if(method==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${method})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${method})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${method})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(!this._capabilities)return;switch(method){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${method})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${method})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${method})`);break;case"ping":break}}assertTaskCapability(method){assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests,method,"Server")}assertTaskHandlerCapability(method){if(!this._capabilities)return;assertClientRequestTaskCapability(this._capabilities.tasks?.requests,method,"Client")}async ping(options){return this.request({method:"ping"},EmptyResultSchema,options)}async complete(params,options){return this.request({method:"completion/complete",params},CompleteResultSchema,options)}async setLoggingLevel(level,options){return this.request({method:"logging/setLevel",params:{level}},EmptyResultSchema,options)}async getPrompt(params,options){return this.request({method:"prompts/get",params},GetPromptResultSchema,options)}async listPrompts(params,options){return this.request({method:"prompts/list",params},ListPromptsResultSchema,options)}async listResources(params,options){return this.request({method:"resources/list",params},ListResourcesResultSchema,options)}async listResourceTemplates(params,options){return this.request({method:"resources/templates/list",params},ListResourceTemplatesResultSchema,options)}async readResource(params,options){return this.request({method:"resources/read",params},ReadResourceResultSchema,options)}async subscribeResource(params,options){return this.request({method:"resources/subscribe",params},EmptyResultSchema,options)}async unsubscribeResource(params,options){return this.request({method:"resources/unsubscribe",params},EmptyResultSchema,options)}async callTool(params,resultSchema=CallToolResultSchema,options){if(this.isToolTaskRequired(params.name))throw new McpError(ErrorCode.InvalidRequest,`Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let result=await this.request({method:"tools/call",params},resultSchema,options),validator=this.getToolOutputValidator(params.name);if(validator){if(!result.structuredContent&&!result.isError)throw new McpError(ErrorCode.InvalidRequest,`Tool ${params.name} has an output schema but did not return structured content`);if(result.structuredContent)try{let validationResult=validator(result.structuredContent);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)}catch(error){if(error instanceof McpError)throw error;throw new McpError(ErrorCode.InvalidParams,`Failed to validate structured content: ${error instanceof Error?error.message:String(error)}`)}}return result}isToolTask(toolName){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has(toolName)}isToolTaskRequired(toolName){return this._cachedRequiredTaskTools.has(toolName)}cacheToolMetadata(tools){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let tool of tools){if(tool.outputSchema){let toolValidator=this._jsonSchemaValidator.getValidator(tool.outputSchema);this._cachedToolOutputValidators.set(tool.name,toolValidator)}let taskSupport=tool.execution?.taskSupport;if(taskSupport==="required"||taskSupport==="optional")this._cachedKnownTaskTools.add(tool.name);if(taskSupport==="required")this._cachedRequiredTaskTools.add(tool.name)}}getToolOutputValidator(toolName){return this._cachedToolOutputValidators.get(toolName)}async listTools(params,options){let result=await this.request({method:"tools/list",params},ListToolsResultSchema,options);return this.cacheToolMetadata(result.tools),result}_setupListChangedHandler(listType,notificationSchema,options,fetcher){let parseResult=ListChangedOptionsBaseSchema.safeParse(options);if(!parseResult.success)throw Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);if(typeof options.onChanged!=="function")throw Error(`Invalid ${listType} listChanged options: onChanged must be a function`);let{autoRefresh,debounceMs}=parseResult.data,{onChanged}=options,refresh=async()=>{if(!autoRefresh){onChanged(null,null);return}try{let items=await fetcher();onChanged(null,items)}catch(e){let error=e instanceof Error?e:Error(String(e));onChanged(error,null)}},handler=()=>{if(debounceMs){let existingTimer=this._listChangedDebounceTimers.get(listType);if(existingTimer)clearTimeout(existingTimer);let timer=setTimeout(refresh,debounceMs);this._listChangedDebounceTimers.set(listType,timer)}else refresh()};this.setNotificationHandler(notificationSchema,handler)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}/*!
|
|
106
110
|
* content-type
|
|
107
111
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
108
112
|
* MIT Licensed
|
|
@@ -117,15 +121,19 @@ ${value}`,dataLines++}else isEventPrefix(chunk,searchIndex,firstCharCode)?eventT
|
|
|
117
121
|
${value2}`,dataLines++;return}if(isEventPrefix(chunk,start,firstCharCode)){eventType=chunk.slice(chunk.charCodeAt(start+6)===SPACE?start+7:start+6,end)||void 0;return}if(firstCharCode===105&&chunk.charCodeAt(start+1)===100&&chunk.charCodeAt(start+2)===58){let value2=chunk.slice(chunk.charCodeAt(start+3)===SPACE?start+4:start+3,end);value2.includes("\x00")||(id=value2);return}if(firstCharCode===58){if(onComment){let line2=chunk.slice(start,end);onComment(line2.slice(chunk.charCodeAt(start+1)===SPACE?2:1))}return}let line=chunk.slice(start,end),fieldSeparatorIndex=line.indexOf(":");if(fieldSeparatorIndex===-1){processField(line,"",line);return}let field=line.slice(0,fieldSeparatorIndex),offset=line.charCodeAt(fieldSeparatorIndex+1)===SPACE?2:1,value=line.slice(fieldSeparatorIndex+offset);processField(field,value,line)}function processField(field,value,line){switch(field){case"event":eventType=value||void 0;break;case"data":data=dataLines===0?value:`${data}
|
|
118
122
|
${value}`,dataLines++;break;case"id":value.includes("\x00")||(id=value);break;case"retry":/^\d+$/.test(value)?onRetry(parseInt(value,10)):onError(new ParseError(`Invalid \`retry\` value: "${value}"`,{type:"invalid-retry",value,line}));break;default:onError(new ParseError(`Unknown field "${field.length>20?`${field.slice(0,20)}…`:field}"`,{type:"unknown-field",field,value,line}));break}}function dispatchEvent(){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data="",dataLines=0,eventType=void 0}function reset(options={}){if(options.consume&&pendingFragments.length>0){let incompleteLine=pendingFragments.join("");parseLine(incompleteLine,0,incompleteLine.length)}isFirstChunk=!0,id=void 0,data="",dataLines=0,eventType=void 0,pendingFragments.length=0,pendingFragmentsLength=0,terminated=!1}return{feed,reset}}function isDataPrefix(chunk,i,firstCharCode){return firstCharCode===100&&chunk.charCodeAt(i+1)===97&&chunk.charCodeAt(i+2)===116&&chunk.charCodeAt(i+3)===97&&chunk.charCodeAt(i+4)===58}function isEventPrefix(chunk,i,firstCharCode){return firstCharCode===101&&chunk.charCodeAt(i+1)===118&&chunk.charCodeAt(i+2)===101&&chunk.charCodeAt(i+3)===110&&chunk.charCodeAt(i+4)===116&&chunk.charCodeAt(i+5)===58}class EventSourceParserStream extends TransformStream{constructor({onError,onRetry,onComment,maxBufferSize}={}){let parser;super({start(controller){parser=createParser({onEvent:(event)=>{controller.enqueue(event)},onError(error){typeof onError=="function"&&onError(error),(onError==="terminate"||error.type==="max-buffer-size-exceeded")&&controller.error(error)},onRetry,onComment,maxBufferSize})},transform(chunk){parser.feed(chunk)}})}}var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class StreamableHTTPError extends Error{constructor(code,message){super(`Streamable HTTP error: ${message}`);this.code=code}}class StreamableHTTPClientTransport{constructor(url,opts){if(this._hasCompletedAuthFlow=!1,this._url=url,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=opts?.requestInit,this._authProvider=opts?.authProvider,this._fetch=opts?.fetch,this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit),this._followRedirects=opts?.redirectPolicy==="follow",this._followRedirects)this._fetch=fetchLeavingRedirects(this._fetch),this._fetchWithInit=fetchLeavingRedirects(this._fetchWithInit);this._sessionId=opts?.sessionId,this._reconnectionOptions=opts?.reconnectionOptions??DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS}_unfollowedRedirect(response,url){let text=unfollowedRedirect(response,url);return text&&!this._followRedirects?`${text} (redirectPolicy: 'same-origin')`:text}async _authThenStart(){if(!this._authProvider)throw new UnauthorizedError("No auth provider");let result;try{result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(error){throw this.onerror?.(error),error}if(result!=="AUTHORIZED")throw new UnauthorizedError;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let headers={};if(this._authProvider){let tokens=await this._authProvider.tokens();if(tokens)headers.Authorization=`Bearer ${tokens.access_token}`}if(this._sessionId)headers["mcp-session-id"]=this._sessionId;if(this._protocolVersion)headers["mcp-protocol-version"]=this._protocolVersion;let extraHeaders=normalizeHeaders(this._requestInit?.headers);return new Headers({...headers,...extraHeaders})}async _startOrAuthSse(options){let{resumptionToken}=options;try{let headers=await this._commonHeaders();if(headers.set("Accept","text/event-stream"),resumptionToken)headers.set("last-event-id",resumptionToken);let fetchFn=this._fetch??fetch,init={method:"GET",headers,signal:this._abortController?.signal},response=await fetchFn(this._url,this._followRedirects?init:{...init,redirect:"manual"}),followed=this._followRedirects?void 0:followWithinOrigin(fetchFn,this._url,init,response);if(followed)response=await followed;if(!response.ok){if(await response.body?.cancel(),response.status===401&&this._authProvider)return await this._authThenStart();if(response.status===405)return;throw new StreamableHTTPError(response.status,`Failed to open SSE stream: ${this._unfollowedRedirect(response,this._url)??response.statusText}`)}this._handleSseStream(response.body,options,!0)}catch(error){throw this.onerror?.(error),error}}_getNextReconnectionDelay(attempt){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let initialDelay=this._reconnectionOptions.initialReconnectionDelay,growFactor=this._reconnectionOptions.reconnectionDelayGrowFactor,maxDelay=this._reconnectionOptions.maxReconnectionDelay;return Math.min(initialDelay*Math.pow(growFactor,attempt),maxDelay)}_scheduleReconnection(options,attemptCount=0){let maxRetries=this._reconnectionOptions.maxRetries;if(attemptCount>=maxRetries){this.onerror?.(Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));return}let delay=this._getNextReconnectionDelay(attemptCount);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(options).catch((error)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${error instanceof Error?error.message:String(error)}`)),this._scheduleReconnection(options,attemptCount+1)})},delay)}_handleSseStream(stream,options,isReconnectable){if(!stream)return;let{onresumptiontoken,replayMessageId}=options,lastEventId,hasPrimingEvent=!1,receivedResponse=!1;(async()=>{try{let reader=stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream({onRetry:(retryMs)=>{this._serverRetryMs=retryMs}})).getReader();while(!0){let{value:event,done}=await reader.read();if(done)break;if(event.id)lastEventId=event.id,hasPrimingEvent=!0,onresumptiontoken?.(event.id);if(!event.data)continue;if(!event.event||event.event==="message")try{let message=JSONRPCMessageSchema.parse(JSON.parse(event.data));if(isJSONRPCResultResponse(message)){if(receivedResponse=!0,replayMessageId!==void 0)message.id=replayMessageId}this.onmessage?.(message)}catch(error){this.onerror?.(error)}}if((isReconnectable||hasPrimingEvent)&&!receivedResponse&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:lastEventId,onresumptiontoken,replayMessageId},0)}catch(error){if(this.onerror?.(Error(`SSE stream disconnected: ${error}`)),(isReconnectable||hasPrimingEvent)&&!receivedResponse&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:lastEventId,onresumptiontoken,replayMessageId},0)}catch(error){this.onerror?.(Error(`Failed to reconnect: ${error instanceof Error?error.message:String(error)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(authorizationCode){if(!this._authProvider)throw new UnauthorizedError("No auth provider");if(await auth(this._authProvider,{serverUrl:this._url,authorizationCode,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send(message,options){try{let{resumptionToken,onresumptiontoken}=options||{};if(resumptionToken){this._startOrAuthSse({resumptionToken,replayMessageId:isJSONRPCRequest(message)?message.id:void 0}).catch((err)=>this.onerror?.(err));return}let headers=await this._commonHeaders();headers.set("content-type","application/json"),headers.set("accept","application/json, text/event-stream");let init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal:this._abortController?.signal},response=await fetchWithinOrigin(this._fetch??fetch)(this._url,init),sessionId=response.headers.get("mcp-session-id");if(sessionId)this._sessionId=sessionId;if(!response.ok){let text=await response.text().catch(()=>null);if(response.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new StreamableHTTPError(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl,scope}=extractWWWAuthenticateParams(response);if(this._resourceMetadataUrl=resourceMetadataUrl,this._scope=scope,await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError;return this._hasCompletedAuthFlow=!0,this.send(message)}if(response.status===403&&this._authProvider){let{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(error==="insufficient_scope"){let wwwAuthHeader=response.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===wwwAuthHeader)throw new StreamableHTTPError(403,"Server returned 403 after trying upscoping");if(scope)this._scope=scope;if(resourceMetadataUrl)this._resourceMetadataUrl=resourceMetadataUrl;if(this._lastUpscopingHeader=wwwAuthHeader??void 0,await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new UnauthorizedError;return this.send(message)}}throw new StreamableHTTPError(response.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(response,this._url)??text}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,response.status===202){if(await response.body?.cancel(),isInitializedNotification(message))this._startOrAuthSse({resumptionToken:void 0}).catch((err)=>this.onerror?.(err));return}let hasRequests=(Array.isArray(message)?message:[message]).filter((msg)=>("method"in msg)&&("id"in msg)&&msg.id!==void 0).length>0,contentType=response.headers.get("content-type"),responseMediaType=mediaTypeEssence(contentType);if(hasRequests)if(responseMediaType==="text/event-stream")this._handleSseStream(response.body,{onresumptiontoken},!1);else if(responseMediaType==="application/json"){let data=await response.json(),responseMessages=Array.isArray(data)?data.map((msg)=>JSONRPCMessageSchema.parse(msg)):[JSONRPCMessageSchema.parse(data)];for(let msg of responseMessages)this.onmessage?.(msg)}else throw await response.body?.cancel(),new StreamableHTTPError(-1,`Unexpected content type: ${contentType}`);else await response.body?.cancel()}catch(error){throw this.onerror?.(error),error}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let headers=await this._commonHeaders(),init={...this._requestInit,method:"DELETE",headers,signal:this._abortController?.signal},response=await fetchWithinOrigin(this._fetch??fetch)(this._url,init);if(await response.body?.cancel(),!response.ok&&response.status!==405)throw new StreamableHTTPError(response.status,`Failed to terminate session: ${this._unfollowedRedirect(response,this._url)??response.statusText}`);this._sessionId=void 0}catch(error){throw this.onerror?.(error),error}}setProtocolVersion(version){this._protocolVersion=version}get protocolVersion(){return this._protocolVersion}async resumeStream(lastEventId,options){await this._startOrAuthSse({resumptionToken:lastEventId,onresumptiontoken:options?.onresumptiontoken})}}class ExperimentalServerTasks{constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some((c)=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some((c)=>c.type==="tool_use");if(hasToolResults){if(lastContent.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter((c)=>c.type==="tool_use").map((c)=>c.id)),toolResultIds=new Set(lastContent.filter((c)=>c.type==="tool_result").map((c)=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every((id)=>toolResultIds.has(id)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode=params.mode??"form";switch(mode){case"url":{if(!clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let normalizedParams=mode==="form"&¶ms.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}}class Server extends Protocol{constructor(_serverInfo,options){super(options);if(this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index)=>[level,index])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,(request)=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);if(parseResult.success)this._loggingLevels.set(transportSessionId,parseResult.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new ExperimentalServerTasks(this)};return this._experimental}registerCapabilities(capabilities){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw Error("Schema is missing a method literal");let methodValue=getLiteralValue(methodSchema);if(typeof methodValue!=="string")throw Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse3(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let validationResult=safeParse3(CallToolResultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(!this._capabilities)return;switch(method){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){if(!this._capabilities)return;assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if(params.tools||params.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some((c)=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some((c)=>c.type==="tool_use");if(hasToolResults){if(lastContent.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter((c)=>c.type==="tool_use").map((c)=>c.id)),toolResultIds=new Set(lastContent.filter((c)=>c.type==="tool_result").map((c)=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every((id)=>toolResultIds.has(id)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(params.tools)return this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options);return this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error){if(error instanceof McpError)throw error;throw new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error instanceof Error?error.message:String(error)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging){if(!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}import process2 from"node:process";var STDIO_DEFAULT_MAX_BUFFER_SIZE=10485760;class ReadBuffer{constructor(options){this._maxBufferSize=options?.maxBufferSize??STDIO_DEFAULT_MAX_BUFFER_SIZE}append(chunk){if((this._buffer?.length??0)+chunk.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index=this._buffer.indexOf(`
|
|
119
123
|
`);if(index===-1)return null;let line=this._buffer.toString("utf8",0,index).replace(/\r$/,"");return this._buffer=this._buffer.subarray(index+1),deserializeMessage(line)}clear(){this._buffer=void 0}}function deserializeMessage(line){return JSONRPCMessageSchema.parse(JSON.parse(line))}function serializeMessage(message){return JSON.stringify(message)+`
|
|
120
|
-
`}class StdioServerTransport{constructor(_stdin=process2.stdin,_stdout=process2.stdout,options){this._stdin=_stdin,this._stdout=_stdout,this._started=!1,this._ondata=(chunk)=>{try{this._readBuffer.append(chunk),this.processReadBuffer()}catch(error){this.onerror?.(error),this.close().catch(()=>{})}},this._onerror=(error)=>{this.onerror?.(error)},this._readBuffer=new ReadBuffer({maxBufferSize:options?.maxBufferSize})}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error){this.onerror?.(error)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(message){return new Promise((resolve)=>{let json=serializeMessage(message);if(this._stdout.write(json))resolve();else this._stdout.once("drain",resolve)})}}async function runProxy(origin,state,workspace){let remote=new Client({name:"diffclarity-companion",version:COMPANION_VERSION});await remote.connect(new StreamableHTTPClientTransport(mcpUrl(origin),{authProvider:new StoredAccess(origin,state,void 0,void 0,workspace)}));let instructions=remote.getInstructions(),local=new Server({name:"diffclarity",version:COMPANION_VERSION},{capabilities:{tools:{}},...instructions===void 0?{}:{instructions}});local.setRequestHandler(ListToolsRequestSchema,(request)=>remote.listTools(request.params)),local.setRequestHandler(CallToolRequestSchema,(request)=>remote.callTool(request.params)),local.onclose=()=>void remote.close(),await local.connect(new StdioServerTransport)}var initialState={kind:"starting"},linkAfter=(link,activity)=>{switch(activity.kind){case"connecting":return link??{kind:"connecting"};case"connected":return{kind:"connected"};case"lost":return{kind:"reconnecting"};case"failing":return{kind:"failing",reason:activity.reason};case"answering":case"answered":return link}};function next(state,activity){switch(activity.kind){case"signing-in":return state.kind==="
|
|
124
|
+
`}class StdioServerTransport{constructor(_stdin=process2.stdin,_stdout=process2.stdout,options){this._stdin=_stdin,this._stdout=_stdout,this._started=!1,this._ondata=(chunk)=>{try{this._readBuffer.append(chunk),this.processReadBuffer()}catch(error){this.onerror?.(error),this.close().catch(()=>{})}},this._onerror=(error)=>{this.onerror?.(error)},this._readBuffer=new ReadBuffer({maxBufferSize:options?.maxBufferSize})}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error){this.onerror?.(error)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(message){return new Promise((resolve)=>{let json=serializeMessage(message);if(this._stdout.write(json))resolve();else this._stdout.once("drain",resolve)})}}async function runProxy(origin,state,workspace){let remote=new Client({name:"diffclarity-companion",version:COMPANION_VERSION});await remote.connect(new StreamableHTTPClientTransport(mcpUrl(origin),{authProvider:new StoredAccess(origin,state,void 0,void 0,workspace)}));let instructions=remote.getInstructions(),local=new Server({name:"diffclarity",version:COMPANION_VERSION},{capabilities:{tools:{}},...instructions===void 0?{}:{instructions}});local.setRequestHandler(ListToolsRequestSchema,(request)=>remote.listTools(request.params)),local.setRequestHandler(CallToolRequestSchema,(request)=>remote.callTool(request.params)),local.onclose=()=>void remote.close(),await local.connect(new StdioServerTransport)}var initialState={kind:"starting"},linkAfter=(link,activity)=>{switch(activity.kind){case"connecting":return link??{kind:"connecting"};case"connected":return{kind:"connected"};case"lost":return{kind:"reconnecting"};case"failing":return{kind:"failing",reason:activity.reason};case"answering":case"answered":return link}},SERVING_NONE={kind:"serving",links:new Map,runs:new Map,names:new Map};function next(state,activity){switch(activity.kind){case"signing-in":return state.kind==="serving"?state:{kind:"signing-in"};case"choosing":return state.kind==="serving"?state:{kind:"choosing"};case"named":{let serving=state.kind==="serving"?state:SERVING_NONE,names=new Map(serving.names);return names.set(activity.connection,activity.workspace),{...serving,names}}case"ended":{if(state.kind!=="serving")return state;let links=new Map(state.links);links.delete(activity.connection);let names=new Map(state.names);return names.delete(activity.connection),{kind:"serving",links,runs:new Map([...state.runs].filter(([,run])=>run.connection!==activity.connection)),names}}case"connection":{let serving=state.kind==="serving"?state:SERVING_NONE,{connection,activity:step}=activity,runs=new Map(serving.runs);if(step.kind==="answering"&&!runs.has(step.runId))runs.set(step.runId,{connection,agent:step.agent});if(step.kind==="answered"&&runs.get(step.runId)?.connection===connection)runs.delete(step.runId);let links=new Map(serving.links),link=linkAfter(links.get(connection),step);if(link!==void 0)links.set(connection,link);return{...serving,links,runs}}}}var NAME2="DiffClarity companion",titled=(detail,where="")=>`${NAME2}${where.length===0?"":` · ${where}`}${detail===null?"":` · ${detail}`}`,whereOf=(names)=>[...new Set(names.values())].join(", ");function statusOf(state){switch(state.kind){case"starting":return{state:"working",isAuth:!1,title:titled("starting"),msg:"Starting"};case"signing-in":return{state:"blocked",isAuth:!0,title:titled("allow it in your browser"),msg:"Allow the companion in your browser"};case"choosing":return{state:"blocked",isAuth:!1,title:titled("choose workspaces"),msg:"Choose the workspaces to answer in"};case"serving":{let where=whereOf(state.names),inWhere=where.length===0?"":` in ${where}`,runs=[...state.runs.values()],[only]=runs;if(only!==void 0){let answeringIn=whereOf(new Map(runs.flatMap((run)=>{let name=state.names.get(run.connection);return name===void 0?[]:[[run.connection,name]]})));return{state:"working",isAuth:!1,title:titled("answering",where),msg:`${runs.length===1?`${agentLabel(only.agent)} is answering a question`:`Answering ${runs.length} questions`}${answeringIn.length===0?"":` in ${answeringIn}`}`}}let links=[...state.links.values()],failing=links.find((link)=>link.kind==="failing");if(failing!==void 0)return{state:"error",isAuth:!1,title:titled("can't connect",where),msg:`${failing.reason} Trying again.`};if(links.some((link)=>link.kind==="reconnecting"))return{state:"working",isAuth:!1,title:titled("connecting",where),msg:`Connecting to DiffClarity again${inWhere}`};if(links.some((link)=>link.kind==="connecting"))return{state:"working",isAuth:!1,title:titled("connecting",where),msg:`Connecting to DiffClarity${inWhere}`};return links.length===0?{state:"idle",isAuth:!1,title:NAME2,msg:"Stopping"}:{state:"idle",isAuth:!1,title:titled(null,where),msg:`Waiting for questions${inWhere}`}}}}var ESC="\x1B",BEL="\x07",ST=`${ESC}\\`,RECORD="id=diffclarity-companion",APP="app=diffclarity-companion",graphemes=new Intl.Segmenter(void 0,{granularity:"grapheme"}),plain=(text,max)=>{let flat=text.replace(/[\p{Cc}\u2028\u2029]+/gu," ").replace(/\s+/gu," ").trim(),characters=Array.from(graphemes.segment(flat),(part)=>part.segment);return characters.length<=max?flat:`${characters.slice(0,max-1).join("")}…`},base642=(text)=>Buffer.from(text,"utf8").toString("base64"),titleSequence=(title)=>`${ESC}]0;${plain(title,120)}${BEL}`,statusSequence=(status)=>`${ESC}]7501;${RECORD}:${APP}:state=${status.state}${status.isAuth?":kind=auth":""}:title=${base642(plain(NAME2,60))}:msg=${base642(plain(status.msg,300))}${ST}`,progressSequence=(state)=>`${ESC}]9;4;${state==="error"?"2;100":state==="idle"?"0":"3"}${ST}`,PUSH_TITLE=`${ESC}[22;0t`,POP_TITLE=`${ESC}[23;0t`,closingSequences=(hasProgress)=>`${ESC}]7501;${RECORD}:state=clear${ST}${hasProgress?progressSequence("idle"):""}${ESC}]0;${BEL}${POP_TITLE}`,isInteractive=(output,env)=>output.isTTY===!0&&env.TERM!=="dumb"&&(env.CI===void 0||env.CI===""||env.CI==="false"||env.CI==="0"),showsProgress=(env)=>env.TERM_PROGRAM==="ghostty"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="",PROGRESS_REPEAT_MS=1e4;function terminalTab(output,env){if(!isInteractive(output,env))return{update:()=>{return},close:()=>{return}};let hasProgress=showsProgress(env),state=initialState,shown=null,isClosed=!1,repeat,write=(text)=>{try{output.write(text)}catch{}},show=(status)=>{let previous=shown;shown=status;let text=previous===null?PUSH_TITLE:"";if(previous?.title!==status.title)text+=titleSequence(status.title);if(previous?.state!==status.state||previous.isAuth!==status.isAuth||previous.msg!==status.msg)text+=statusSequence(status);if(hasProgress&&previous?.state!==status.state)text+=progressSequence(status.state),clearInterval(repeat),repeat=status.state==="idle"?void 0:setInterval(()=>write(progressSequence(status.state)),PROGRESS_REPEAT_MS),repeat?.unref();if(text.length>0)write(text)};return show(statusOf(state)),{update:(activity)=>{if(isClosed)return;state=next(state,activity),show(statusOf(state))},close:()=>{if(isClosed)return;isClosed=!0,clearInterval(repeat),write(closingSequences(hasProgress))}}}var USAGE=`DiffClarity companion ${COMPANION_VERSION}
|
|
121
125
|
|
|
122
126
|
Usage:
|
|
123
|
-
npx @diffclarity/companion connect Answer questions from DiffClarity with your installed agents,
|
|
124
|
-
|
|
125
|
-
|
|
127
|
+
npx @diffclarity/companion connect Answer questions from DiffClarity with your installed agents. In a terminal,
|
|
128
|
+
when it is allowed in several workspaces, it asks which to answer in this
|
|
129
|
+
time (all are ticked); otherwise it answers in every one
|
|
130
|
+
--workspace <name or id> Answer in this workspace (repeat for more; "personal" is your own) and ask nothing
|
|
131
|
+
--all-workspaces Answer in every workspace it is allowed in, and ask nothing
|
|
132
|
+
--add-workspace Allow it in more workspaces first: tick them in the browser
|
|
133
|
+
npx @diffclarity/companion workspaces List the workspaces it is allowed in, with their ids
|
|
126
134
|
npx @diffclarity/companion disconnect Forget this machine's access to DiffClarity, in every workspace
|
|
127
135
|
npx @diffclarity/companion mcp (used by the agents the companion starts) DiffClarity's tools over stdio
|
|
128
136
|
|
|
129
137
|
--origin <url> Which DiffClarity (default: ${COMPANION_DEFAULT_ORIGIN}); a local stage or another deployment
|
|
130
138
|
shows its own in the review's Assistant panel
|
|
131
|
-
--state <file> Where the companion keeps its access (default: one file per origin under ~/.config/diffclarity)`,option2=(args,name)=>{let index=args.indexOf(name);if(index===-1)return;let value=args[index+1];if(value===void 0)throw Error(`${name} needs a value`);return value},log=(line)=>console.error(line)
|
|
139
|
+
--state <file> Where the companion keeps its access (default: one file per origin under ~/.config/diffclarity)`,option2=(args,name)=>{let index=args.indexOf(name);if(index===-1)return;let value=args[index+1];if(value===void 0)throw Error(`${name} needs a value`);return value},options=(args,name)=>args.flatMap((arg,index)=>{if(arg!==name)return[];let value=args[index+1];if(value===void 0||value.startsWith("--"))throw Error(`${name} needs a value`);return[value]}),log=(line)=>console.error(line);class StoppedBeforeServing extends Error{}var proxyFor=(origin,state,workspace)=>({command:process.execPath,args:[fileURLToPath(import.meta.url),"mcp","--origin",origin,"--state",state,...workspace===void 0||workspace===""?[]:["--workspace",workspace]],env:{}});function chooserFor(origin,named,isAll,canAsk,isColour,onAsk){let ticked=[],hasAsked=!1;return{choose:async(saved,justAllowed)=>{if(named.length>0){let found=namedWorkspaces(saved,named,addWorkspaceCommand(origin));if(found.kind==="refused")throw Error(found.message);return{kind:"answer-in",workspaces:found.workspaces}}let every=saved.map((workspace)=>workspace.id);if(isAll||!canAsk||saved.length<2||saved.every((workspace)=>justAllowed.includes(workspace.id)))return{kind:"answer-in",workspaces:every};onAsk(),hasAsked=!0;let step=await pickInTerminal(process.stdin,process.stderr,pickerOf(saved,ticked.length===0?every:[...ticked,...justAllowed]),isColour);switch(step.kind){case"chosen":return{kind:"answer-in",workspaces:step.workspaces};case"allow-more":return ticked=step.ticked,{kind:"allow-more"};case"cancelled":throw new StoppedBeforeServing("Stopped before connecting; the companion isn't answering anywhere.")}},hasAsked:()=>hasAsked}}async function main(args){let[command,...rest]=args;switch(command){case"connect":{let origin=originFrom(option2(rest,"--origin")),state=option2(rest,"--state")??stateFileFor(origin),named=options(rest,"--workspace"),isAll=rest.includes("--all-workspaces");if(isAll&&named.length>0)throw Error("Use either --workspace or --all-workspaces, not both.");let tab=terminalTab(process.stderr,process.env);process.once("exit",tab.close);let leave=(signal)=>{tab.close(),process.kill(process.pid,signal)};process.once("SIGINT",leave),process.once("SIGTERM",leave);let agents=await detectAgents();if(agents.length===0)return log("Found none of Claude Code (claude), Codex (codex) or opencode 2 (opencode) on your PATH. Install one, sign in to it, and run this again."),1;log(`Found ${agents.map((agent)=>`${agentLabel(agent.kind)} ${agent.version}`).join(", ")}.`);let canAsk=isInteractive(process.stdin,process.env)&&isInteractive(process.stderr,process.env),{choose,hasAsked}=chooserFor(origin,named,isAll,canAsk,canAsk&&(process.env.NO_COLOR??"")==="",()=>tab.update({kind:"choosing"})),accesses=await signIn(origin,state,log,{addWorkspace:rest.includes("--add-workspace"),choose,onBrowser:()=>tab.update({kind:"signing-in"})}).catch((error)=>{if(error instanceof StoppedBeforeServing)return log(error.message),null;throw error});if(accesses===null)return 0;process.off("SIGINT",leave),process.off("SIGTERM",leave);let stop=new AbortController;process.on("SIGINT",()=>stop.abort()),process.on("SIGTERM",()=>stop.abort());let saved=await savedWorkspaces(state),workspaces=new Map(accesses.map((access,index)=>[`${index}`,saved.find((workspace)=>workspace.id===access.workspace)??{id:access.workspace??""}])),isSeveral=accesses.length>1,others=saved.filter((workspace)=>!accesses.some((access)=>access.workspace===workspace.id)),chosen=[...workspaces.values()];if(!hasAsked()&&chosen.every((workspace)=>workspace.named!==void 0))log(`Answering in ${workspaceList(chosen)}${others.length===0?"":`, not in ${workspaceList(others)}, this time`}.`);if(!canAsk&&named.length===0)log(`${saved.length>1?"To answer in fewer, name each with --workspace (`workspaces` lists them). ":""}To allow it in more workspaces, run \`${addWorkspaceCommand(origin)}\`.`);let live=new Set(workspaces.keys()),welcomed=new Set,ended=await Promise.allSettled(accesses.map((access,index)=>{let connection=`${index}`,workspaceOf=()=>workspaces.get(connection)??{id:""},logHere=(line)=>log(isSeveral?`[${workspaceTag(workspaceOf())}] ${line}`:line),onWelcome=(workspace)=>{workspaces.set(connection,{id:workspaceOf().id,named:{name:workspace.name,personal:workspace.personal}}),tab.update({kind:"named",connection,workspace:workspaceTag(workspaceOf())}),access.rememberName(workspace).catch((error)=>logHere(error instanceof Error?error.message:String(error)));let isFirst=!welcomed.has(connection);if(welcomed.add(connection),isSeveral&&isFirst&&[...live].every((other)=>welcomed.has(other)))log(`Answering in ${workspaceList([...live].map((other)=>workspaces.get(other)??{id:""}))}. Ask in a review's Assistant panel; keep this running, and press Ctrl+C to stop.`)},serving=serve(access,agents,proxyFor(origin,state,access.workspace),logHere,stop.signal,{onActivity:(activity)=>tab.update({kind:"connection",connection,activity}),onWelcome,isOneOfSeveral:isSeveral});return tab.update({kind:"named",connection,workspace:workspaceTag(workspaceOf())}),serving.catch((error)=>{if(live.delete(connection),isSeveral){if(logHere(`${error instanceof Error?error.message:String(error)} It no longer answers there.`),live.size>0)log(`Still answering in ${workspaceList([...live].map((other)=>workspaces.get(other)??{id:""}))}.`)}throw error}).finally(()=>tab.update({kind:"ended",connection}))})),failures=ended.flatMap((result)=>result.status==="rejected"?[result.reason instanceof Error?result.reason:Error(String(result.reason))]:[]),[first]=failures;if(first!==void 0&&failures.length===ended.length){if(!isSeveral)throw first;return 1}return log("Disconnected."),0}case"workspaces":{let origin=originFrom(option2(rest,"--origin")),state=option2(rest,"--state")??stateFileFor(origin);for(let line of workspaceLines(await savedWorkspaces(state),origin,addWorkspaceCommand(origin)))console.log(line);return 0}case"disconnect":{let origin=originFrom(option2(rest,"--origin")),state=option2(rest,"--state")??stateFileFor(origin);return await new StoredAccess(origin,state).forget(),log(`Forgot this machine's access to ${origin} in every workspace (${state}). Connecting again replaces its entry in Account → Connected agents; to end its access now, remove it there.`),0}case"mcp":{let origin=originFrom(option2(rest,"--origin")),state=option2(rest,"--state")??stateFileFor(origin),workspace=option2(rest,"--workspace")??(await savedWorkspaces(state))[0]?.id;if(workspace===void 0)throw new NeedsSignIn(`The companion isn't allowed in any workspace. Run \`${companionCommand("connect",origin)}\`.`);return await runProxy(origin,state,workspace),0}default:return log(USAGE),command===void 0||command==="--help"||command==="-h"?0:1}}main(process.argv.slice(2)).then((code)=>{if(code!==0)process.exit(code)},(error)=>{log(error instanceof Error?error.message:String(error)),process.exit(1)});
|