@cairnvibe/sdk 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cairn-widget.js +2 -2
- package/dist/index.js +58 -1
- package/dist/realtime-cli.js +86 -12
- package/package.json +1 -1
- package/src/index.tsx +68 -2
- package/src/realtime-cli.ts +84 -12
package/dist/cairn-widget.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";(()=>{var lt=Object.defineProperty;var dt=(r,e)=>{for(var t in e)lt(r,t,{get:e[t],enumerable:!0})};function Be(){if(typeof document>"u"||typeof window>"u")return[];let r=document.querySelectorAll("[data-ai]"),e=[];return r.forEach(t=>{let n=t.getBoundingClientRect();if(!(n.bottom>0&&n.top<window.innerHeight&&n.right>0&&n.left<window.innerWidth))return;let i=t.getAttribute("data-ai");i&&e.push(i)}),e}function ke(r){if(typeof document>"u")return null;let e=document.querySelector(`[data-ai="${Ie(r)}"]`);if(e)return e;let t=document.querySelector(`[aria-label="${Ie(r)}"]`);if(t)return t;let n=document.querySelector(`[role="${Ie(r)}"]`);if(n)return n;let s=document.querySelectorAll("button, a, [role='button'], input[type='submit'], input[type='button']"),i=je(r);for(let a of Array.from(s))if(je(a.textContent??"")===i)return a;for(let a of Array.from(s))if(je(a.textContent??"").includes(i))return a;return null}function we(r,e=4e3){r.scrollIntoView({behavior:"smooth",block:"center"}),r.classList.add("cairn-glow"),window.setTimeout(()=>r.classList.remove("cairn-glow"),e)}var Fe="cairn:misses",ut=200;function Te(r){try{let e=window.localStorage.getItem(Fe),t=e?JSON.parse(e):[];t.push({...r,at:new Date().toISOString()}),window.localStorage.setItem(Fe,JSON.stringify(t.slice(-ut)))}catch{}}function je(r){return r.trim().toLowerCase().replace(/\s+/g," ")}function Ie(r){return r.replace(/["\\]/g,"\\$&")}var p={};dt(p,{BRAND:()=>$t,DIRTY:()=>F,EMPTY_PATH:()=>mt,INVALID:()=>m,NEVER:()=>_r,OK:()=>T,ParseStatus:()=>w,Schema:()=>b,ZodAny:()=>z,ZodArray:()=>P,ZodBigInt:()=>W,ZodBoolean:()=>q,ZodBranded:()=>xe,ZodCatch:()=>se,ZodDate:()=>G,ZodDefault:()=>ne,ZodDiscriminatedUnion:()=>Ae,ZodEffects:()=>M,ZodEnum:()=>te,ZodError:()=>S,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Me,ZodIntersection:()=>X,ZodIssueCode:()=>c,ZodLazy:()=>K,ZodLiteral:()=>ee,ZodMap:()=>fe,ZodNaN:()=>ge,ZodNativeEnum:()=>re,ZodNever:()=>O,ZodNull:()=>Y,ZodNullable:()=>B,ZodNumber:()=>U,ZodObject:()=>E,ZodOptional:()=>A,ZodParsedType:()=>h,ZodPipeline:()=>_e,ZodPromise:()=>H,ZodReadonly:()=>ie,ZodRecord:()=>Ce,ZodSchema:()=>b,ZodSet:()=>me,ZodString:()=>Z,ZodSymbol:()=>he,ZodTransformer:()=>M,ZodTuple:()=>N,ZodType:()=>b,ZodUndefined:()=>J,ZodUnion:()=>Q,ZodUnknown:()=>$,ZodVoid:()=>pe,addIssueToContext:()=>l,any:()=>Wt,array:()=>Yt,bigint:()=>Zt,boolean:()=>tt,coerce:()=>xr,custom:()=>Xe,date:()=>zt,datetimeRegex:()=>Ye,defaultErrorMap:()=>I,discriminatedUnion:()=>er,effect:()=>hr,enum:()=>lr,function:()=>ar,getErrorMap:()=>le,getParsedType:()=>R,instanceof:()=>Vt,intersection:()=>tr,isAborted:()=>Se,isAsync:()=>de,isDirty:()=>Ee,isValid:()=>D,late:()=>Pt,lazy:()=>or,literal:()=>cr,makeIssue:()=>be,map:()=>sr,nan:()=>Dt,nativeEnum:()=>dr,never:()=>Gt,null:()=>Ut,nullable:()=>fr,number:()=>et,object:()=>Qt,objectUtil:()=>Le,oboolean:()=>br,onumber:()=>vr,optional:()=>pr,ostring:()=>yr,pipeline:()=>gr,preprocess:()=>mr,promise:()=>ur,quotelessJson:()=>ht,record:()=>nr,set:()=>ir,setErrorMap:()=>ft,strictObject:()=>Xt,string:()=>Ke,symbol:()=>Ht,transformer:()=>hr,tuple:()=>rr,undefined:()=>Ft,union:()=>Kt,unknown:()=>qt,util:()=>x,void:()=>Jt});var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let a of s)i[a]=a;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(let o of i)a[o]=s[o];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},r.find=(s,i)=>{for(let a of s)if(i(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var Le;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Le||(Le={}));var h=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}};var c=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ht=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),S=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,d=0;for(;d<a.path.length;){let u=a.path[d];d===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],d++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};S.create=r=>new S(r);var pt=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},I=pt;var Ue=I;function ft(r){Ue=r}function le(){return Ue}var be=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="",d=n.filter(u=>!!u).slice().reverse();for(let u of d)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}},mt=[];function l(r,e){let t=le(),n=be({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===I?void 0:I].filter(s=>!!s)});r.common.issues.push(n)}var w=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return m;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,a=await s.value;n.push({key:i,value:a})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return m;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}},m=Object.freeze({status:"aborted"}),F=r=>({status:"dirty",value:r}),T=r=>({status:"valid",value:r}),Se=r=>r.status==="aborted",Ee=r=>r.status==="dirty",D=r=>r.status==="valid",de=r=>typeof Promise<"u"&&r instanceof Promise;var f;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(f||(f={}));var C=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},We=(r,e)=>{if(D(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new S(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{let{message:d}=r;return a.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:s}}var b=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(de(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},s=this._parseSync({data:e,path:n.path,parent:n});return We(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return D(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>D(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(de(s)?s:Promise.resolve(s));return We(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let a=e(s),o=()=>i.addIssue({code:c.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new M({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return A.create(this,this._def)}nullable(){return B.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return P.create(this)}promise(){return H.create(this,this._def)}or(e){return Q.create([this,e],this._def)}and(e){return X.create(this,e,this._def)}transform(e){return new M({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ne({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new xe({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new se({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _e.create(this,e)}readonly(){return ie.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},gt=/^c[^\s-]{8,}$/i,yt=/^[0-9a-z]+$/,vt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xt=/^[a-z0-9_-]{21}$/i,_t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,wt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$e,St=/^(?:(?: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])$/,Et=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,At=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ct=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ot=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ge="((\\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])))",Rt=new RegExp(`^${Ge}$`);function Je(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Nt(r){return new RegExp(`^${Je(r)}$`)}function Ye(r){let e=`${Ge}T${Je(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Bt(r,e){return!!((e==="v4"||!e)&&St.test(r)||(e==="v6"||!e)&&At.test(r))}function jt(r,e){if(!_t.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function It(r,e){return!!((e==="v4"||!e)&&Et.test(r)||(e==="v6"||!e)&&Ct.test(r))}var Z=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:h.string,received:i.parsedType}),m}let n=new w,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?l(s,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&l(s,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")wt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"email",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")$e||($e=new RegExp(Tt,"u")),$e.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"emoji",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")bt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"uuid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")xt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"nanoid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")gt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cuid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")yt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cuid2",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")vt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"ulid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),l(s,{validation:"url",code:c.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"regex",code:c.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ye(i).test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Rt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Nt(i).test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?kt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"duration",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Bt(e.data,i.version)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"ip",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?jt(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"jwt",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?It(e.data,i.version)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cidr",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Mt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"base64",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Ot.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"base64url",code:c.invalid_string,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:c.invalid_string,...f.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...f.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...f.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...f.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...f.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...f.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...f.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...f.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...f.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...f.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...f.errToObj(t)})}nonempty(e){return this.min(1,f.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Z.create=r=>new Z({checks:[],typeName:g.ZodString,coerce:r?.coerce??!1,...v(r)});function Lt(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}var U=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:h.number,received:i.parsedType}),m}let n,s=new w;for(let i of this._def.checks)i.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Lt(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.not_finite,message:i.message}),s.dirty()):x.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:f.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:f.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:f.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};U.create=r=>new U({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,...v(r)});var W=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let n,s=new w;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):x.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return l(t,{code:c.invalid_type,expected:h.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:f.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};W.create=r=>new W({checks:[],typeName:g.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var q=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.boolean,received:n.parsedType}),m}return T(e.data)}};q.create=r=>new q({typeName:g.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var G=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:h.date,received:i.parsedType}),m}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_date}),m}let n=new w,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):x.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:f.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:f.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};G.create=r=>new G({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,...v(r)});var he=class extends b{_parse(e){if(this._getType(e)!==h.symbol){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.symbol,received:n.parsedType}),m}return T(e.data)}};he.create=r=>new he({typeName:g.ZodSymbol,...v(r)});var J=class extends b{_parse(e){if(this._getType(e)!==h.undefined){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.undefined,received:n.parsedType}),m}return T(e.data)}};J.create=r=>new J({typeName:g.ZodUndefined,...v(r)});var Y=class extends b{_parse(e){if(this._getType(e)!==h.null){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.null,received:n.parsedType}),m}return T(e.data)}};Y.create=r=>new Y({typeName:g.ZodNull,...v(r)});var z=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};z.create=r=>new z({typeName:g.ZodAny,...v(r)});var $=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};$.create=r=>new $({typeName:g.ZodUnknown,...v(r)});var O=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return l(t,{code:c.invalid_type,expected:h.never,received:t.parsedType}),m}};O.create=r=>new O({typeName:g.ZodNever,...v(r)});var pe=class extends b{_parse(e){if(this._getType(e)!==h.undefined){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.void,received:n.parsedType}),m}return T(e.data)}};pe.create=r=>new pe({typeName:g.ZodVoid,...v(r)});var P=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==h.array)return l(t,{code:c.invalid_type,expected:h.array,received:t.parsedType}),m;if(s.exactLength!==null){let a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(l(t,{code:a?c.too_big:c.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(l(t,{code:c.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(l(t,{code:c.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new C(t,a,t.path,o)))).then(a=>w.mergeArray(n,a));let i=[...t.data].map((a,o)=>s.type._parseSync(new C(t,a,t.path,o)));return w.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:f.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:f.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:f.toString(t)}})}nonempty(e){return this.min(1,e)}};P.create=(r,e)=>new P({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...v(e)});function ue(r){if(r instanceof E){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=A.create(ue(n))}return new E({...r._def,shape:()=>e})}else return r instanceof P?new P({...r._def,type:ue(r.element)}):r instanceof A?A.create(ue(r.unwrap())):r instanceof B?B.create(ue(r.unwrap())):r instanceof N?N.create(r.items.map(e=>ue(e))):r}var E=class r extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){let u=this._getOrReturnCtx(e);return l(u,{code:c.invalid_type,expected:h.object,received:u.parsedType}),m}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof O&&this._def.unknownKeys==="strip"))for(let u in s.data)a.includes(u)||o.push(u);let d=[];for(let u of a){let y=i[u],_=s.data[u];d.push({key:{status:"valid",value:u},value:y._parse(new C(s,_,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof O){let u=this._def.unknownKeys;if(u==="passthrough")for(let y of o)d.push({key:{status:"valid",value:y},value:{status:"valid",value:s.data[y]}});else if(u==="strict")o.length>0&&(l(s,{code:c.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let y of o){let _=s.data[y];d.push({key:{status:"valid",value:y},value:u._parse(new C(s,_,s.path,y)),alwaysSet:y in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let y of d){let _=await y.key,ye=await y.value;u.push({key:_,value:ye,alwaysSet:y.alwaysSet})}return u}).then(u=>w.mergeObjectSync(n,u)):w.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(e){return f.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:f.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return ue(this)}partial(e){let t={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof A;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Qe(x.objectKeys(this.shape))}};E.create=(r,e)=>new E({shape:()=>r,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,...v(e)});E.strictCreate=(r,e)=>new E({shape:()=>r,unknownKeys:"strict",catchall:O.create(),typeName:g.ZodObject,...v(e)});E.lazycreate=(r,e)=>new E({shape:r,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,...v(e)});var Q=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(o=>new S(o.ctx.common.issues));return l(t,{code:c.invalid_union,unionErrors:a}),m}if(t.common.async)return Promise.all(n.map(async i=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let d of n){let u={...t,common:{...t.common,issues:[]},parent:null},y=d._parseSync({data:t.data,path:t.path,parent:u});if(y.status==="valid")return y;y.status==="dirty"&&!i&&(i={result:y,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let o=a.map(d=>new S(d));return l(t,{code:c.invalid_union,unionErrors:o}),m}}get options(){return this._def.options}};Q.create=(r,e)=>new Q({options:r,typeName:g.ZodUnion,...v(e)});var L=r=>r instanceof K?L(r.schema):r instanceof M?L(r.innerType()):r instanceof ee?[r.value]:r instanceof te?r.options:r instanceof re?x.objectValues(r.enum):r instanceof ne?L(r._def.innerType):r instanceof J?[void 0]:r instanceof Y?[null]:r instanceof A?[void 0,...L(r.unwrap())]:r instanceof B?[null,...L(r.unwrap())]:r instanceof xe||r instanceof ie?L(r.unwrap()):r instanceof se?L(r._def.innerType):[],Ae=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return l(t,{code:c.invalid_type,expected:h.object,received:t.parsedType}),m;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let a=L(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(n)})}};function Pe(r,e){let t=R(r),n=R(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&n===h.object){let s=x.objectKeys(e),i=x.objectKeys(r).filter(o=>s.indexOf(o)!==-1),a={...r,...e};for(let o of i){let d=Pe(r[o],e[o]);if(!d.valid)return{valid:!1};a[o]=d.data}return{valid:!0,data:a}}else if(t===h.array&&n===h.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let a=r[i],o=e[i],d=Pe(a,o);if(!d.valid)return{valid:!1};s.push(d.data)}return{valid:!0,data:s}}else return t===h.date&&n===h.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var X=class extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(Se(i)||Se(a))return m;let o=Pe(i.value,a.value);return o.valid?((Ee(i)||Ee(a))&&t.dirty(),{status:t.value,value:o.data}):(l(n,{code:c.invalid_intersection_types}),m)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};X.create=(r,e,t)=>new X({left:r,right:e,typeName:g.ZodIntersection,...v(t)});var N=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.array)return l(n,{code:c.invalid_type,expected:h.array,received:n.parsedType}),m;if(n.data.length<this._def.items.length)return l(n,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&n.data.length>this._def.items.length&&(l(n,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((a,o)=>{let d=this._def.items[o]||this._def.rest;return d?d._parse(new C(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>w.mergeArray(t,a)):w.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};N.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N({items:r,typeName:g.ZodTuple,rest:null,...v(e)})};var Ce=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.object)return l(n,{code:c.invalid_type,expected:h.object,received:n.parsedType}),m;let s=[],i=this._def.keyType,a=this._def.valueType;for(let o in n.data)s.push({key:i._parse(new C(n,o,n.path,o)),value:a._parse(new C(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?w.mergeObjectAsync(t,s):w.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:g.ZodRecord,...v(n)}):new r({keyType:Z.create(),valueType:e,typeName:g.ZodRecord,...v(t)})}},fe=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.map)return l(n,{code:c.invalid_type,expected:h.map,received:n.parsedType}),m;let s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,d],u)=>({key:s._parse(new C(n,o,n.path,[u,"key"])),value:i._parse(new C(n,d,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let d of a){let u=await d.key,y=await d.value;if(u.status==="aborted"||y.status==="aborted")return m;(u.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(u.value,y.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let d of a){let u=d.key,y=d.value;if(u.status==="aborted"||y.status==="aborted")return m;(u.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(u.value,y.value)}return{status:t.value,value:o}}}};fe.create=(r,e,t)=>new fe({valueType:e,keyType:r,typeName:g.ZodMap,...v(t)});var me=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.set)return l(n,{code:c.invalid_type,expected:h.set,received:n.parsedType}),m;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(l(n,{code:c.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(l(n,{code:c.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function a(d){let u=new Set;for(let y of d){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),u.add(y.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((d,u)=>i._parse(new C(n,d,n.path,u)));return n.common.async?Promise.all(o).then(d=>a(d)):a(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:f.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:f.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};me.create=(r,e)=>new me({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,...v(e)});var Me=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return l(t,{code:c.invalid_type,expected:h.function,received:t.parsedType}),m;function n(o,d){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),I].filter(u=>!!u),issueData:{code:c.invalid_arguments,argumentsError:d}})}function s(o,d){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),I].filter(u=>!!u),issueData:{code:c.invalid_return_type,returnTypeError:d}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof H){let o=this;return T(async function(...d){let u=new S([]),y=await o._def.args.parseAsync(d,i).catch(ve=>{throw u.addIssue(n(d,ve)),u}),_=await Reflect.apply(a,this,y);return await o._def.returns._def.type.parseAsync(_,i).catch(ve=>{throw u.addIssue(s(_,ve)),u})})}else{let o=this;return T(function(...d){let u=o._def.args.safeParse(d,i);if(!u.success)throw new S([n(d,u.error)]);let y=Reflect.apply(a,this,u.data),_=o._def.returns.safeParse(y,i);if(!_.success)throw new S([s(y,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:N.create(e).rest($.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||N.create([]).rest($.create()),returns:t||$.create(),typeName:g.ZodFunction,...v(n)})}},K=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};K.create=(r,e)=>new K({getter:r,typeName:g.ZodLazy,...v(e)});var ee=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};ee.create=(r,e)=>new ee({value:r,typeName:g.ZodLiteral,...v(e)});function Qe(r,e){return new te({values:r,typeName:g.ZodEnum,...v(e)})}var te=class r extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return l(t,{expected:x.joinValues(n),received:t.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return l(t,{received:t.data,code:c.invalid_enum_value,options:n}),m}return T(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};te.create=Qe;var re=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==h.string&&n.parsedType!==h.number){let s=x.objectValues(t);return l(n,{expected:x.joinValues(s),received:n.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(t);return l(n,{received:n.data,code:c.invalid_enum_value,options:s}),m}return T(e.data)}get enum(){return this._def.values}};re.create=(r,e)=>new re({values:r,typeName:g.ZodNativeEnum,...v(e)});var H=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return l(t,{code:c.invalid_type,expected:h.promise,received:t.parsedType}),m;let n=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return T(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};H.create=(r,e)=>new H({type:r,typeName:g.ZodPromise,...v(e)});var M=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{l(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return m;let d=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return d.status==="aborted"?m:d.status==="dirty"?F(d.value):t.value==="dirty"?F(d.value):d});{if(t.value==="aborted")return m;let o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?m:o.status==="dirty"?F(o.value):t.value==="dirty"?F(o.value):o}}if(s.type==="refinement"){let a=o=>{let d=s.refinement(o,i);if(n.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!D(a))return m;let o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>D(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:t.value,value:o})):m);x.assertNever(s)}};M.create=(r,e,t)=>new M({schema:r,typeName:g.ZodEffects,effect:e,...v(t)});M.createWithPreprocess=(r,e,t)=>new M({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,...v(t)});var A=class extends b{_parse(e){return this._getType(e)===h.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A.create=(r,e)=>new A({innerType:r,typeName:g.ZodOptional,...v(e)});var B=class extends b{_parse(e){return this._getType(e)===h.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};B.create=(r,e)=>new B({innerType:r,typeName:g.ZodNullable,...v(e)});var ne=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===h.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ne.create=(r,e)=>new ne({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var se=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return de(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new S(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new S(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};se.create=(r,e)=>new se({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var ge=class extends b{_parse(e){if(this._getType(e)!==h.nan){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.nan,received:n.parsedType}),m}return{status:"valid",value:e.data}}};ge.create=r=>new ge({typeName:g.ZodNaN,...v(r)});var $t=Symbol("zod_brand"),xe=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},_e=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?m:i.status==="dirty"?(t.dirty(),F(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?m:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},ie=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=s=>(D(s)&&(s.value=Object.freeze(s.value)),s);return de(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};ie.create=(r,e)=>new ie({innerType:r,typeName:g.ZodReadonly,...v(e)});function qe(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xe(r,e={},t){return r?z.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(a=>{if(!a){let o=qe(e,n),d=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:d})}});if(!i){let a=qe(e,n),o=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:o})}}):z.create()}var Pt={object:E.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var Vt=(r,e={message:`Input not instance of ${r.name}`})=>Xe(t=>t instanceof r,e),Ke=Z.create,et=U.create,Dt=ge.create,Zt=W.create,tt=q.create,zt=G.create,Ht=he.create,Ft=J.create,Ut=Y.create,Wt=z.create,qt=$.create,Gt=O.create,Jt=pe.create,Yt=P.create,Qt=E.create,Xt=E.strictCreate,Kt=Q.create,er=Ae.create,tr=X.create,rr=N.create,nr=Ce.create,sr=fe.create,ir=me.create,ar=Me.create,or=K.create,cr=ee.create,lr=te.create,dr=re.create,ur=H.create,hr=M.create,pr=A.create,fr=B.create,mr=M.createWithPreprocess,gr=_e.create,yr=()=>Ke().optional(),vr=()=>et().optional(),br=()=>tt().optional(),xr={string:r=>Z.create({...r,coerce:!0}),number:r=>U.create({...r,coerce:!0}),boolean:r=>q.create({...r,coerce:!0}),bigint:r=>W.create({...r,coerce:!0}),date:r=>G.create({...r,coerce:!0})};var _r=m;var kr=p.object({id:p.string(),label:p.string(),selector:p.string(),fallbacks:p.array(p.string()),does:p.string(),confidence:p.number().min(0).max(1),evidence:p.array(p.string())}),wr=p.object({id:p.string(),route:p.string(),file:p.string(),title:p.string(),purpose:p.string(),whenToUse:p.string(),confidence:p.number().min(0).max(1),elements:p.array(kr)}),Tr=p.object({candidates:p.array(p.string()),chose:p.string(),reason:p.string(),confidence:p.number().min(0).max(1)}),xn=p.object({version:p.literal("1"),commit:p.string(),generatedAt:p.string(),pages:p.array(wr),dead:p.array(p.string()),conflicts:p.array(Tr)}),ae=()=>p.preprocess(r=>r===null?void 0:r,p.string().optional()),rt=p.discriminatedUnion("verb",[p.object({verb:p.literal("explain"),text:p.string().min(1)}).strict(),p.object({verb:p.literal("highlight"),target:p.string().min(1),text:ae()}).strict(),p.object({verb:p.literal("open"),target:p.string().min(1),text:ae()}).strict(),p.object({verb:p.literal("navigate"),route:p.string().min(1),text:ae()}).strict(),p.object({verb:p.literal("do"),action:p.string().min(1),target:ae(),text:ae()}).strict(),p.object({verb:p.literal("tour"),steps:p.array(p.object({text:p.string().min(1),target:ae(),route:ae()}).strict()).min(2).max(6)}).strict()]),Sr=p.object({role:p.enum(["user","assistant"]),text:p.string()}),_n=p.object({route:p.string(),question:p.string().min(1),visible:p.array(p.string()),history:p.array(Sr).optional()});var Er="I'm not sure \u2014 I couldn't understand that response. Try rephrasing your question.";function nt(r,e,t){let n=rt.safeParse(r);if(!n.success){t.onExplain(Er);return}Ar(n.data,e,t)}function Ar(r,e,t){switch(r.verb){case"explain":t.onExplain(r.text);return;case"highlight":case"open":{let n=ke(r.target);if(!n){(t.onMiss??Te)({attempted:r.target,route:e}),t.onExplain(r.text??"I know what you need, but I can't find it on this page right now.");return}we(n),r.text&&t.onExplain(r.text);return}case"navigate":t.onNavigate?.(r.route),r.text&&t.onExplain(r.text);return;case"do":{if(!(t.registeredActions??[]).includes(r.action)){t.onExplain("That action isn't available here.");return}t.onDo?.(r.action,r.target),r.text&&t.onExplain(r.text);return}case"tour":t.onTour?t.onTour(r.steps):t.onExplain(r.steps.map(n=>n.text).join(" "));return}}var Cr={idle:"",asking:"Thinking\u2026",recording:"Listening \u2014 transcribing live\u2026","rt-connecting":"Connecting\u2026","rt-listening":"Listening\u2026","rt-thinking":"Thinking\u2026","rt-speaking":"Speaking\u2026"},Mr=8,Or=`
|
|
1
|
+
"use strict";(()=>{var lt=Object.defineProperty;var dt=(r,e)=>{for(var t in e)lt(r,t,{get:e[t],enumerable:!0})};function Be(){if(typeof document>"u"||typeof window>"u")return[];let r=document.querySelectorAll("[data-ai]"),e=[];return r.forEach(t=>{let n=t.getBoundingClientRect();if(!(n.bottom>0&&n.top<window.innerHeight&&n.right>0&&n.left<window.innerWidth))return;let i=t.getAttribute("data-ai");i&&e.push(i)}),e}function ke(r){if(typeof document>"u")return null;let e=document.querySelector(`[data-ai="${Ie(r)}"]`);if(e)return e;let t=document.querySelector(`[aria-label="${Ie(r)}"]`);if(t)return t;let n=document.querySelector(`[role="${Ie(r)}"]`);if(n)return n;let s=document.querySelectorAll("button, a, [role='button'], input[type='submit'], input[type='button']"),i=je(r);for(let a of Array.from(s))if(je(a.textContent??"")===i)return a;for(let a of Array.from(s))if(je(a.textContent??"").includes(i))return a;return null}function we(r,e=4e3){r.scrollIntoView({behavior:"smooth",block:"center"}),r.classList.add("cairn-glow"),window.setTimeout(()=>r.classList.remove("cairn-glow"),e)}var Fe="cairn:misses",ut=200;function Te(r){try{let e=window.localStorage.getItem(Fe),t=e?JSON.parse(e):[];t.push({...r,at:new Date().toISOString()}),window.localStorage.setItem(Fe,JSON.stringify(t.slice(-ut)))}catch{}}function je(r){return r.trim().toLowerCase().replace(/\s+/g," ")}function Ie(r){return r.replace(/["\\]/g,"\\$&")}var p={};dt(p,{BRAND:()=>$t,DIRTY:()=>F,EMPTY_PATH:()=>mt,INVALID:()=>m,NEVER:()=>_r,OK:()=>T,ParseStatus:()=>w,Schema:()=>b,ZodAny:()=>z,ZodArray:()=>P,ZodBigInt:()=>W,ZodBoolean:()=>q,ZodBranded:()=>xe,ZodCatch:()=>se,ZodDate:()=>G,ZodDefault:()=>ne,ZodDiscriminatedUnion:()=>Ae,ZodEffects:()=>M,ZodEnum:()=>te,ZodError:()=>S,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Me,ZodIntersection:()=>X,ZodIssueCode:()=>c,ZodLazy:()=>K,ZodLiteral:()=>ee,ZodMap:()=>fe,ZodNaN:()=>ge,ZodNativeEnum:()=>re,ZodNever:()=>O,ZodNull:()=>Y,ZodNullable:()=>B,ZodNumber:()=>U,ZodObject:()=>E,ZodOptional:()=>A,ZodParsedType:()=>h,ZodPipeline:()=>_e,ZodPromise:()=>H,ZodReadonly:()=>ie,ZodRecord:()=>Ce,ZodSchema:()=>b,ZodSet:()=>me,ZodString:()=>Z,ZodSymbol:()=>he,ZodTransformer:()=>M,ZodTuple:()=>N,ZodType:()=>b,ZodUndefined:()=>J,ZodUnion:()=>Q,ZodUnknown:()=>$,ZodVoid:()=>pe,addIssueToContext:()=>l,any:()=>Wt,array:()=>Yt,bigint:()=>Zt,boolean:()=>tt,coerce:()=>xr,custom:()=>Xe,date:()=>zt,datetimeRegex:()=>Ye,defaultErrorMap:()=>I,discriminatedUnion:()=>er,effect:()=>hr,enum:()=>lr,function:()=>ar,getErrorMap:()=>le,getParsedType:()=>R,instanceof:()=>Vt,intersection:()=>tr,isAborted:()=>Se,isAsync:()=>de,isDirty:()=>Ee,isValid:()=>D,late:()=>Pt,lazy:()=>or,literal:()=>cr,makeIssue:()=>be,map:()=>sr,nan:()=>Dt,nativeEnum:()=>dr,never:()=>Gt,null:()=>Ut,nullable:()=>fr,number:()=>et,object:()=>Qt,objectUtil:()=>Le,oboolean:()=>br,onumber:()=>vr,optional:()=>pr,ostring:()=>yr,pipeline:()=>gr,preprocess:()=>mr,promise:()=>ur,quotelessJson:()=>ht,record:()=>nr,set:()=>ir,setErrorMap:()=>ft,strictObject:()=>Xt,string:()=>Ke,symbol:()=>Ht,transformer:()=>hr,tuple:()=>rr,undefined:()=>Ft,union:()=>Kt,unknown:()=>qt,util:()=>x,void:()=>Jt});var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let a of s)i[a]=a;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(let o of i)a[o]=s[o];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},r.find=(s,i)=>{for(let a of s)if(i(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var Le;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Le||(Le={}));var h=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}};var c=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ht=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),S=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,d=0;for(;d<a.path.length;){let u=a.path[d];d===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],d++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};S.create=r=>new S(r);var pt=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},I=pt;var Ue=I;function ft(r){Ue=r}function le(){return Ue}var be=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="",d=n.filter(u=>!!u).slice().reverse();for(let u of d)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}},mt=[];function l(r,e){let t=le(),n=be({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===I?void 0:I].filter(s=>!!s)});r.common.issues.push(n)}var w=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return m;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,a=await s.value;n.push({key:i,value:a})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return m;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}},m=Object.freeze({status:"aborted"}),F=r=>({status:"dirty",value:r}),T=r=>({status:"valid",value:r}),Se=r=>r.status==="aborted",Ee=r=>r.status==="dirty",D=r=>r.status==="valid",de=r=>typeof Promise<"u"&&r instanceof Promise;var f;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(f||(f={}));var C=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},We=(r,e)=>{if(D(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new S(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{let{message:d}=r;return a.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:s}}var b=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(de(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},s=this._parseSync({data:e,path:n.path,parent:n});return We(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return D(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>D(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(de(s)?s:Promise.resolve(s));return We(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let a=e(s),o=()=>i.addIssue({code:c.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new M({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return A.create(this,this._def)}nullable(){return B.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return P.create(this)}promise(){return H.create(this,this._def)}or(e){return Q.create([this,e],this._def)}and(e){return X.create(this,e,this._def)}transform(e){return new M({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ne({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new xe({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new se({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _e.create(this,e)}readonly(){return ie.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},gt=/^c[^\s-]{8,}$/i,yt=/^[0-9a-z]+$/,vt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xt=/^[a-z0-9_-]{21}$/i,_t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,wt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$e,St=/^(?:(?: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])$/,Et=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,At=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ct=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ot=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ge="((\\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])))",Rt=new RegExp(`^${Ge}$`);function Je(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Nt(r){return new RegExp(`^${Je(r)}$`)}function Ye(r){let e=`${Ge}T${Je(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Bt(r,e){return!!((e==="v4"||!e)&&St.test(r)||(e==="v6"||!e)&&At.test(r))}function jt(r,e){if(!_t.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function It(r,e){return!!((e==="v4"||!e)&&Et.test(r)||(e==="v6"||!e)&&Ct.test(r))}var Z=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:h.string,received:i.parsedType}),m}let n=new w,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?l(s,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&l(s,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")wt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"email",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")$e||($e=new RegExp(Tt,"u")),$e.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"emoji",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")bt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"uuid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")xt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"nanoid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")gt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cuid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")yt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cuid2",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")vt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"ulid",code:c.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),l(s,{validation:"url",code:c.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"regex",code:c.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ye(i).test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Rt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Nt(i).test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?kt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"duration",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Bt(e.data,i.version)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"ip",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?jt(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"jwt",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?It(e.data,i.version)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cidr",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Mt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"base64",code:c.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Ot.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"base64url",code:c.invalid_string,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:c.invalid_string,...f.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...f.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...f.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...f.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...f.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...f.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...f.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...f.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...f.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...f.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...f.errToObj(t)})}nonempty(e){return this.min(1,f.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Z.create=r=>new Z({checks:[],typeName:g.ZodString,coerce:r?.coerce??!1,...v(r)});function Lt(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}var U=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:h.number,received:i.parsedType}),m}let n,s=new w;for(let i of this._def.checks)i.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Lt(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.not_finite,message:i.message}),s.dirty()):x.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:f.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:f.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:f.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};U.create=r=>new U({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,...v(r)});var W=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let n,s=new w;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):x.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return l(t,{code:c.invalid_type,expected:h.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:f.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};W.create=r=>new W({checks:[],typeName:g.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var q=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.boolean,received:n.parsedType}),m}return T(e.data)}};q.create=r=>new q({typeName:g.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var G=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:h.date,received:i.parsedType}),m}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_date}),m}let n=new w,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):x.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:f.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:f.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};G.create=r=>new G({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,...v(r)});var he=class extends b{_parse(e){if(this._getType(e)!==h.symbol){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.symbol,received:n.parsedType}),m}return T(e.data)}};he.create=r=>new he({typeName:g.ZodSymbol,...v(r)});var J=class extends b{_parse(e){if(this._getType(e)!==h.undefined){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.undefined,received:n.parsedType}),m}return T(e.data)}};J.create=r=>new J({typeName:g.ZodUndefined,...v(r)});var Y=class extends b{_parse(e){if(this._getType(e)!==h.null){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.null,received:n.parsedType}),m}return T(e.data)}};Y.create=r=>new Y({typeName:g.ZodNull,...v(r)});var z=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};z.create=r=>new z({typeName:g.ZodAny,...v(r)});var $=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};$.create=r=>new $({typeName:g.ZodUnknown,...v(r)});var O=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return l(t,{code:c.invalid_type,expected:h.never,received:t.parsedType}),m}};O.create=r=>new O({typeName:g.ZodNever,...v(r)});var pe=class extends b{_parse(e){if(this._getType(e)!==h.undefined){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.void,received:n.parsedType}),m}return T(e.data)}};pe.create=r=>new pe({typeName:g.ZodVoid,...v(r)});var P=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==h.array)return l(t,{code:c.invalid_type,expected:h.array,received:t.parsedType}),m;if(s.exactLength!==null){let a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(l(t,{code:a?c.too_big:c.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(l(t,{code:c.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(l(t,{code:c.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new C(t,a,t.path,o)))).then(a=>w.mergeArray(n,a));let i=[...t.data].map((a,o)=>s.type._parseSync(new C(t,a,t.path,o)));return w.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:f.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:f.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:f.toString(t)}})}nonempty(e){return this.min(1,e)}};P.create=(r,e)=>new P({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...v(e)});function ue(r){if(r instanceof E){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=A.create(ue(n))}return new E({...r._def,shape:()=>e})}else return r instanceof P?new P({...r._def,type:ue(r.element)}):r instanceof A?A.create(ue(r.unwrap())):r instanceof B?B.create(ue(r.unwrap())):r instanceof N?N.create(r.items.map(e=>ue(e))):r}var E=class r extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){let u=this._getOrReturnCtx(e);return l(u,{code:c.invalid_type,expected:h.object,received:u.parsedType}),m}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof O&&this._def.unknownKeys==="strip"))for(let u in s.data)a.includes(u)||o.push(u);let d=[];for(let u of a){let y=i[u],_=s.data[u];d.push({key:{status:"valid",value:u},value:y._parse(new C(s,_,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof O){let u=this._def.unknownKeys;if(u==="passthrough")for(let y of o)d.push({key:{status:"valid",value:y},value:{status:"valid",value:s.data[y]}});else if(u==="strict")o.length>0&&(l(s,{code:c.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let y of o){let _=s.data[y];d.push({key:{status:"valid",value:y},value:u._parse(new C(s,_,s.path,y)),alwaysSet:y in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let y of d){let _=await y.key,ye=await y.value;u.push({key:_,value:ye,alwaysSet:y.alwaysSet})}return u}).then(u=>w.mergeObjectSync(n,u)):w.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(e){return f.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:f.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return ue(this)}partial(e){let t={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof A;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Qe(x.objectKeys(this.shape))}};E.create=(r,e)=>new E({shape:()=>r,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,...v(e)});E.strictCreate=(r,e)=>new E({shape:()=>r,unknownKeys:"strict",catchall:O.create(),typeName:g.ZodObject,...v(e)});E.lazycreate=(r,e)=>new E({shape:r,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,...v(e)});var Q=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(o=>new S(o.ctx.common.issues));return l(t,{code:c.invalid_union,unionErrors:a}),m}if(t.common.async)return Promise.all(n.map(async i=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let d of n){let u={...t,common:{...t.common,issues:[]},parent:null},y=d._parseSync({data:t.data,path:t.path,parent:u});if(y.status==="valid")return y;y.status==="dirty"&&!i&&(i={result:y,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let o=a.map(d=>new S(d));return l(t,{code:c.invalid_union,unionErrors:o}),m}}get options(){return this._def.options}};Q.create=(r,e)=>new Q({options:r,typeName:g.ZodUnion,...v(e)});var L=r=>r instanceof K?L(r.schema):r instanceof M?L(r.innerType()):r instanceof ee?[r.value]:r instanceof te?r.options:r instanceof re?x.objectValues(r.enum):r instanceof ne?L(r._def.innerType):r instanceof J?[void 0]:r instanceof Y?[null]:r instanceof A?[void 0,...L(r.unwrap())]:r instanceof B?[null,...L(r.unwrap())]:r instanceof xe||r instanceof ie?L(r.unwrap()):r instanceof se?L(r._def.innerType):[],Ae=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return l(t,{code:c.invalid_type,expected:h.object,received:t.parsedType}),m;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let a=L(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(n)})}};function Pe(r,e){let t=R(r),n=R(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&n===h.object){let s=x.objectKeys(e),i=x.objectKeys(r).filter(o=>s.indexOf(o)!==-1),a={...r,...e};for(let o of i){let d=Pe(r[o],e[o]);if(!d.valid)return{valid:!1};a[o]=d.data}return{valid:!0,data:a}}else if(t===h.array&&n===h.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let a=r[i],o=e[i],d=Pe(a,o);if(!d.valid)return{valid:!1};s.push(d.data)}return{valid:!0,data:s}}else return t===h.date&&n===h.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var X=class extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(Se(i)||Se(a))return m;let o=Pe(i.value,a.value);return o.valid?((Ee(i)||Ee(a))&&t.dirty(),{status:t.value,value:o.data}):(l(n,{code:c.invalid_intersection_types}),m)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};X.create=(r,e,t)=>new X({left:r,right:e,typeName:g.ZodIntersection,...v(t)});var N=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.array)return l(n,{code:c.invalid_type,expected:h.array,received:n.parsedType}),m;if(n.data.length<this._def.items.length)return l(n,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&n.data.length>this._def.items.length&&(l(n,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((a,o)=>{let d=this._def.items[o]||this._def.rest;return d?d._parse(new C(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>w.mergeArray(t,a)):w.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};N.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N({items:r,typeName:g.ZodTuple,rest:null,...v(e)})};var Ce=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.object)return l(n,{code:c.invalid_type,expected:h.object,received:n.parsedType}),m;let s=[],i=this._def.keyType,a=this._def.valueType;for(let o in n.data)s.push({key:i._parse(new C(n,o,n.path,o)),value:a._parse(new C(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?w.mergeObjectAsync(t,s):w.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:g.ZodRecord,...v(n)}):new r({keyType:Z.create(),valueType:e,typeName:g.ZodRecord,...v(t)})}},fe=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.map)return l(n,{code:c.invalid_type,expected:h.map,received:n.parsedType}),m;let s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,d],u)=>({key:s._parse(new C(n,o,n.path,[u,"key"])),value:i._parse(new C(n,d,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let d of a){let u=await d.key,y=await d.value;if(u.status==="aborted"||y.status==="aborted")return m;(u.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(u.value,y.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let d of a){let u=d.key,y=d.value;if(u.status==="aborted"||y.status==="aborted")return m;(u.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(u.value,y.value)}return{status:t.value,value:o}}}};fe.create=(r,e,t)=>new fe({valueType:e,keyType:r,typeName:g.ZodMap,...v(t)});var me=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.set)return l(n,{code:c.invalid_type,expected:h.set,received:n.parsedType}),m;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(l(n,{code:c.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(l(n,{code:c.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function a(d){let u=new Set;for(let y of d){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),u.add(y.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((d,u)=>i._parse(new C(n,d,n.path,u)));return n.common.async?Promise.all(o).then(d=>a(d)):a(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:f.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:f.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};me.create=(r,e)=>new me({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,...v(e)});var Me=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return l(t,{code:c.invalid_type,expected:h.function,received:t.parsedType}),m;function n(o,d){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),I].filter(u=>!!u),issueData:{code:c.invalid_arguments,argumentsError:d}})}function s(o,d){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),I].filter(u=>!!u),issueData:{code:c.invalid_return_type,returnTypeError:d}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof H){let o=this;return T(async function(...d){let u=new S([]),y=await o._def.args.parseAsync(d,i).catch(ve=>{throw u.addIssue(n(d,ve)),u}),_=await Reflect.apply(a,this,y);return await o._def.returns._def.type.parseAsync(_,i).catch(ve=>{throw u.addIssue(s(_,ve)),u})})}else{let o=this;return T(function(...d){let u=o._def.args.safeParse(d,i);if(!u.success)throw new S([n(d,u.error)]);let y=Reflect.apply(a,this,u.data),_=o._def.returns.safeParse(y,i);if(!_.success)throw new S([s(y,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:N.create(e).rest($.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||N.create([]).rest($.create()),returns:t||$.create(),typeName:g.ZodFunction,...v(n)})}},K=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};K.create=(r,e)=>new K({getter:r,typeName:g.ZodLazy,...v(e)});var ee=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};ee.create=(r,e)=>new ee({value:r,typeName:g.ZodLiteral,...v(e)});function Qe(r,e){return new te({values:r,typeName:g.ZodEnum,...v(e)})}var te=class r extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return l(t,{expected:x.joinValues(n),received:t.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return l(t,{received:t.data,code:c.invalid_enum_value,options:n}),m}return T(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};te.create=Qe;var re=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==h.string&&n.parsedType!==h.number){let s=x.objectValues(t);return l(n,{expected:x.joinValues(s),received:n.parsedType,code:c.invalid_type}),m}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(t);return l(n,{received:n.data,code:c.invalid_enum_value,options:s}),m}return T(e.data)}get enum(){return this._def.values}};re.create=(r,e)=>new re({values:r,typeName:g.ZodNativeEnum,...v(e)});var H=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return l(t,{code:c.invalid_type,expected:h.promise,received:t.parsedType}),m;let n=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return T(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};H.create=(r,e)=>new H({type:r,typeName:g.ZodPromise,...v(e)});var M=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{l(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return m;let d=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return d.status==="aborted"?m:d.status==="dirty"?F(d.value):t.value==="dirty"?F(d.value):d});{if(t.value==="aborted")return m;let o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?m:o.status==="dirty"?F(o.value):t.value==="dirty"?F(o.value):o}}if(s.type==="refinement"){let a=o=>{let d=s.refinement(o,i);if(n.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!D(a))return m;let o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>D(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:t.value,value:o})):m);x.assertNever(s)}};M.create=(r,e,t)=>new M({schema:r,typeName:g.ZodEffects,effect:e,...v(t)});M.createWithPreprocess=(r,e,t)=>new M({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,...v(t)});var A=class extends b{_parse(e){return this._getType(e)===h.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A.create=(r,e)=>new A({innerType:r,typeName:g.ZodOptional,...v(e)});var B=class extends b{_parse(e){return this._getType(e)===h.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};B.create=(r,e)=>new B({innerType:r,typeName:g.ZodNullable,...v(e)});var ne=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===h.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ne.create=(r,e)=>new ne({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var se=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return de(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new S(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new S(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};se.create=(r,e)=>new se({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var ge=class extends b{_parse(e){if(this._getType(e)!==h.nan){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:h.nan,received:n.parsedType}),m}return{status:"valid",value:e.data}}};ge.create=r=>new ge({typeName:g.ZodNaN,...v(r)});var $t=Symbol("zod_brand"),xe=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},_e=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?m:i.status==="dirty"?(t.dirty(),F(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?m:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},ie=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=s=>(D(s)&&(s.value=Object.freeze(s.value)),s);return de(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};ie.create=(r,e)=>new ie({innerType:r,typeName:g.ZodReadonly,...v(e)});function qe(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xe(r,e={},t){return r?z.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(a=>{if(!a){let o=qe(e,n),d=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:d})}});if(!i){let a=qe(e,n),o=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:o})}}):z.create()}var Pt={object:E.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var Vt=(r,e={message:`Input not instance of ${r.name}`})=>Xe(t=>t instanceof r,e),Ke=Z.create,et=U.create,Dt=ge.create,Zt=W.create,tt=q.create,zt=G.create,Ht=he.create,Ft=J.create,Ut=Y.create,Wt=z.create,qt=$.create,Gt=O.create,Jt=pe.create,Yt=P.create,Qt=E.create,Xt=E.strictCreate,Kt=Q.create,er=Ae.create,tr=X.create,rr=N.create,nr=Ce.create,sr=fe.create,ir=me.create,ar=Me.create,or=K.create,cr=ee.create,lr=te.create,dr=re.create,ur=H.create,hr=M.create,pr=A.create,fr=B.create,mr=M.createWithPreprocess,gr=_e.create,yr=()=>Ke().optional(),vr=()=>et().optional(),br=()=>tt().optional(),xr={string:r=>Z.create({...r,coerce:!0}),number:r=>U.create({...r,coerce:!0}),boolean:r=>q.create({...r,coerce:!0}),bigint:r=>W.create({...r,coerce:!0}),date:r=>G.create({...r,coerce:!0})};var _r=m;var kr=p.object({method:p.enum(["POST","PUT","PATCH","DELETE"]),url:p.string()}),wr=p.object({id:p.string(),label:p.string(),selector:p.string(),fallbacks:p.array(p.string()),does:p.string(),confidence:p.number().min(0).max(1),evidence:p.array(p.string()),apiCall:kr.nullable().optional()}),Tr=p.object({id:p.string(),route:p.string(),file:p.string(),title:p.string(),purpose:p.string(),whenToUse:p.string(),confidence:p.number().min(0).max(1),elements:p.array(wr)}),Sr=p.object({candidates:p.array(p.string()),chose:p.string(),reason:p.string(),confidence:p.number().min(0).max(1)}),_n=p.object({version:p.literal("1"),commit:p.string(),generatedAt:p.string(),pages:p.array(Tr),dead:p.array(p.string()),conflicts:p.array(Sr)}),ae=()=>p.preprocess(r=>r===null?void 0:r,p.string().optional()),rt=p.discriminatedUnion("verb",[p.object({verb:p.literal("explain"),text:p.string().min(1)}).strict(),p.object({verb:p.literal("highlight"),target:p.string().min(1),text:ae()}).strict(),p.object({verb:p.literal("open"),target:p.string().min(1),text:ae()}).strict(),p.object({verb:p.literal("navigate"),route:p.string().min(1),text:ae()}).strict(),p.object({verb:p.literal("do"),action:p.string().min(1),target:ae(),text:ae()}).strict(),p.object({verb:p.literal("tour"),steps:p.array(p.object({text:p.string().min(1),target:ae(),route:ae()}).strict()).min(2).max(6)}).strict()]),Er=p.object({role:p.enum(["user","assistant"]),text:p.string()}),kn=p.object({route:p.string(),question:p.string().min(1),visible:p.array(p.string()),history:p.array(Er).optional()});var Ar="I'm not sure \u2014 I couldn't understand that response. Try rephrasing your question.";function nt(r,e,t){let n=rt.safeParse(r);if(!n.success){t.onExplain(Ar);return}Cr(n.data,e,t)}function Cr(r,e,t){switch(r.verb){case"explain":t.onExplain(r.text);return;case"highlight":case"open":{let n=ke(r.target);if(!n){(t.onMiss??Te)({attempted:r.target,route:e}),t.onExplain(r.text??"I know what you need, but I can't find it on this page right now.");return}we(n),r.text&&t.onExplain(r.text);return}case"navigate":t.onNavigate?.(r.route),r.text&&t.onExplain(r.text);return;case"do":{if(!(t.registeredActions??[]).includes(r.action)){t.onExplain("That action isn't available here.");return}t.onDo?.(r.action,r.target),r.text&&t.onExplain(r.text);return}case"tour":t.onTour?t.onTour(r.steps):t.onExplain(r.steps.map(n=>n.text).join(" "));return}}var Mr={idle:"",asking:"Thinking\u2026",recording:"Listening \u2014 transcribing live\u2026","rt-connecting":"Connecting\u2026","rt-listening":"Listening\u2026","rt-thinking":"Thinking\u2026","rt-speaking":"Speaking\u2026"},Or=8,Rr=`
|
|
2
2
|
:host {
|
|
3
3
|
all: initial;
|
|
4
4
|
font: 13.5px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", sans-serif;
|
|
@@ -225,4 +225,4 @@
|
|
|
225
225
|
.cairn-rt-dot-rt-thinking { background: #f59e0b; }
|
|
226
226
|
.cairn-rt-label { flex: 1; font-size: 12.5px; color: #33384a; }
|
|
227
227
|
.cairn-rt-controls { display: flex; gap: 6px; }
|
|
228
|
-
`,st='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',Oe='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><line x1="12" x2="12" y1="18" y2="22"/></svg>',Rr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"/><line x1="12" y1="19" x2="12" y2="22"/></svg>',Nr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>',Br='<svg class="cairn-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',jr='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',it='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="7" y="12.5" width="6" height="2.6" rx="0.5" fill="currentColor"/><rect x="4.5" y="8.5" width="11" height="2.6" rx="0.5" fill="currentColor" opacity="0.75"/><rect x="8.2" y="4.5" width="3.6" height="2.6" rx="0.5" fill="currentColor" opacity="0.5"/></svg>',Ir='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"/></svg>',Lr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.83 16.57a1 1 0 0 0 1.21-.3l.36-.47A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A17.87 17.87 0 0 1 9.3 17.6"/><path d="M4.27 5.34C3.5 6.44 4 8 4 8a17.9 17.9 0 0 0 2.14 6.6"/><path d="M2 2v0"/><line x1="2" y1="2" x2="22" y2="22"/></svg>',at='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>',$r='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>',Ve=class extends HTMLElement{shadow;fab;panel;stackEl;userBubbleEl;agentBubbleEl;chipEl;agentTextEl;thinkingEl;formEl;inputEl;sendBtn;micBtn=null;phoneBtn=null;rtBar;rtDot;rtLabel;rtMicBtn;rtSpeakerBtn;rtEndBtn;isOpen=!1;status="idle";recording=!1;touringActive=!1;caption="";answer=null;lastQuestion=null;tourGeneration=0;mediaRecorder=null;audioChunks=[];transcribeInFlight=!1;activeAudio=null;history=[];rtSocket=null;rtCleanup=null;rtMicMuted=!1;rtSpeakerMuted=!1;rtStarting=!1;rtPlaybackCtx=null;rtPlaybackGain=null;rtNextPlayTime=0;rtScheduledSources=[];rtThinkingWatchdog=null;rtAudioDoneArriving=!0;rtTourAudioDoneResolve=null;static get observedAttributes(){return["persona"]}connectedCallback(){this.shadow||(this.shadow=this.attachShadow({mode:"open"}),this.buildDom())}attributeChangedCallback(e){e==="persona"&&this.panel&&this.panel.setAttribute("aria-label",`${this.persona} help panel`)}get endpoint(){return this.getAttribute("endpoint")??"/api/copilot"}get speakEndpoint(){return this.getAttribute("speak-endpoint")}get transcribeEndpoint(){return this.getAttribute("transcribe-endpoint")}get reportMissesEndpoint(){return this.getAttribute("report-misses-endpoint")}get realtimeUrl(){return this.getAttribute("realtime-url")}get persona(){return this.getAttribute("persona")??"Cairn"}get registeredActions(){return(this.getAttribute("registered-actions")??"").split(",").map(e=>e.trim()).filter(Boolean)}get realtimeActive(){return this.status.startsWith("rt-")}get busy(){return this.status==="asking"||this.status==="rt-thinking"||this.touringActive}micSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"}buildDom(){let e=document.createElement("style");e.textContent=Or,this.shadow.appendChild(e),this.fab=document.createElement("button"),this.fab.className="cairn-fab",this.fab.innerHTML=it,this.fab.setAttribute("aria-label",`Open ${this.persona} help`),this.fab.addEventListener("click",()=>this.toggleOpen()),this.shadow.appendChild(this.fab),this.panel=document.createElement("div"),this.panel.className="cairn-panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",`${this.persona} help panel`),this.stackEl=document.createElement("div"),this.stackEl.className="cairn-stack",this.stackEl.style.display="none",this.userBubbleEl=document.createElement("div"),this.userBubbleEl.className="cairn-bubble cairn-bubble-user",this.userBubbleEl.style.display="none",this.stackEl.appendChild(this.userBubbleEl),this.agentBubbleEl=document.createElement("div"),this.agentBubbleEl.className="cairn-bubble cairn-bubble-agent",this.agentBubbleEl.style.display="none",this.chipEl=document.createElement("span"),this.chipEl.className="cairn-chip",this.chipEl.style.display="none",this.agentBubbleEl.appendChild(this.chipEl),this.agentTextEl=document.createElement("span"),this.agentTextEl.className="cairn-bubble-text",this.agentBubbleEl.appendChild(this.agentTextEl),this.thinkingEl=document.createElement("span"),this.thinkingEl.className="cairn-thinking",this.thinkingEl.setAttribute("aria-label","Thinking"),this.thinkingEl.style.display="none",this.thinkingEl.innerHTML='<span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span>',this.agentBubbleEl.appendChild(this.thinkingEl),this.stackEl.appendChild(this.agentBubbleEl),this.panel.appendChild(this.stackEl),this.rtBar=document.createElement("div"),this.rtBar.className="cairn-rt-bar",this.rtBar.style.display="none",this.rtDot=document.createElement("span"),this.rtDot.className="cairn-rt-dot",this.rtBar.appendChild(this.rtDot),this.rtLabel=document.createElement("span"),this.rtLabel.className="cairn-rt-label",this.rtBar.appendChild(this.rtLabel);let t=document.createElement("div");t.className="cairn-rt-controls",this.rtMicBtn=document.createElement("button"),this.rtMicBtn.type="button",this.rtMicBtn.className="cairn-icon-btn",this.rtMicBtn.innerHTML=Oe,this.rtMicBtn.setAttribute("aria-label","Mute microphone"),this.rtMicBtn.addEventListener("click",()=>this.toggleRtMic()),t.appendChild(this.rtMicBtn),this.rtSpeakerBtn=document.createElement("button"),this.rtSpeakerBtn.type="button",this.rtSpeakerBtn.className="cairn-icon-btn",this.rtSpeakerBtn.innerHTML=at,this.rtSpeakerBtn.setAttribute("aria-label","Mute speaker"),this.rtSpeakerBtn.addEventListener("click",()=>this.toggleRtSpeaker()),t.appendChild(this.rtSpeakerBtn),this.rtEndBtn=document.createElement("button"),this.rtEndBtn.type="button",this.rtEndBtn.className="cairn-icon-btn cairn-icon-btn-end",this.rtEndBtn.innerHTML=Lr,this.rtEndBtn.setAttribute("aria-label","End conversation"),this.rtEndBtn.addEventListener("click",()=>this.endRealtime()),t.appendChild(this.rtEndBtn),this.rtBar.appendChild(t),this.panel.appendChild(this.rtBar),this.formEl=document.createElement("form");let n=document.createElement("div");n.className="cairn-input-row",this.inputEl=document.createElement("input"),this.inputEl.placeholder="What do you need help with?",this.inputEl.setAttribute("aria-label",`Ask ${this.persona} a question`),this.inputEl.addEventListener("input",()=>this.updateBusyState()),n.appendChild(this.inputEl),this.realtimeUrl&&this.micSupported()&&(this.phoneBtn=document.createElement("button"),this.phoneBtn.type="button",this.phoneBtn.className="cairn-icon-btn",this.phoneBtn.innerHTML=Ir,this.phoneBtn.setAttribute("aria-label","Start realtime conversation"),this.phoneBtn.addEventListener("click",()=>void this.startRealtime()),n.appendChild(this.phoneBtn)),this.transcribeEndpoint&&this.micSupported()&&(this.micBtn=document.createElement("button"),this.micBtn.type="button",this.micBtn.className="cairn-icon-btn",this.micBtn.innerHTML=Oe,this.micBtn.setAttribute("aria-label","Ask by voice"),this.micBtn.addEventListener("click",()=>this.recording?this.stopRecording():void this.startRecording()),n.appendChild(this.micBtn)),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="cairn-send",this.sendBtn.innerHTML=st,this.sendBtn.setAttribute("aria-label","Send"),n.appendChild(this.sendBtn),this.formEl.appendChild(n),this.formEl.addEventListener("submit",s=>{s.preventDefault();let i=this.inputEl.value.trim();i&&this.ask(i)}),this.panel.appendChild(this.formEl),this.shadow.appendChild(this.panel),this.render()}toggleOpen(){this.isOpen=!this.isOpen,this.panel.classList.toggle("cairn-open",this.isOpen),this.fab.innerHTML=this.isOpen?jr:it,this.fab.setAttribute("aria-label",this.isOpen?`Close ${this.persona} help`:`Open ${this.persona} help`),this.isOpen&&!this.realtimeActive&&this.inputEl.focus()}render(){let e=this.realtimeActive;if(this.fab.classList.toggle("cairn-fab-speaking",this.status==="rt-speaking"),this.rtBar.style.display=e?"flex":"none",this.formEl.style.display=e?"none":"block",e){this.rtDot.className=`cairn-rt-dot cairn-rt-dot-${this.status}`,this.rtLabel.textContent=Cr[this.status];let i=this.status==="rt-speaking";this.rtMicBtn.className=i?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtSpeakerBtn.className=i?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtMicBtn.innerHTML=this.rtMicMuted?Rr:Oe,this.rtMicBtn.setAttribute("aria-label",this.rtMicMuted?"Unmute microphone":"Mute microphone"),this.rtSpeakerBtn.innerHTML=this.rtSpeakerMuted?$r:at,this.rtSpeakerBtn.setAttribute("aria-label",this.rtSpeakerMuted?"Unmute speaker":"Mute speaker")}let t=this.touringActive?this.caption:"",n=!this.touringActive&&(this.recording||e)?this.caption:this.lastQuestion??"",s=!!this.answer||this.busy;this.stackEl.style.display=n||s?"flex":"none",this.userBubbleEl.style.display=n?"block":"none",this.userBubbleEl.textContent=n,this.agentBubbleEl.style.display=s?"flex":"none",this.chipEl.style.display=t?"inline-block":"none",this.chipEl.textContent=t,this.answer?(this.agentTextEl.style.display="inline",this.renderCaptionWords(this.agentTextEl,this.answer),this.thinkingEl.style.display="none"):(this.agentTextEl.style.display="none",this.agentTextEl.textContent="",this.thinkingEl.style.display=this.busy?"inline-flex":"none"),this.phoneBtn&&(this.phoneBtn.disabled=this.busy||this.recording),this.updateBusyState()}setStatus(e){this.status=e,this.render()}setCaption(e){this.caption=e,this.render()}updateBusyState(){this.inputEl.disabled=this.recording||this.touringActive,this.sendBtn.disabled=this.busy||this.recording||!this.inputEl.value.trim(),this.sendBtn.innerHTML=this.busy?Br:st,this.micBtn&&(this.micBtn.disabled=this.touringActive)}setAnswer(e){this.answer=e,this.render()}renderCaptionWords(e,t){e.innerHTML="";let n=t.split(" ");n.forEach((s,i)=>{let a=document.createElement("span");a.className="cairn-word",a.style.animationDelay=`${Math.min(i*55,2800)}ms`,a.textContent=i<n.length-1?s+" ":s,e.appendChild(a)})}reportMiss(e){Te(e);let t=this.reportMissesEndpoint;t&&fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async ask(e){this.setStatus("asking"),this.setAnswer(null),this.lastQuestion=e,this.inputEl.value="",this.render();try{let n=await(await fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:location.pathname,question:e,visible:Be(),history:this.history})})).json().catch(()=>null);this.handleVerb(n),this.history=[...this.history,{role:"user",text:e},{role:"assistant",text:Pr(n)}].slice(-Mr)}catch{this.setAnswer("Something went wrong reaching the help service \u2014 try again in a moment.")}finally{this.setStatus("idle")}}handleVerb(e){nt(e,location.pathname,{onExplain:t=>{this.setAnswer(t),this.realtimeActive||this.speak(t)},onNavigate:t=>{location.assign(t)},onMiss:t=>this.reportMiss(t),onDo:(t,n)=>{this.dispatchEvent(new CustomEvent("cairn-do",{detail:{action:t,target:n},bubbles:!0,composed:!0}))},onTour:t=>void this.runTour(t),registeredActions:this.registeredActions})}async runTour(e){let t=++this.tourGeneration,n=this.realtimeActive;this.touringActive=!0,n&&this.setStatus("rt-speaking"),this.setAnswer(null);let s=location.pathname;try{for(let i=0;i<e.length;i++){if(this.tourGeneration!==t)return;let a=e[i];if(this.setCaption(`Step ${i+1} of ${e.length}`),this.setAnswer(a.text),a.route&&a.route!==s){location.assign(a.route);return}if(a.target){let o=ke(a.target);o?we(o):this.reportMiss({attempted:a.target,route:s})}if(n&&this.rtSocket?.readyState===WebSocket.OPEN?await this.speakOverRealtime(a.text):this.speakEndpoint?await this.speakAndWait(a.text):await new Promise(o=>setTimeout(o,Math.max(1200,a.text.length*45))),this.tourGeneration!==t)return}if(this.tourGeneration!==t)return;this.setCaption(""),n&&this.realtimeActive&&this.setStatus("rt-listening")}finally{this.tourGeneration===t&&(this.touringActive=!1,this.render())}}playResponseAudio(e){this.activeAudio&&(this.activeAudio.pause(),this.activeAudio.currentTime=0);let t=URL.createObjectURL(e),n=new Audio(t);return this.activeAudio=n,new Promise(s=>{let i=()=>{URL.revokeObjectURL(t),this.activeAudio===n&&(this.activeAudio=null),s()};n.onended=i,n.play().catch(i)})}async speak(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;this.playResponseAudio(await t.blob())}catch{}}async speakAndWait(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;await this.playResponseAudio(await t.blob())}catch{}}speakOverRealtime(e){return new Promise(t=>{let n=this.rtSocket;if(!n||n.readyState!==WebSocket.OPEN){t();return}this.rtAudioDoneArriving=!1;let s=!1,i=()=>{s||(s=!0,this.rtTourAudioDoneResolve=null,t())};this.rtTourAudioDoneResolve=i,setTimeout(()=>{s||console.warn("[cairn] tour step audio confirmation timed out \u2014 continuing"),i()},15e3),n.send(JSON.stringify({type:"speak",text:e}))})}async startRecording(){if(!(!this.transcribeEndpoint||!this.micSupported()||this.realtimeActive))try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e);this.audioChunks=[],this.setCaption(""),t.ondataavailable=n=>{n.data.size!==0&&(this.audioChunks.push(n.data),this.transcribeSoFar(t.mimeType||"audio/webm",!0))},t.onstop=()=>void this.transcribeSoFar(t.mimeType||"audio/webm",!1),this.mediaRecorder=t,t.start(2e3),this.recording=!0,this.micBtn&&(this.micBtn.innerHTML=Nr,this.micBtn.classList.add("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Stop recording")),this.render()}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site.")}}stopRecording(){let e=this.mediaRecorder?.stream;this.mediaRecorder?.stop(),e?.getTracks().forEach(t=>t.stop()),this.recording=!1,this.micBtn&&(this.micBtn.innerHTML=Oe,this.micBtn.classList.remove("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Ask by voice")),this.render()}async transcribeSoFar(e,t){if(this.transcribeEndpoint&&!(t&&this.transcribeInFlight)){this.transcribeInFlight=!0;try{let n=new Blob(this.audioChunks,{type:e}),i=await(await fetch(this.transcribeEndpoint,{method:"POST",headers:{"content-type":e},body:n})).json().catch(()=>null);i?.text?(this.inputEl.value=i.text,this.setCaption(i.text),this.updateBusyState()):t||this.setAnswer("Couldn't make that out \u2014 try typing instead.")}catch{t||this.setAnswer("Couldn't reach the transcription service.")}finally{this.transcribeInFlight=!1}}}async startRealtime(){if(!(!this.realtimeUrl||!this.micSupported()||this.realtimeActive||this.rtStarting)){this.rtStarting=!0,this.setAnswer(null),this.setCaption(""),this.setStatus("rt-connecting");try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new WebSocket(this.realtimeUrl);t.binaryType="arraybuffer",this.rtSocket=t;let n=new AudioContext,s=n.createGain();s.gain.value=this.rtSpeakerMuted?0:1,s.connect(n.destination),this.rtPlaybackCtx=n,this.rtPlaybackGain=s,this.rtNextPlayTime=0,this.rtScheduledSources=[],this.rtAudioDoneArriving=!0;let i=new AudioContext,a=i.createMediaStreamSource(e),o=i.createScriptProcessor(4096,1,1),d=i.createGain();d.gain.value=0;let u=()=>{if(this.rtAudioDoneArriving&&!(this.rtScheduledSources.length>0)){if(this.touringActive){this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null;return}this.setStatus("rt-listening"),this.setCaption("")}},y=()=>{this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null)},_=()=>{y(),this.rtThinkingWatchdog=setTimeout(()=>{this.rtThinkingWatchdog=null,console.warn("[cairn] realtime turn timed out waiting on the server \u2014 resuming listening"),this.rtAudioDoneArriving=!0,this.setStatus("rt-listening"),this.setCaption("")},2e4)},ye=()=>{for(let j of this.rtScheduledSources)try{j.stop()}catch{}this.rtScheduledSources=[],this.rtNextPlayTime=this.rtPlaybackCtx?.currentTime??0},ve=()=>{y(),ye(),this.rtAudioDoneArriving=!0,t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"barge_in"})),this.setStatus("rt-listening"),this.setCaption("")};o.onaudioprocess=j=>{if(t.readyState!==WebSocket.OPEN||this.rtMicMuted)return;if(this.status==="rt-speaking"&&!this.touringActive){Dr(j.inputBuffer.getChannelData(0))>Vr&&ve();return}if(this.status!=="rt-listening")return;let k=zr(Zr(j.inputBuffer.getChannelData(0),i.sampleRate));t.send(k)},a.connect(o),o.connect(d),d.connect(i.destination),this.rtCleanup=()=>{o.disconnect(),a.disconnect(),e.getTracks().forEach(j=>j.stop()),i.close(),ye(),n.close(),this.rtPlaybackCtx=null,this.rtPlaybackGain=null},t.onopen=()=>{t.send(JSON.stringify({type:"context",route:location.pathname,visible:Be()})),this.setStatus("rt-listening"),this.rtStarting=!1},t.onmessage=j=>{if(typeof j.data!="string")return;let k=JSON.parse(j.data);if(k.type==="interim")this.setCaption(k.text);else if(k.type==="final")this.setCaption(k.text),this.setStatus("rt-thinking"),_();else if(k.type==="verb")y(),this.handleVerb(k.verb);else if(k.type==="speaking_start")y(),this.rtAudioDoneArriving=!1,this.setStatus("rt-speaking");else if(k.type==="audio_chunk"){let oe=this.rtPlaybackCtx,De=this.rtPlaybackGain;if(!oe||!De)return;oe.resume().catch(()=>{});let Ze=Uint8Array.from(atob(k.audio),V=>V.charCodeAt(0)),Re=Ze.length/2,ze=new Float32Array(Re),ot=new DataView(Ze.buffer);for(let V=0;V<Re;V++)ze[V]=ot.getInt16(V*2,!0)/32768;let ct=typeof k.sampleRate=="number"?k.sampleRate:24e3,Ne=oe.createBuffer(1,Re,ct);Ne.copyToChannel(ze,0);let ce=oe.createBufferSource();ce.buffer=Ne,ce.connect(De);let He=Math.max(oe.currentTime,this.rtNextPlayTime);ce.start(He),this.rtNextPlayTime=He+Ne.duration,this.rtScheduledSources.push(ce),ce.onended=()=>{this.rtScheduledSources=this.rtScheduledSources.filter(V=>V!==ce),u()}}else k.type==="speaking_end"||k.type==="turn_complete"?(y(),this.rtAudioDoneArriving=!0,u()):k.type==="error"&&(y(),this.setAnswer(k.message??"Something went wrong."),this.touringActive||(this.setStatus("rt-listening"),this.setCaption("")))},t.onerror=()=>{this.setAnswer("Couldn't connect to the realtime voice service."),this.endRealtime()},t.onclose=()=>{this.status!=="idle"&&this.endRealtime()}}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site."),this.setStatus("idle"),this.rtStarting=!1}}}endRealtime(){this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null),this.rtStarting=!1,this.activeAudio?.pause(),this.activeAudio=null,this.rtSocket?.close(),this.rtSocket=null,this.rtCleanup?.(),this.rtCleanup=null,this.rtMicMuted=!1,this.rtSpeakerMuted=!1,this.setCaption(""),this.setStatus("idle"),this.tourGeneration++,this.touringActive=!1,this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null,this.render()}toggleRtMic(){this.rtMicMuted=!this.rtMicMuted,this.render()}toggleRtSpeaker(){this.rtSpeakerMuted=!this.rtSpeakerMuted,this.rtPlaybackGain&&(this.rtPlaybackGain.gain.value=this.rtSpeakerMuted?0:1),this.render()}};function Pr(r){if(!r||typeof r!="object")return"(no response)";let e=r;if(typeof e.text=="string"&&e.text)return e.text;switch(e.verb){case"highlight":case"open":return`(highlighted ${String(e.target)})`;case"navigate":return`(navigated to ${String(e.route)})`;case"do":return`(ran ${String(e.action)}${e.target?` on ${String(e.target)}`:""})`;case"tour":return Array.isArray(e.steps)?e.steps.map(t=>t.text??"").join(" "):"(tour)";default:return"(no response)"}}var Vr=.02;function Dr(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t]*r[t];return Math.sqrt(e/r.length)}function Zr(r,e){if(e===16e3)return r;let n=e/16e3,s=Math.round(r.length/n),i=new Float32Array(s),a=0,o=0;for(;a<s;){let d=Math.round((a+1)*n),u=0,y=0;for(let _=o;_<d&&_<r.length;_++)u+=r[_],y++;i[a]=y>0?u/y:0,a++,o=d}return i}function zr(r){let e=new ArrayBuffer(r.length*2),t=new DataView(e);for(let n=0;n<r.length;n++){let s=Math.max(-1,Math.min(1,r[n]));t.setInt16(n*2,s<0?s*32768:s*32767,!0)}return e}typeof customElements<"u"&&!customElements.get("cairn-widget")&&customElements.define("cairn-widget",Ve);})();
|
|
228
|
+
`,st='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',Oe='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><line x1="12" x2="12" y1="18" y2="22"/></svg>',Nr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"/><line x1="12" y1="19" x2="12" y2="22"/></svg>',Br='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>',jr='<svg class="cairn-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Ir='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',it='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="7" y="12.5" width="6" height="2.6" rx="0.5" fill="currentColor"/><rect x="4.5" y="8.5" width="11" height="2.6" rx="0.5" fill="currentColor" opacity="0.75"/><rect x="8.2" y="4.5" width="3.6" height="2.6" rx="0.5" fill="currentColor" opacity="0.5"/></svg>',Lr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"/></svg>',$r='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.83 16.57a1 1 0 0 0 1.21-.3l.36-.47A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A17.87 17.87 0 0 1 9.3 17.6"/><path d="M4.27 5.34C3.5 6.44 4 8 4 8a17.9 17.9 0 0 0 2.14 6.6"/><path d="M2 2v0"/><line x1="2" y1="2" x2="22" y2="22"/></svg>',at='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>',Pr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>',Ve=class extends HTMLElement{shadow;fab;panel;stackEl;userBubbleEl;agentBubbleEl;chipEl;agentTextEl;thinkingEl;formEl;inputEl;sendBtn;micBtn=null;phoneBtn=null;rtBar;rtDot;rtLabel;rtMicBtn;rtSpeakerBtn;rtEndBtn;isOpen=!1;status="idle";recording=!1;touringActive=!1;caption="";answer=null;lastQuestion=null;tourGeneration=0;mediaRecorder=null;audioChunks=[];transcribeInFlight=!1;activeAudio=null;history=[];rtSocket=null;rtCleanup=null;rtMicMuted=!1;rtSpeakerMuted=!1;rtStarting=!1;rtPlaybackCtx=null;rtPlaybackGain=null;rtNextPlayTime=0;rtScheduledSources=[];rtThinkingWatchdog=null;rtAudioDoneArriving=!0;rtTourAudioDoneResolve=null;static get observedAttributes(){return["persona"]}connectedCallback(){this.shadow||(this.shadow=this.attachShadow({mode:"open"}),this.buildDom())}attributeChangedCallback(e){e==="persona"&&this.panel&&this.panel.setAttribute("aria-label",`${this.persona} help panel`)}get endpoint(){return this.getAttribute("endpoint")??"/api/copilot"}get speakEndpoint(){return this.getAttribute("speak-endpoint")}get transcribeEndpoint(){return this.getAttribute("transcribe-endpoint")}get reportMissesEndpoint(){return this.getAttribute("report-misses-endpoint")}get realtimeUrl(){return this.getAttribute("realtime-url")}get persona(){return this.getAttribute("persona")??"Cairn"}get registeredActions(){return(this.getAttribute("registered-actions")??"").split(",").map(e=>e.trim()).filter(Boolean)}get realtimeActive(){return this.status.startsWith("rt-")}get busy(){return this.status==="asking"||this.status==="rt-thinking"||this.touringActive}micSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"}buildDom(){let e=document.createElement("style");e.textContent=Rr,this.shadow.appendChild(e),this.fab=document.createElement("button"),this.fab.className="cairn-fab",this.fab.innerHTML=it,this.fab.setAttribute("aria-label",`Open ${this.persona} help`),this.fab.addEventListener("click",()=>this.toggleOpen()),this.shadow.appendChild(this.fab),this.panel=document.createElement("div"),this.panel.className="cairn-panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",`${this.persona} help panel`),this.stackEl=document.createElement("div"),this.stackEl.className="cairn-stack",this.stackEl.style.display="none",this.userBubbleEl=document.createElement("div"),this.userBubbleEl.className="cairn-bubble cairn-bubble-user",this.userBubbleEl.style.display="none",this.stackEl.appendChild(this.userBubbleEl),this.agentBubbleEl=document.createElement("div"),this.agentBubbleEl.className="cairn-bubble cairn-bubble-agent",this.agentBubbleEl.style.display="none",this.chipEl=document.createElement("span"),this.chipEl.className="cairn-chip",this.chipEl.style.display="none",this.agentBubbleEl.appendChild(this.chipEl),this.agentTextEl=document.createElement("span"),this.agentTextEl.className="cairn-bubble-text",this.agentBubbleEl.appendChild(this.agentTextEl),this.thinkingEl=document.createElement("span"),this.thinkingEl.className="cairn-thinking",this.thinkingEl.setAttribute("aria-label","Thinking"),this.thinkingEl.style.display="none",this.thinkingEl.innerHTML='<span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span>',this.agentBubbleEl.appendChild(this.thinkingEl),this.stackEl.appendChild(this.agentBubbleEl),this.panel.appendChild(this.stackEl),this.rtBar=document.createElement("div"),this.rtBar.className="cairn-rt-bar",this.rtBar.style.display="none",this.rtDot=document.createElement("span"),this.rtDot.className="cairn-rt-dot",this.rtBar.appendChild(this.rtDot),this.rtLabel=document.createElement("span"),this.rtLabel.className="cairn-rt-label",this.rtBar.appendChild(this.rtLabel);let t=document.createElement("div");t.className="cairn-rt-controls",this.rtMicBtn=document.createElement("button"),this.rtMicBtn.type="button",this.rtMicBtn.className="cairn-icon-btn",this.rtMicBtn.innerHTML=Oe,this.rtMicBtn.setAttribute("aria-label","Mute microphone"),this.rtMicBtn.addEventListener("click",()=>this.toggleRtMic()),t.appendChild(this.rtMicBtn),this.rtSpeakerBtn=document.createElement("button"),this.rtSpeakerBtn.type="button",this.rtSpeakerBtn.className="cairn-icon-btn",this.rtSpeakerBtn.innerHTML=at,this.rtSpeakerBtn.setAttribute("aria-label","Mute speaker"),this.rtSpeakerBtn.addEventListener("click",()=>this.toggleRtSpeaker()),t.appendChild(this.rtSpeakerBtn),this.rtEndBtn=document.createElement("button"),this.rtEndBtn.type="button",this.rtEndBtn.className="cairn-icon-btn cairn-icon-btn-end",this.rtEndBtn.innerHTML=$r,this.rtEndBtn.setAttribute("aria-label","End conversation"),this.rtEndBtn.addEventListener("click",()=>this.endRealtime()),t.appendChild(this.rtEndBtn),this.rtBar.appendChild(t),this.panel.appendChild(this.rtBar),this.formEl=document.createElement("form");let n=document.createElement("div");n.className="cairn-input-row",this.inputEl=document.createElement("input"),this.inputEl.placeholder="What do you need help with?",this.inputEl.setAttribute("aria-label",`Ask ${this.persona} a question`),this.inputEl.addEventListener("input",()=>this.updateBusyState()),n.appendChild(this.inputEl),this.realtimeUrl&&this.micSupported()&&(this.phoneBtn=document.createElement("button"),this.phoneBtn.type="button",this.phoneBtn.className="cairn-icon-btn",this.phoneBtn.innerHTML=Lr,this.phoneBtn.setAttribute("aria-label","Start realtime conversation"),this.phoneBtn.addEventListener("click",()=>void this.startRealtime()),n.appendChild(this.phoneBtn)),this.transcribeEndpoint&&this.micSupported()&&(this.micBtn=document.createElement("button"),this.micBtn.type="button",this.micBtn.className="cairn-icon-btn",this.micBtn.innerHTML=Oe,this.micBtn.setAttribute("aria-label","Ask by voice"),this.micBtn.addEventListener("click",()=>this.recording?this.stopRecording():void this.startRecording()),n.appendChild(this.micBtn)),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="cairn-send",this.sendBtn.innerHTML=st,this.sendBtn.setAttribute("aria-label","Send"),n.appendChild(this.sendBtn),this.formEl.appendChild(n),this.formEl.addEventListener("submit",s=>{s.preventDefault();let i=this.inputEl.value.trim();i&&this.ask(i)}),this.panel.appendChild(this.formEl),this.shadow.appendChild(this.panel),this.render()}toggleOpen(){this.isOpen=!this.isOpen,this.panel.classList.toggle("cairn-open",this.isOpen),this.fab.innerHTML=this.isOpen?Ir:it,this.fab.setAttribute("aria-label",this.isOpen?`Close ${this.persona} help`:`Open ${this.persona} help`),this.isOpen&&!this.realtimeActive&&this.inputEl.focus()}render(){let e=this.realtimeActive;if(this.fab.classList.toggle("cairn-fab-speaking",this.status==="rt-speaking"),this.rtBar.style.display=e?"flex":"none",this.formEl.style.display=e?"none":"block",e){this.rtDot.className=`cairn-rt-dot cairn-rt-dot-${this.status}`,this.rtLabel.textContent=Mr[this.status];let i=this.status==="rt-speaking";this.rtMicBtn.className=i?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtSpeakerBtn.className=i?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtMicBtn.innerHTML=this.rtMicMuted?Nr:Oe,this.rtMicBtn.setAttribute("aria-label",this.rtMicMuted?"Unmute microphone":"Mute microphone"),this.rtSpeakerBtn.innerHTML=this.rtSpeakerMuted?Pr:at,this.rtSpeakerBtn.setAttribute("aria-label",this.rtSpeakerMuted?"Unmute speaker":"Mute speaker")}let t=this.touringActive?this.caption:"",n=!this.touringActive&&(this.recording||e)?this.caption:this.lastQuestion??"",s=!!this.answer||this.busy;this.stackEl.style.display=n||s?"flex":"none",this.userBubbleEl.style.display=n?"block":"none",this.userBubbleEl.textContent=n,this.agentBubbleEl.style.display=s?"flex":"none",this.chipEl.style.display=t?"inline-block":"none",this.chipEl.textContent=t,this.answer?(this.agentTextEl.style.display="inline",this.renderCaptionWords(this.agentTextEl,this.answer),this.thinkingEl.style.display="none"):(this.agentTextEl.style.display="none",this.agentTextEl.textContent="",this.thinkingEl.style.display=this.busy?"inline-flex":"none"),this.phoneBtn&&(this.phoneBtn.disabled=this.busy||this.recording),this.updateBusyState()}setStatus(e){this.status=e,this.render()}setCaption(e){this.caption=e,this.render()}updateBusyState(){this.inputEl.disabled=this.recording||this.touringActive,this.sendBtn.disabled=this.busy||this.recording||!this.inputEl.value.trim(),this.sendBtn.innerHTML=this.busy?jr:st,this.micBtn&&(this.micBtn.disabled=this.touringActive)}setAnswer(e){this.answer=e,this.render()}renderCaptionWords(e,t){e.innerHTML="";let n=t.split(" ");n.forEach((s,i)=>{let a=document.createElement("span");a.className="cairn-word",a.style.animationDelay=`${Math.min(i*55,2800)}ms`,a.textContent=i<n.length-1?s+" ":s,e.appendChild(a)})}reportMiss(e){Te(e);let t=this.reportMissesEndpoint;t&&fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async ask(e){this.setStatus("asking"),this.setAnswer(null),this.lastQuestion=e,this.inputEl.value="",this.render();try{let n=await(await fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:location.pathname,question:e,visible:Be(),history:this.history})})).json().catch(()=>null);this.handleVerb(n),this.history=[...this.history,{role:"user",text:e},{role:"assistant",text:Vr(n)}].slice(-Or)}catch{this.setAnswer("Something went wrong reaching the help service \u2014 try again in a moment.")}finally{this.setStatus("idle")}}handleVerb(e){nt(e,location.pathname,{onExplain:t=>{this.setAnswer(t),this.realtimeActive||this.speak(t)},onNavigate:t=>{location.assign(t)},onMiss:t=>this.reportMiss(t),onDo:(t,n)=>{this.dispatchEvent(new CustomEvent("cairn-do",{detail:{action:t,target:n},bubbles:!0,composed:!0}))},onTour:t=>void this.runTour(t),registeredActions:this.registeredActions})}async runTour(e){let t=++this.tourGeneration,n=this.realtimeActive;this.touringActive=!0,n&&this.setStatus("rt-speaking"),this.setAnswer(null);let s=location.pathname;try{for(let i=0;i<e.length;i++){if(this.tourGeneration!==t)return;let a=e[i];if(this.setCaption(`Step ${i+1} of ${e.length}`),this.setAnswer(a.text),a.route&&a.route!==s){location.assign(a.route);return}if(a.target){let o=ke(a.target);o?we(o):this.reportMiss({attempted:a.target,route:s})}if(n&&this.rtSocket?.readyState===WebSocket.OPEN?await this.speakOverRealtime(a.text):this.speakEndpoint?await this.speakAndWait(a.text):await new Promise(o=>setTimeout(o,Math.max(1200,a.text.length*45))),this.tourGeneration!==t)return}if(this.tourGeneration!==t)return;this.setCaption(""),n&&this.realtimeActive&&this.setStatus("rt-listening")}finally{this.tourGeneration===t&&(this.touringActive=!1,this.render())}}playResponseAudio(e){this.activeAudio&&(this.activeAudio.pause(),this.activeAudio.currentTime=0);let t=URL.createObjectURL(e),n=new Audio(t);return this.activeAudio=n,new Promise(s=>{let i=()=>{URL.revokeObjectURL(t),this.activeAudio===n&&(this.activeAudio=null),s()};n.onended=i,n.play().catch(i)})}async speak(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;this.playResponseAudio(await t.blob())}catch{}}async speakAndWait(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;await this.playResponseAudio(await t.blob())}catch{}}speakOverRealtime(e){return new Promise(t=>{let n=this.rtSocket;if(!n||n.readyState!==WebSocket.OPEN){t();return}this.rtAudioDoneArriving=!1;let s=!1,i=()=>{s||(s=!0,this.rtTourAudioDoneResolve=null,t())};this.rtTourAudioDoneResolve=i,setTimeout(()=>{s||console.warn("[cairn] tour step audio confirmation timed out \u2014 continuing"),i()},15e3),n.send(JSON.stringify({type:"speak",text:e}))})}async startRecording(){if(!(!this.transcribeEndpoint||!this.micSupported()||this.realtimeActive))try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e);this.audioChunks=[],this.setCaption(""),t.ondataavailable=n=>{n.data.size!==0&&(this.audioChunks.push(n.data),this.transcribeSoFar(t.mimeType||"audio/webm",!0))},t.onstop=()=>void this.transcribeSoFar(t.mimeType||"audio/webm",!1),this.mediaRecorder=t,t.start(2e3),this.recording=!0,this.micBtn&&(this.micBtn.innerHTML=Br,this.micBtn.classList.add("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Stop recording")),this.render()}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site.")}}stopRecording(){let e=this.mediaRecorder?.stream;this.mediaRecorder?.stop(),e?.getTracks().forEach(t=>t.stop()),this.recording=!1,this.micBtn&&(this.micBtn.innerHTML=Oe,this.micBtn.classList.remove("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Ask by voice")),this.render()}async transcribeSoFar(e,t){if(this.transcribeEndpoint&&!(t&&this.transcribeInFlight)){this.transcribeInFlight=!0;try{let n=new Blob(this.audioChunks,{type:e}),i=await(await fetch(this.transcribeEndpoint,{method:"POST",headers:{"content-type":e},body:n})).json().catch(()=>null);i?.text?(this.inputEl.value=i.text,this.setCaption(i.text),this.updateBusyState()):t||this.setAnswer("Couldn't make that out \u2014 try typing instead.")}catch{t||this.setAnswer("Couldn't reach the transcription service.")}finally{this.transcribeInFlight=!1}}}async startRealtime(){if(!(!this.realtimeUrl||!this.micSupported()||this.realtimeActive||this.rtStarting)){this.rtStarting=!0,this.setAnswer(null),this.setCaption(""),this.setStatus("rt-connecting");try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new WebSocket(this.realtimeUrl);t.binaryType="arraybuffer",this.rtSocket=t;let n=new AudioContext,s=n.createGain();s.gain.value=this.rtSpeakerMuted?0:1,s.connect(n.destination),this.rtPlaybackCtx=n,this.rtPlaybackGain=s,this.rtNextPlayTime=0,this.rtScheduledSources=[],this.rtAudioDoneArriving=!0;let i=new AudioContext,a=i.createMediaStreamSource(e),o=i.createScriptProcessor(4096,1,1),d=i.createGain();d.gain.value=0;let u=()=>{if(this.rtAudioDoneArriving&&!(this.rtScheduledSources.length>0)){if(this.touringActive){this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null;return}this.setStatus("rt-listening"),this.setCaption("")}},y=()=>{this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null)},_=()=>{y(),this.rtThinkingWatchdog=setTimeout(()=>{this.rtThinkingWatchdog=null,console.warn("[cairn] realtime turn timed out waiting on the server \u2014 resuming listening"),this.rtAudioDoneArriving=!0,this.setStatus("rt-listening"),this.setCaption("")},2e4)},ye=()=>{for(let j of this.rtScheduledSources)try{j.stop()}catch{}this.rtScheduledSources=[],this.rtNextPlayTime=this.rtPlaybackCtx?.currentTime??0},ve=()=>{y(),ye(),this.rtAudioDoneArriving=!0,t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"barge_in"})),this.setStatus("rt-listening"),this.setCaption("")};o.onaudioprocess=j=>{if(t.readyState!==WebSocket.OPEN||this.rtMicMuted)return;if(this.status==="rt-speaking"&&!this.touringActive){Zr(j.inputBuffer.getChannelData(0))>Dr&&ve();return}if(this.status!=="rt-listening")return;let k=Hr(zr(j.inputBuffer.getChannelData(0),i.sampleRate));t.send(k)},a.connect(o),o.connect(d),d.connect(i.destination),this.rtCleanup=()=>{o.disconnect(),a.disconnect(),e.getTracks().forEach(j=>j.stop()),i.close(),ye(),n.close(),this.rtPlaybackCtx=null,this.rtPlaybackGain=null},t.onopen=()=>{t.send(JSON.stringify({type:"context",route:location.pathname,visible:Be()})),this.setStatus("rt-listening"),this.rtStarting=!1},t.onmessage=j=>{if(typeof j.data!="string")return;let k=JSON.parse(j.data);if(k.type==="interim")this.setCaption(k.text);else if(k.type==="final")this.setCaption(k.text),this.setStatus("rt-thinking"),_();else if(k.type==="verb")y(),this.handleVerb(k.verb);else if(k.type==="speaking_start")y(),this.rtAudioDoneArriving=!1,this.setStatus("rt-speaking");else if(k.type==="audio_chunk"){let oe=this.rtPlaybackCtx,De=this.rtPlaybackGain;if(!oe||!De)return;oe.resume().catch(()=>{});let Ze=Uint8Array.from(atob(k.audio),V=>V.charCodeAt(0)),Re=Ze.length/2,ze=new Float32Array(Re),ot=new DataView(Ze.buffer);for(let V=0;V<Re;V++)ze[V]=ot.getInt16(V*2,!0)/32768;let ct=typeof k.sampleRate=="number"?k.sampleRate:24e3,Ne=oe.createBuffer(1,Re,ct);Ne.copyToChannel(ze,0);let ce=oe.createBufferSource();ce.buffer=Ne,ce.connect(De);let He=Math.max(oe.currentTime,this.rtNextPlayTime);ce.start(He),this.rtNextPlayTime=He+Ne.duration,this.rtScheduledSources.push(ce),ce.onended=()=>{this.rtScheduledSources=this.rtScheduledSources.filter(V=>V!==ce),u()}}else k.type==="speaking_end"||k.type==="turn_complete"?(y(),this.rtAudioDoneArriving=!0,u()):k.type==="error"&&(y(),this.setAnswer(k.message??"Something went wrong."),this.touringActive||(this.setStatus("rt-listening"),this.setCaption("")))},t.onerror=()=>{this.setAnswer("Couldn't connect to the realtime voice service."),this.endRealtime()},t.onclose=()=>{this.status!=="idle"&&this.endRealtime()}}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site."),this.setStatus("idle"),this.rtStarting=!1}}}endRealtime(){this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null),this.rtStarting=!1,this.activeAudio?.pause(),this.activeAudio=null,this.rtSocket?.close(),this.rtSocket=null,this.rtCleanup?.(),this.rtCleanup=null,this.rtMicMuted=!1,this.rtSpeakerMuted=!1,this.setCaption(""),this.setStatus("idle"),this.tourGeneration++,this.touringActive=!1,this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null,this.render()}toggleRtMic(){this.rtMicMuted=!this.rtMicMuted,this.render()}toggleRtSpeaker(){this.rtSpeakerMuted=!this.rtSpeakerMuted,this.rtPlaybackGain&&(this.rtPlaybackGain.gain.value=this.rtSpeakerMuted?0:1),this.render()}};function Vr(r){if(!r||typeof r!="object")return"(no response)";let e=r;if(typeof e.text=="string"&&e.text)return e.text;switch(e.verb){case"highlight":case"open":return`(highlighted ${String(e.target)})`;case"navigate":return`(navigated to ${String(e.route)})`;case"do":return`(ran ${String(e.action)}${e.target?` on ${String(e.target)}`:""})`;case"tour":return Array.isArray(e.steps)?e.steps.map(t=>t.text??"").join(" "):"(tour)";default:return"(no response)"}}var Dr=.02;function Zr(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t]*r[t];return Math.sqrt(e/r.length)}function zr(r,e){if(e===16e3)return r;let n=e/16e3,s=Math.round(r.length/n),i=new Float32Array(s),a=0,o=0;for(;a<s;){let d=Math.round((a+1)*n),u=0,y=0;for(let _=o;_<d&&_<r.length;_++)u+=r[_],y++;i[a]=y>0?u/y:0,a++,o=d}return i}function Hr(r){let e=new ArrayBuffer(r.length*2),t=new DataView(e);for(let n=0;n<r.length;n++){let s=Math.max(-1,Math.min(1,r[n]));t.setInt16(n*2,s<0?s*32768:s*32767,!0)}return e}typeof customElements<"u"&&!customElements.get("cairn-widget")&&customElements.define("cairn-widget",Ve);})();
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,21 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
22
22
|
// completion, so the exchange stays paired on screen the way a caption
|
|
23
23
|
// track shows the current line, not a scrolling transcript.
|
|
24
24
|
const [lastQuestion, setLastQuestion] = (0, react_1.useState)(null);
|
|
25
|
+
// Persistent scroll-back log: previous exchanges get archived here (see
|
|
26
|
+
// archiveCurrentExchange below) the instant a new one starts, so they
|
|
27
|
+
// stay visible — scrolled up, not gone — instead of the old behavior of
|
|
28
|
+
// silently overwriting `answer`/`caption` with nothing left to look back
|
|
29
|
+
// at once the next question began.
|
|
30
|
+
const [transcript, setTranscript] = (0, react_1.useState)([]);
|
|
31
|
+
const transcriptIdRef = (0, react_1.useRef)(0);
|
|
32
|
+
const panelRef = (0, react_1.useRef)(null);
|
|
33
|
+
// Mirror the values archiveCurrentExchange needs to read from inside
|
|
34
|
+
// stale closures (the realtime WebSocket's onmessage handler is created
|
|
35
|
+
// once per call and doesn't see later renders' state directly — same
|
|
36
|
+
// reason the rest of the realtime path already uses refs like
|
|
37
|
+
// rtStateRef instead of reading state).
|
|
38
|
+
const userCaptionRef = (0, react_1.useRef)("");
|
|
39
|
+
const answerRef = (0, react_1.useRef)(null);
|
|
25
40
|
const [rtMicMuted, setRtMicMuted] = (0, react_1.useState)(false);
|
|
26
41
|
const [rtSpeakerMuted, setRtSpeakerMuted] = (0, react_1.useState)(false);
|
|
27
42
|
// Set while a "tour" verb's steps are being narrated/highlighted one at a
|
|
@@ -99,6 +114,37 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
99
114
|
// slot falls back to the last typed question.
|
|
100
115
|
const tourChip = touring ? caption : "";
|
|
101
116
|
const userCaption = !touring && (recording || realtimeActive) ? caption : lastQuestion ?? "";
|
|
117
|
+
(0, react_1.useEffect)(() => {
|
|
118
|
+
userCaptionRef.current = userCaption;
|
|
119
|
+
}, [userCaption]);
|
|
120
|
+
(0, react_1.useEffect)(() => {
|
|
121
|
+
answerRef.current = answer;
|
|
122
|
+
}, [answer]);
|
|
123
|
+
// Auto-scroll to the newest content whenever the transcript grows or the
|
|
124
|
+
// live (not-yet-archived) bubble's text changes.
|
|
125
|
+
(0, react_1.useEffect)(() => {
|
|
126
|
+
const el = panelRef.current;
|
|
127
|
+
if (el)
|
|
128
|
+
el.scrollTop = el.scrollHeight;
|
|
129
|
+
}, [transcript, answer, userCaption, busy]);
|
|
130
|
+
/**
|
|
131
|
+
* Moves whatever's currently showing as the "live" exchange into the
|
|
132
|
+
* permanent transcript log, right before it's about to be overwritten by
|
|
133
|
+
* a new turn — called at the start of ask(), at the start of each
|
|
134
|
+
* realtime "final" transcript, and at the start of a tour/tour step. Its
|
|
135
|
+
* effect is exactly "previous goes up, recent shows": the outgoing
|
|
136
|
+
* text becomes a fixed history entry the instant the incoming one starts
|
|
137
|
+
* replacing it, instead of just vanishing.
|
|
138
|
+
*/
|
|
139
|
+
function archiveText(role, text) {
|
|
140
|
+
if (!text)
|
|
141
|
+
return;
|
|
142
|
+
setTranscript((prev) => [...prev, { id: transcriptIdRef.current++, role, text }]);
|
|
143
|
+
}
|
|
144
|
+
function archiveCurrentExchange() {
|
|
145
|
+
archiveText("user", userCaptionRef.current);
|
|
146
|
+
archiveText("agent", answerRef.current ?? "");
|
|
147
|
+
}
|
|
102
148
|
function setRtStatus(next) {
|
|
103
149
|
rtStateRef.current = next;
|
|
104
150
|
setStatus(next);
|
|
@@ -147,6 +193,7 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
147
193
|
touringRef.current = true;
|
|
148
194
|
if (wasRealtimeListening)
|
|
149
195
|
setRtStatus("rt-speaking");
|
|
196
|
+
archiveCurrentExchange();
|
|
150
197
|
setAnswer(null);
|
|
151
198
|
// Tracked locally rather than reading the component's `pathname` —
|
|
152
199
|
// that's only current as of this render, and a step below can navigate
|
|
@@ -159,6 +206,10 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
159
206
|
if (tourGenerationRef.current !== myGeneration)
|
|
160
207
|
return; // superseded — e.g. widget closed or a new question came in
|
|
161
208
|
const step = steps[i];
|
|
209
|
+
// Move the previous step's narration into history before this one replaces it —
|
|
210
|
+
// agent-only, since the tour's triggering question was already archived once, above.
|
|
211
|
+
if (i > 0)
|
|
212
|
+
archiveText("agent", answerRef.current ?? "");
|
|
162
213
|
setTourStep({ index: i, total: steps.length });
|
|
163
214
|
setCaption(`Step ${i + 1} of ${steps.length}`);
|
|
164
215
|
setAnswer(step.text);
|
|
@@ -214,6 +265,7 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
214
265
|
// Typed / push-to-talk question flow
|
|
215
266
|
// ---------------------------------------------------------------------
|
|
216
267
|
async function ask(q) {
|
|
268
|
+
archiveCurrentExchange();
|
|
217
269
|
setStatus("asking");
|
|
218
270
|
setAnswer(null);
|
|
219
271
|
setLastQuestion(q);
|
|
@@ -410,6 +462,7 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
410
462
|
if (!realtimeUrl || !micSupported || realtimeActive || rtStartingRef.current)
|
|
411
463
|
return;
|
|
412
464
|
rtStartingRef.current = true;
|
|
465
|
+
archiveCurrentExchange(); // preserve whatever typed/mic exchange preceded switching into a live call
|
|
413
466
|
setAnswer(null);
|
|
414
467
|
setCaption("");
|
|
415
468
|
setRtStatus("rt-connecting");
|
|
@@ -553,6 +606,7 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
553
606
|
setCaption(msg.text);
|
|
554
607
|
}
|
|
555
608
|
else if (msg.type === "final") {
|
|
609
|
+
archiveCurrentExchange(); // the previous turn's pair is complete — move it into history before this one starts overwriting caption/answer
|
|
556
610
|
setCaption(msg.text);
|
|
557
611
|
setRtStatus("rt-thinking");
|
|
558
612
|
armThinkingWatchdog();
|
|
@@ -683,7 +737,7 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
|
|
|
683
737
|
"rt-thinking": "Thinking…",
|
|
684
738
|
"rt-speaking": "Speaking…",
|
|
685
739
|
};
|
|
686
|
-
return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("style", { suppressHydrationWarning: true, dangerouslySetInnerHTML: { __html: COPILOT_STYLES } }), (0, jsx_runtime_1.jsx)("button", { className: status === "rt-speaking" ? "cairn-fab cairn-fab-speaking" : "cairn-fab", "aria-label": open ? `Close ${persona} help` : `Open ${persona} help`, onClick: () => setOpen((v) => !v), children: open ? (0, jsx_runtime_1.jsx)(lucide_react_1.X, { size: 22 }) : (0, jsx_runtime_1.jsx)(CairnMark, {}) }), open && ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-panel", role: "dialog", "aria-label": `${persona} help panel`, children: [(userCaption || answer || busy) && ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-stack", children: [userCaption && ((0, jsx_runtime_1.jsx)("div", { className: "cairn-bubble cairn-bubble-user", children: userCaption }, `u-${userCaption}`)), (answer || busy) && ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-bubble cairn-bubble-agent", children: [tourChip && (0, jsx_runtime_1.jsx)("span", { className: "cairn-chip", children: tourChip }), answer ? ((0, jsx_runtime_1.jsx)("span", { className: "cairn-bubble-text", children: renderCaptionWords(answer) })) : ((0, jsx_runtime_1.jsxs)("span", { className: "cairn-thinking", "aria-label": "Thinking", children: [(0, jsx_runtime_1.jsx)("span", { className: "cairn-thinking-dot" }), (0, jsx_runtime_1.jsx)("span", { className: "cairn-thinking-dot" }), (0, jsx_runtime_1.jsx)("span", { className: "cairn-thinking-dot" })] }))] }, `a-${answer ?? status}`))] })), realtimeActive ? ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-rt-bar", children: [(0, jsx_runtime_1.jsx)("span", { className: `cairn-rt-dot cairn-rt-dot-${status}` }), (0, jsx_runtime_1.jsx)("span", { className: "cairn-rt-label", children: statusLabel[status] }), (0, jsx_runtime_1.jsxs)("div", { className: "cairn-rt-controls", children: [(0, jsx_runtime_1.jsx)("button", { type: "button", className: status === "rt-speaking" ? "cairn-icon-btn cairn-icon-btn-speaking" : "cairn-icon-btn", "aria-label": rtMicMuted ? "Unmute microphone" : "Mute microphone", onClick: toggleRtMic, children: rtMicMuted ? (0, jsx_runtime_1.jsx)(lucide_react_1.MicOff, { size: 16 }) : (0, jsx_runtime_1.jsx)(lucide_react_1.Mic, { size: 16 }) }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: status === "rt-speaking" ? "cairn-icon-btn cairn-icon-btn-speaking" : "cairn-icon-btn", "aria-label": rtSpeakerMuted ? "Unmute speaker" : "Mute speaker", onClick: toggleRtSpeaker, children: rtSpeakerMuted ? (0, jsx_runtime_1.jsx)(lucide_react_1.VolumeX, { size: 16 }) : (0, jsx_runtime_1.jsx)(lucide_react_1.Volume2, { size: 16 }) }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: "cairn-icon-btn cairn-icon-btn-end", "aria-label": "End conversation", onClick: endRealtime, children: (0, jsx_runtime_1.jsx)(lucide_react_1.PhoneOff, { size: 16 }) })] })] })) : ((0, jsx_runtime_1.jsx)("form", { onSubmit: (e) => {
|
|
740
|
+
return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("style", { suppressHydrationWarning: true, dangerouslySetInnerHTML: { __html: COPILOT_STYLES } }), (0, jsx_runtime_1.jsx)("button", { className: status === "rt-speaking" ? "cairn-fab cairn-fab-speaking" : "cairn-fab", "aria-label": open ? `Close ${persona} help` : `Open ${persona} help`, onClick: () => setOpen((v) => !v), children: open ? (0, jsx_runtime_1.jsx)(lucide_react_1.X, { size: 22 }) : (0, jsx_runtime_1.jsx)(CairnMark, {}) }), open && ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-panel", role: "dialog", "aria-label": `${persona} help panel`, ref: panelRef, children: [(transcript.length > 0 || userCaption || answer || busy) && ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-stack", children: [transcript.map((entry) => ((0, jsx_runtime_1.jsx)("div", { className: entry.role === "user" ? "cairn-bubble cairn-bubble-user cairn-bubble-past" : "cairn-bubble cairn-bubble-agent cairn-bubble-past", children: entry.role === "agent" ? (0, jsx_runtime_1.jsx)("span", { className: "cairn-bubble-text", children: entry.text }) : entry.text }, entry.id))), userCaption && ((0, jsx_runtime_1.jsx)("div", { className: "cairn-bubble cairn-bubble-user", children: userCaption }, `u-${userCaption}`)), (answer || busy) && ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-bubble cairn-bubble-agent", children: [tourChip && (0, jsx_runtime_1.jsx)("span", { className: "cairn-chip", children: tourChip }), answer ? ((0, jsx_runtime_1.jsx)("span", { className: "cairn-bubble-text", children: renderCaptionWords(answer) })) : ((0, jsx_runtime_1.jsxs)("span", { className: "cairn-thinking", "aria-label": "Thinking", children: [(0, jsx_runtime_1.jsx)("span", { className: "cairn-thinking-dot" }), (0, jsx_runtime_1.jsx)("span", { className: "cairn-thinking-dot" }), (0, jsx_runtime_1.jsx)("span", { className: "cairn-thinking-dot" })] }))] }, `a-${answer ?? status}`))] })), realtimeActive ? ((0, jsx_runtime_1.jsxs)("div", { className: "cairn-rt-bar", children: [(0, jsx_runtime_1.jsx)("span", { className: `cairn-rt-dot cairn-rt-dot-${status}` }), (0, jsx_runtime_1.jsx)("span", { className: "cairn-rt-label", children: statusLabel[status] }), (0, jsx_runtime_1.jsxs)("div", { className: "cairn-rt-controls", children: [(0, jsx_runtime_1.jsx)("button", { type: "button", className: status === "rt-speaking" ? "cairn-icon-btn cairn-icon-btn-speaking" : "cairn-icon-btn", "aria-label": rtMicMuted ? "Unmute microphone" : "Mute microphone", onClick: toggleRtMic, children: rtMicMuted ? (0, jsx_runtime_1.jsx)(lucide_react_1.MicOff, { size: 16 }) : (0, jsx_runtime_1.jsx)(lucide_react_1.Mic, { size: 16 }) }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: status === "rt-speaking" ? "cairn-icon-btn cairn-icon-btn-speaking" : "cairn-icon-btn", "aria-label": rtSpeakerMuted ? "Unmute speaker" : "Mute speaker", onClick: toggleRtSpeaker, children: rtSpeakerMuted ? (0, jsx_runtime_1.jsx)(lucide_react_1.VolumeX, { size: 16 }) : (0, jsx_runtime_1.jsx)(lucide_react_1.Volume2, { size: 16 }) }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: "cairn-icon-btn cairn-icon-btn-end", "aria-label": "End conversation", onClick: endRealtime, children: (0, jsx_runtime_1.jsx)(lucide_react_1.PhoneOff, { size: 16 }) })] })] })) : ((0, jsx_runtime_1.jsx)("form", { onSubmit: (e) => {
|
|
687
741
|
e.preventDefault();
|
|
688
742
|
const trimmed = question.trim();
|
|
689
743
|
if (trimmed)
|
|
@@ -920,6 +974,9 @@ const COPILOT_STYLES = `
|
|
|
920
974
|
.cairn-bubble-text {
|
|
921
975
|
white-space: pre-wrap;
|
|
922
976
|
}
|
|
977
|
+
.cairn-bubble-past {
|
|
978
|
+
opacity: 0.55;
|
|
979
|
+
}
|
|
923
980
|
.cairn-word {
|
|
924
981
|
display: inline-block;
|
|
925
982
|
animation: cairn-word-sweep 0.4s ease forwards;
|
package/dist/realtime-cli.js
CHANGED
|
@@ -7,8 +7,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
7
7
|
// `cairn-realtime` — zero-code way to run the realtime voice relay
|
|
8
8
|
// alongside `next dev`, configured entirely through env vars (matching how
|
|
9
9
|
// `cairn build` already works) plus an optional `--port` flag.
|
|
10
|
+
//
|
|
11
|
+
// `--with "<command>"` is what lets `cairn setup` collapse this into a
|
|
12
|
+
// single `npm run dev`, instead of the realtime relay only ever being
|
|
13
|
+
// something you remember to start yourself in a second terminal (which,
|
|
14
|
+
// found live, is indistinguishable from "voice just doesn't work" —
|
|
15
|
+
// nothing in the widget UI hints that a whole separate process needs to
|
|
16
|
+
// be running for realtimeUrl to connect to anything). Spawns the given
|
|
17
|
+
// shell command as a child alongside the relay; either process exiting
|
|
18
|
+
// takes the other down with it, so a crashed `next dev` doesn't leave an
|
|
19
|
+
// orphaned relay listening forever, and vice versa.
|
|
10
20
|
const node_fs_1 = __importDefault(require("node:fs"));
|
|
11
21
|
const node_path_1 = __importDefault(require("node:path"));
|
|
22
|
+
const node_child_process_1 = require("node:child_process");
|
|
12
23
|
const core_1 = require("@cairnvibe/core");
|
|
13
24
|
const realtime_server_1 = require("./realtime-server");
|
|
14
25
|
function parseCapability(raw) {
|
|
@@ -23,26 +34,87 @@ function parsePortFlag(argv) {
|
|
|
23
34
|
const value = Number(argv[idx + 1]);
|
|
24
35
|
return Number.isFinite(value) ? value : undefined;
|
|
25
36
|
}
|
|
37
|
+
function parseWithFlag(argv) {
|
|
38
|
+
const idx = argv.indexOf("--with");
|
|
39
|
+
return idx === -1 ? undefined : argv[idx + 1];
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Real bug this closes: `--with "next dev"` makes this the *first* process
|
|
43
|
+
* `npm run dev` spawns, a sibling of Next.js, not code running inside it —
|
|
44
|
+
* so it never gets Next's own automatic .env/.env.local loading, and a real
|
|
45
|
+
* key sitting in .env was invisible to it (`process.env.DEEPGRAM_API_KEY`
|
|
46
|
+
* genuinely undefined) even though the exact same key worked fine for
|
|
47
|
+
* Next.js's own API routes a moment later. No new dependency for this —
|
|
48
|
+
* .env is a plain KEY=VALUE format. .env.local loads first (checked second
|
|
49
|
+
* in this list, but a key already set never gets overwritten below) to
|
|
50
|
+
* match Next.js's own precedence; nothing here ever overrides a real,
|
|
51
|
+
* already-set process.env value (a shell export, or a platform like Vercel
|
|
52
|
+
* injecting its own configured env vars) — file contents only ever fill a
|
|
53
|
+
* gap, never win over something actually set.
|
|
54
|
+
*/
|
|
55
|
+
function loadDotEnv() {
|
|
56
|
+
for (const filename of [".env.local", ".env"]) {
|
|
57
|
+
const filePath = node_path_1.default.join(process.cwd(), filename);
|
|
58
|
+
if (!node_fs_1.default.existsSync(filePath))
|
|
59
|
+
continue;
|
|
60
|
+
for (const line of node_fs_1.default.readFileSync(filePath, "utf8").split("\n")) {
|
|
61
|
+
const trimmed = line.trim();
|
|
62
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
63
|
+
continue;
|
|
64
|
+
const eq = trimmed.indexOf("=");
|
|
65
|
+
if (eq === -1)
|
|
66
|
+
continue;
|
|
67
|
+
const key = trimmed.slice(0, eq).trim();
|
|
68
|
+
let value = trimmed.slice(eq + 1).trim();
|
|
69
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
70
|
+
value = value.slice(1, -1);
|
|
71
|
+
}
|
|
72
|
+
if (process.env[key] === undefined)
|
|
73
|
+
process.env[key] = value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function spawnCompanion(command) {
|
|
78
|
+
const child = (0, node_child_process_1.spawn)(command, { shell: true, stdio: "inherit" });
|
|
79
|
+
const shutdown = (code) => {
|
|
80
|
+
child.kill();
|
|
81
|
+
process.exit(code ?? 0);
|
|
82
|
+
};
|
|
83
|
+
child.on("exit", shutdown);
|
|
84
|
+
process.on("exit", () => child.kill());
|
|
85
|
+
process.on("SIGINT", () => shutdown(0));
|
|
86
|
+
process.on("SIGTERM", () => shutdown(0));
|
|
87
|
+
}
|
|
26
88
|
function main() {
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
89
|
+
const withCommand = parseWithFlag(process.argv.slice(2));
|
|
90
|
+
// With --with, this process's real job is running the companion command
|
|
91
|
+
// (`next dev`, typically) — a missing key or an unbuilt manifest should
|
|
92
|
+
// skip *voice specifically*, never take down the whole dev server. Without
|
|
93
|
+
// --with (a bare, deliberate `cairn-realtime` invocation), the old
|
|
94
|
+
// hard-fail-with-a-clear-message behavior is exactly right — there's
|
|
95
|
+
// nothing else this process exists to do.
|
|
96
|
+
const fail = (message) => {
|
|
97
|
+
console.error(`cairn-realtime: ${message}`);
|
|
98
|
+
if (withCommand) {
|
|
99
|
+
console.error("cairn-realtime: continuing without voice — starting the companion command anyway.");
|
|
100
|
+
spawnCompanion(withCommand);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
30
103
|
process.exit(1);
|
|
31
|
-
}
|
|
104
|
+
};
|
|
105
|
+
const manifestPath = node_path_1.default.join(process.cwd(), "ui-manifest.json");
|
|
106
|
+
if (!node_fs_1.default.existsSync(manifestPath))
|
|
107
|
+
return fail(`no ${manifestPath} — run \`cairn build\` first.`);
|
|
32
108
|
const manifest = core_1.ManifestSchema.parse(JSON.parse(node_fs_1.default.readFileSync(manifestPath, "utf8")));
|
|
33
109
|
const deepgramApiKey = process.env.DEEPGRAM_API_KEY;
|
|
34
|
-
if (!deepgramApiKey)
|
|
35
|
-
|
|
36
|
-
process.exit(1);
|
|
37
|
-
}
|
|
110
|
+
if (!deepgramApiKey)
|
|
111
|
+
return fail("DEEPGRAM_API_KEY is not set.");
|
|
38
112
|
const provider = process.env.CAIRN_RUNTIME_PROVIDER === "anthropic" ? "anthropic" : "groq";
|
|
39
113
|
if (provider === "anthropic" && !process.env.ANTHROPIC_API_KEY) {
|
|
40
|
-
|
|
41
|
-
process.exit(1);
|
|
114
|
+
return fail("ANTHROPIC_API_KEY is not set (CAIRN_RUNTIME_PROVIDER=anthropic).");
|
|
42
115
|
}
|
|
43
116
|
if (provider === "groq" && !process.env.GROQ_API_KEYS) {
|
|
44
|
-
|
|
45
|
-
process.exit(1);
|
|
117
|
+
return fail("GROQ_API_KEYS is not set (comma-separated).");
|
|
46
118
|
}
|
|
47
119
|
const registeredActions = (process.env.CAIRN_REGISTERED_ACTIONS ?? "")
|
|
48
120
|
.split(",")
|
|
@@ -54,6 +126,8 @@ function main() {
|
|
|
54
126
|
const server = (0, realtime_server_1.createRealtimeServer)({ manifest, provider, deepgramApiKey, registeredActions, capability, persona });
|
|
55
127
|
server.listen(port, () => {
|
|
56
128
|
console.error(`cairn-realtime: listening on ws://localhost:${port} (provider: ${provider})`);
|
|
129
|
+
if (withCommand)
|
|
130
|
+
spawnCompanion(withCommand);
|
|
57
131
|
});
|
|
58
132
|
}
|
|
59
133
|
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cairnvibe/sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "In-app AI copilot — <Copilot/> for React/Next.js, <cairn-widget> for any framework — plus the server handlers and realtime voice relay behind them.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": { "access": "public" },
|
package/src/index.tsx
CHANGED
|
@@ -74,6 +74,21 @@ export function Copilot({
|
|
|
74
74
|
// completion, so the exchange stays paired on screen the way a caption
|
|
75
75
|
// track shows the current line, not a scrolling transcript.
|
|
76
76
|
const [lastQuestion, setLastQuestion] = useState<string | null>(null);
|
|
77
|
+
// Persistent scroll-back log: previous exchanges get archived here (see
|
|
78
|
+
// archiveCurrentExchange below) the instant a new one starts, so they
|
|
79
|
+
// stay visible — scrolled up, not gone — instead of the old behavior of
|
|
80
|
+
// silently overwriting `answer`/`caption` with nothing left to look back
|
|
81
|
+
// at once the next question began.
|
|
82
|
+
const [transcript, setTranscript] = useState<{ id: number; role: "user" | "agent"; text: string }[]>([]);
|
|
83
|
+
const transcriptIdRef = useRef(0);
|
|
84
|
+
const panelRef = useRef<HTMLDivElement | null>(null);
|
|
85
|
+
// Mirror the values archiveCurrentExchange needs to read from inside
|
|
86
|
+
// stale closures (the realtime WebSocket's onmessage handler is created
|
|
87
|
+
// once per call and doesn't see later renders' state directly — same
|
|
88
|
+
// reason the rest of the realtime path already uses refs like
|
|
89
|
+
// rtStateRef instead of reading state).
|
|
90
|
+
const userCaptionRef = useRef<string>("");
|
|
91
|
+
const answerRef = useRef<string | null>(null);
|
|
77
92
|
const [rtMicMuted, setRtMicMuted] = useState(false);
|
|
78
93
|
const [rtSpeakerMuted, setRtSpeakerMuted] = useState(false);
|
|
79
94
|
// Set while a "tour" verb's steps are being narrated/highlighted one at a
|
|
@@ -157,6 +172,39 @@ export function Copilot({
|
|
|
157
172
|
const tourChip = touring ? caption : "";
|
|
158
173
|
const userCaption = !touring && (recording || realtimeActive) ? caption : lastQuestion ?? "";
|
|
159
174
|
|
|
175
|
+
useEffect(() => {
|
|
176
|
+
userCaptionRef.current = userCaption;
|
|
177
|
+
}, [userCaption]);
|
|
178
|
+
useEffect(() => {
|
|
179
|
+
answerRef.current = answer;
|
|
180
|
+
}, [answer]);
|
|
181
|
+
|
|
182
|
+
// Auto-scroll to the newest content whenever the transcript grows or the
|
|
183
|
+
// live (not-yet-archived) bubble's text changes.
|
|
184
|
+
useEffect(() => {
|
|
185
|
+
const el = panelRef.current;
|
|
186
|
+
if (el) el.scrollTop = el.scrollHeight;
|
|
187
|
+
}, [transcript, answer, userCaption, busy]);
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Moves whatever's currently showing as the "live" exchange into the
|
|
191
|
+
* permanent transcript log, right before it's about to be overwritten by
|
|
192
|
+
* a new turn — called at the start of ask(), at the start of each
|
|
193
|
+
* realtime "final" transcript, and at the start of a tour/tour step. Its
|
|
194
|
+
* effect is exactly "previous goes up, recent shows": the outgoing
|
|
195
|
+
* text becomes a fixed history entry the instant the incoming one starts
|
|
196
|
+
* replacing it, instead of just vanishing.
|
|
197
|
+
*/
|
|
198
|
+
function archiveText(role: "user" | "agent", text: string) {
|
|
199
|
+
if (!text) return;
|
|
200
|
+
setTranscript((prev) => [...prev, { id: transcriptIdRef.current++, role, text }]);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function archiveCurrentExchange() {
|
|
204
|
+
archiveText("user", userCaptionRef.current);
|
|
205
|
+
archiveText("agent", answerRef.current ?? "");
|
|
206
|
+
}
|
|
207
|
+
|
|
160
208
|
function setRtStatus(next: Status) {
|
|
161
209
|
rtStateRef.current = next;
|
|
162
210
|
setStatus(next);
|
|
@@ -206,6 +254,7 @@ export function Copilot({
|
|
|
206
254
|
const wasRealtimeListening = realtimeActive;
|
|
207
255
|
touringRef.current = true;
|
|
208
256
|
if (wasRealtimeListening) setRtStatus("rt-speaking");
|
|
257
|
+
archiveCurrentExchange();
|
|
209
258
|
setAnswer(null);
|
|
210
259
|
// Tracked locally rather than reading the component's `pathname` —
|
|
211
260
|
// that's only current as of this render, and a step below can navigate
|
|
@@ -218,6 +267,9 @@ export function Copilot({
|
|
|
218
267
|
for (let i = 0; i < steps.length; i++) {
|
|
219
268
|
if (tourGenerationRef.current !== myGeneration) return; // superseded — e.g. widget closed or a new question came in
|
|
220
269
|
const step = steps[i];
|
|
270
|
+
// Move the previous step's narration into history before this one replaces it —
|
|
271
|
+
// agent-only, since the tour's triggering question was already archived once, above.
|
|
272
|
+
if (i > 0) archiveText("agent", answerRef.current ?? "");
|
|
221
273
|
setTourStep({ index: i, total: steps.length });
|
|
222
274
|
setCaption(`Step ${i + 1} of ${steps.length}`);
|
|
223
275
|
setAnswer(step.text);
|
|
@@ -269,6 +321,7 @@ export function Copilot({
|
|
|
269
321
|
// ---------------------------------------------------------------------
|
|
270
322
|
|
|
271
323
|
async function ask(q: string) {
|
|
324
|
+
archiveCurrentExchange();
|
|
272
325
|
setStatus("asking");
|
|
273
326
|
setAnswer(null);
|
|
274
327
|
setLastQuestion(q);
|
|
@@ -453,6 +506,7 @@ export function Copilot({
|
|
|
453
506
|
// which is exactly what "hearing the agent twice, in parallel" was.
|
|
454
507
|
if (!realtimeUrl || !micSupported || realtimeActive || rtStartingRef.current) return;
|
|
455
508
|
rtStartingRef.current = true;
|
|
509
|
+
archiveCurrentExchange(); // preserve whatever typed/mic exchange preceded switching into a live call
|
|
456
510
|
setAnswer(null);
|
|
457
511
|
setCaption("");
|
|
458
512
|
setRtStatus("rt-connecting");
|
|
@@ -600,6 +654,7 @@ export function Copilot({
|
|
|
600
654
|
if (msg.type === "interim") {
|
|
601
655
|
setCaption(msg.text);
|
|
602
656
|
} else if (msg.type === "final") {
|
|
657
|
+
archiveCurrentExchange(); // the previous turn's pair is complete — move it into history before this one starts overwriting caption/answer
|
|
603
658
|
setCaption(msg.text);
|
|
604
659
|
setRtStatus("rt-thinking");
|
|
605
660
|
armThinkingWatchdog();
|
|
@@ -743,10 +798,18 @@ export function Copilot({
|
|
|
743
798
|
{open ? <X size={22} /> : <CairnMark />}
|
|
744
799
|
</button>
|
|
745
800
|
{open && (
|
|
746
|
-
<div className="cairn-panel" role="dialog" aria-label={`${persona} help panel`}>
|
|
801
|
+
<div className="cairn-panel" role="dialog" aria-label={`${persona} help panel`} ref={panelRef}>
|
|
747
802
|
|
|
748
|
-
{(userCaption || answer || busy) && (
|
|
803
|
+
{(transcript.length > 0 || userCaption || answer || busy) && (
|
|
749
804
|
<div className="cairn-stack">
|
|
805
|
+
{transcript.map((entry) => (
|
|
806
|
+
<div
|
|
807
|
+
className={entry.role === "user" ? "cairn-bubble cairn-bubble-user cairn-bubble-past" : "cairn-bubble cairn-bubble-agent cairn-bubble-past"}
|
|
808
|
+
key={entry.id}
|
|
809
|
+
>
|
|
810
|
+
{entry.role === "agent" ? <span className="cairn-bubble-text">{entry.text}</span> : entry.text}
|
|
811
|
+
</div>
|
|
812
|
+
))}
|
|
750
813
|
{userCaption && (
|
|
751
814
|
<div className="cairn-bubble cairn-bubble-user" key={`u-${userCaption}`}>
|
|
752
815
|
{userCaption}
|
|
@@ -1101,6 +1164,9 @@ const COPILOT_STYLES = `
|
|
|
1101
1164
|
.cairn-bubble-text {
|
|
1102
1165
|
white-space: pre-wrap;
|
|
1103
1166
|
}
|
|
1167
|
+
.cairn-bubble-past {
|
|
1168
|
+
opacity: 0.55;
|
|
1169
|
+
}
|
|
1104
1170
|
.cairn-word {
|
|
1105
1171
|
display: inline-block;
|
|
1106
1172
|
animation: cairn-word-sweep 0.4s ease forwards;
|
package/src/realtime-cli.ts
CHANGED
|
@@ -2,8 +2,19 @@
|
|
|
2
2
|
// `cairn-realtime` — zero-code way to run the realtime voice relay
|
|
3
3
|
// alongside `next dev`, configured entirely through env vars (matching how
|
|
4
4
|
// `cairn build` already works) plus an optional `--port` flag.
|
|
5
|
+
//
|
|
6
|
+
// `--with "<command>"` is what lets `cairn setup` collapse this into a
|
|
7
|
+
// single `npm run dev`, instead of the realtime relay only ever being
|
|
8
|
+
// something you remember to start yourself in a second terminal (which,
|
|
9
|
+
// found live, is indistinguishable from "voice just doesn't work" —
|
|
10
|
+
// nothing in the widget UI hints that a whole separate process needs to
|
|
11
|
+
// be running for realtimeUrl to connect to anything). Spawns the given
|
|
12
|
+
// shell command as a child alongside the relay; either process exiting
|
|
13
|
+
// takes the other down with it, so a crashed `next dev` doesn't leave an
|
|
14
|
+
// orphaned relay listening forever, and vice versa.
|
|
5
15
|
import fs from "node:fs";
|
|
6
16
|
import path from "node:path";
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
7
18
|
import { ManifestSchema } from "@cairnvibe/core";
|
|
8
19
|
import { createRealtimeServer } from "./realtime-server";
|
|
9
20
|
import type { CapabilityTier } from "./server";
|
|
@@ -20,28 +31,88 @@ function parsePortFlag(argv: string[]): number | undefined {
|
|
|
20
31
|
return Number.isFinite(value) ? value : undefined;
|
|
21
32
|
}
|
|
22
33
|
|
|
34
|
+
function parseWithFlag(argv: string[]): string | undefined {
|
|
35
|
+
const idx = argv.indexOf("--with");
|
|
36
|
+
return idx === -1 ? undefined : argv[idx + 1];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Real bug this closes: `--with "next dev"` makes this the *first* process
|
|
41
|
+
* `npm run dev` spawns, a sibling of Next.js, not code running inside it —
|
|
42
|
+
* so it never gets Next's own automatic .env/.env.local loading, and a real
|
|
43
|
+
* key sitting in .env was invisible to it (`process.env.DEEPGRAM_API_KEY`
|
|
44
|
+
* genuinely undefined) even though the exact same key worked fine for
|
|
45
|
+
* Next.js's own API routes a moment later. No new dependency for this —
|
|
46
|
+
* .env is a plain KEY=VALUE format. .env.local loads first (checked second
|
|
47
|
+
* in this list, but a key already set never gets overwritten below) to
|
|
48
|
+
* match Next.js's own precedence; nothing here ever overrides a real,
|
|
49
|
+
* already-set process.env value (a shell export, or a platform like Vercel
|
|
50
|
+
* injecting its own configured env vars) — file contents only ever fill a
|
|
51
|
+
* gap, never win over something actually set.
|
|
52
|
+
*/
|
|
53
|
+
function loadDotEnv(): void {
|
|
54
|
+
for (const filename of [".env.local", ".env"]) {
|
|
55
|
+
const filePath = path.join(process.cwd(), filename);
|
|
56
|
+
if (!fs.existsSync(filePath)) continue;
|
|
57
|
+
for (const line of fs.readFileSync(filePath, "utf8").split("\n")) {
|
|
58
|
+
const trimmed = line.trim();
|
|
59
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
60
|
+
const eq = trimmed.indexOf("=");
|
|
61
|
+
if (eq === -1) continue;
|
|
62
|
+
const key = trimmed.slice(0, eq).trim();
|
|
63
|
+
let value = trimmed.slice(eq + 1).trim();
|
|
64
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
65
|
+
value = value.slice(1, -1);
|
|
66
|
+
}
|
|
67
|
+
if (process.env[key] === undefined) process.env[key] = value;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function spawnCompanion(command: string): void {
|
|
73
|
+
const child = spawn(command, { shell: true, stdio: "inherit" });
|
|
74
|
+
const shutdown = (code: number | null) => {
|
|
75
|
+
child.kill();
|
|
76
|
+
process.exit(code ?? 0);
|
|
77
|
+
};
|
|
78
|
+
child.on("exit", shutdown);
|
|
79
|
+
process.on("exit", () => child.kill());
|
|
80
|
+
process.on("SIGINT", () => shutdown(0));
|
|
81
|
+
process.on("SIGTERM", () => shutdown(0));
|
|
82
|
+
}
|
|
83
|
+
|
|
23
84
|
function main(): void {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
85
|
+
const withCommand = parseWithFlag(process.argv.slice(2));
|
|
86
|
+
|
|
87
|
+
// With --with, this process's real job is running the companion command
|
|
88
|
+
// (`next dev`, typically) — a missing key or an unbuilt manifest should
|
|
89
|
+
// skip *voice specifically*, never take down the whole dev server. Without
|
|
90
|
+
// --with (a bare, deliberate `cairn-realtime` invocation), the old
|
|
91
|
+
// hard-fail-with-a-clear-message behavior is exactly right — there's
|
|
92
|
+
// nothing else this process exists to do.
|
|
93
|
+
const fail = (message: string): never | void => {
|
|
94
|
+
console.error(`cairn-realtime: ${message}`);
|
|
95
|
+
if (withCommand) {
|
|
96
|
+
console.error("cairn-realtime: continuing without voice — starting the companion command anyway.");
|
|
97
|
+
spawnCompanion(withCommand);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
27
100
|
process.exit(1);
|
|
28
|
-
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const manifestPath = path.join(process.cwd(), "ui-manifest.json");
|
|
104
|
+
if (!fs.existsSync(manifestPath)) return fail(`no ${manifestPath} — run \`cairn build\` first.`);
|
|
29
105
|
const manifest = ManifestSchema.parse(JSON.parse(fs.readFileSync(manifestPath, "utf8")));
|
|
30
106
|
|
|
31
107
|
const deepgramApiKey = process.env.DEEPGRAM_API_KEY;
|
|
32
|
-
if (!deepgramApiKey)
|
|
33
|
-
console.error("cairn-realtime: DEEPGRAM_API_KEY is not set.");
|
|
34
|
-
process.exit(1);
|
|
35
|
-
}
|
|
108
|
+
if (!deepgramApiKey) return fail("DEEPGRAM_API_KEY is not set.");
|
|
36
109
|
|
|
37
110
|
const provider = process.env.CAIRN_RUNTIME_PROVIDER === "anthropic" ? "anthropic" : "groq";
|
|
38
111
|
if (provider === "anthropic" && !process.env.ANTHROPIC_API_KEY) {
|
|
39
|
-
|
|
40
|
-
process.exit(1);
|
|
112
|
+
return fail("ANTHROPIC_API_KEY is not set (CAIRN_RUNTIME_PROVIDER=anthropic).");
|
|
41
113
|
}
|
|
42
114
|
if (provider === "groq" && !process.env.GROQ_API_KEYS) {
|
|
43
|
-
|
|
44
|
-
process.exit(1);
|
|
115
|
+
return fail("GROQ_API_KEYS is not set (comma-separated).");
|
|
45
116
|
}
|
|
46
117
|
|
|
47
118
|
const registeredActions = (process.env.CAIRN_REGISTERED_ACTIONS ?? "")
|
|
@@ -56,6 +127,7 @@ function main(): void {
|
|
|
56
127
|
const server = createRealtimeServer({ manifest, provider, deepgramApiKey, registeredActions, capability, persona });
|
|
57
128
|
server.listen(port, () => {
|
|
58
129
|
console.error(`cairn-realtime: listening on ws://localhost:${port} (provider: ${provider})`);
|
|
130
|
+
if (withCommand) spawnCompanion(withCommand);
|
|
59
131
|
});
|
|
60
132
|
}
|
|
61
133
|
|