@tokmizer/plugin 0.9.54 → 0.9.56
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/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/plugin.json +1 -1
- package/dist/bin/tkr-codex-hook.js +34 -34
- package/dist/bin/tkr-daemon.js +40 -40
- package/dist/bin/tkr-exec +39 -39
- package/dist/bin/tkr-exec.js +39 -39
- package/dist/bin/tkr-shim.js +29 -29
- package/dist/bin/tkr.js +100 -100
- package/dist/hooks-host/post-tool-use.js +45 -45
- package/dist/hooks-host/reducer-stop.js +16 -16
- package/dist/index.js +36 -36
- package/dist/native/manifest.json +8 -8
- package/dist/native/tkr-exec-darwin-arm64 +0 -0
- package/dist/native/tkr-exec-darwin-x64 +0 -0
- package/dist/native/tkr-exec-linux-arm64 +0 -0
- package/dist/native/tkr-exec-linux-x64 +0 -0
- package/package.json +1 -1
package/dist/bin/tkr.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __tkrCreateRequire } from "node:module"; const require = __tkrCreateRequire(import.meta.url);
|
|
3
|
-
var Ki=Object.defineProperty;var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var te=(t,e)=>{for(var r in e)Ki(t,r,{get:e[r],enumerable:!0})};var S,jr,p,oe,yt=E(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(S||(S={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(jr||(jr={}));p=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),oe=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}}});var d,Gi,F,Vt=E(()=>{yt();d=S.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"]),Gi=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),F=class t 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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};F.create=t=>new F(t)});var Ji,le,zr=E(()=>{Vt();yt();Ji=(t,e)=>{let r;switch(t.code){case d.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,S.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${S.joinValues(t.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${S.joinValues(t.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${S.joinValues(t.options)}, received '${t.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:S.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case d.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case d.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=e.defaultError,S.assertNever(t)}return{message:r}},le=Ji});function Wi(t){os=t}function Ye(){return os}var os,Kt=E(()=>{zr();os=le});function m(t,e){let r=Ye(),n=wt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===le?void 0:le].filter(s=>!!s)});t.common.issues.push(n)}var wt,Yi,I,w,Ae,M,Gt,Jt,ye,qe,Ur=E(()=>{Kt();zr();wt=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},Yi=[];I=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return w;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return w;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),Ae=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),Gt=t=>t.status==="aborted",Jt=t=>t.status==="dirty",ye=t=>t.status==="valid",qe=t=>typeof Promise<"u"&&t instanceof Promise});var is=E(()=>{});var h,as=E(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}))});function _(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||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:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function ds(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ma(t){return new RegExp(`^${ds(t)}$`)}function fs(t){let e=`${ls}T${ds(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function pa(t,e){return!!((e==="v4"||!e)&&ia.test(t)||(e==="v6"||!e)&&ca.test(t))}function ha(t,e){if(!ra.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.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 ga(t,e){return!!((e==="v4"||!e)&&aa.test(t)||(e==="v6"||!e)&&ua.test(t))}function ya(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Xe(t){if(t instanceof j){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=J.create(Xe(n))}return new j({...t._def,shape:()=>e})}else return t instanceof me?new me({...t._def,type:Xe(t.element)}):t instanceof J?J.create(Xe(t.unwrap())):t instanceof ae?ae.create(Xe(t.unwrap())):t instanceof ie?ie.create(t.items.map(e=>Xe(e))):t}function Hr(t,e){let r=oe(t),n=oe(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=S.objectKeys(e),o=S.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Hr(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Hr(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ms(t,e){return new Fe({values:t,typeName:b.ZodEnum,..._(e)})}function us(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ps(t,e={},r){return t?be.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=us(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=us(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):be.create()}var W,cs,x,qi,Xi,Qi,ea,ta,ra,na,sa,oa,Zr,ia,aa,ca,ua,la,da,ls,fa,we,Re,Ce,$e,Pe,Qe,Oe,Ie,be,fe,re,et,me,j,De,de,Wt,Ne,ie,Yt,tt,rt,qt,Me,Le,Fe,je,ve,Y,J,ae,ze,Ue,nt,wa,bt,vt,Ze,ba,b,va,hs,gs,ka,_a,ys,xa,Sa,Ea,Ta,Aa,Ra,Ca,$a,Pa,Oa,Ia,Da,Na,Ma,La,Fa,ja,za,Ua,Za,Ha,Ba,Va,Ka,Ga,Ja,Wa,Ya,qa,Xa,Qa,ec,tc,rc,ws=E(()=>{Vt();Kt();as();Ur();yt();W=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,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}},cs=(t,e)=>{if(ye(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new F(t.common.issues);return this._error=r,this._error}}};x=class{get description(){return this._def.description}_getType(e){return oe(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I,ctx:{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(qe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return cs(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ye(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ye(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(qe(s)?s:Promise.resolve(s));return cs(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Y({schema:this,typeName:b.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:r=>this["~validate"](r)}}optional(){return J.create(this,this._def)}nullable(){return ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return ve.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Ne.create(this,e,this._def)}transform(e){return new Y({..._(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ze({..._(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new bt({typeName:b.ZodBranded,type:this,..._(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ue({..._(this._def),innerType:this,catchValue:r,typeName:b.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vt.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qi=/^c[^\s-]{8,}$/i,Xi=/^[0-9a-z]+$/,Qi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ea=/^[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,ta=/^[a-z0-9_-]{21}$/i,ra=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,na=/^[-+]?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)?)??$/,sa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ia=/^(?:(?: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])$/,aa=/^(?:(?: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])$/,ca=/^(([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]))$/,ua=/^(([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])$/,la=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,da=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ls="((\\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])))",fa=new RegExp(`^${ls}$`);we=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.string,received:o.parsedType}),w}let n=new I,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")sa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Zr||(Zr=new RegExp(oa,"u")),Zr.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ea.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")ta.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Xi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:d.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:d.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?fs(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?fa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?ma(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?na.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?pa(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?ha(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"jwt",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ga(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cidr",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?la.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?da.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64url",code:d.invalid_string,message:o.message}),n.dirty()):S.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.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,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};we.create=t=>new we({checks:[],typeName:b.ZodString,coerce:t?.coerce??!1,..._(t)});Re=class t extends x{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)!==p.number){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.number,received:o.parsedType}),w}let n,s=new I;for(let o of this._def.checks)o.kind==="int"?S.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?ya(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_finite,message:o.message}),s.dirty()):S.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&S.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Re.create=t=>new Re({checks:[],typeName:b.ZodNumber,coerce:t?.coerce||!1,..._(t)});Ce=class t extends x{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)!==p.bigint)return this._getInvalidInput(e);let n,s=new I;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):S.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ce.create=t=>new Ce({checks:[],typeName:b.ZodBigInt,coerce:t?.coerce??!1,..._(t)});$e=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.boolean,received:n.parsedType}),w}return M(e.data)}};$e.create=t=>new $e({typeName:b.ZodBoolean,coerce:t?.coerce||!1,..._(t)});Pe=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.date,received:o.parsedType}),w}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_date}),w}let n=new I,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):S.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Pe.create=t=>new Pe({checks:[],coerce:t?.coerce||!1,typeName:b.ZodDate,..._(t)});Qe=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.symbol,received:n.parsedType}),w}return M(e.data)}};Qe.create=t=>new Qe({typeName:b.ZodSymbol,..._(t)});Oe=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.undefined,received:n.parsedType}),w}return M(e.data)}};Oe.create=t=>new Oe({typeName:b.ZodUndefined,..._(t)});Ie=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.null,received:n.parsedType}),w}return M(e.data)}};Ie.create=t=>new Ie({typeName:b.ZodNull,..._(t)});be=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}};be.create=t=>new be({typeName:b.ZodAny,..._(t)});fe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}};fe.create=t=>new fe({typeName:b.ZodUnknown,..._(t)});re=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.never,received:r.parsedType}),w}};re.create=t=>new re({typeName:b.ZodNever,..._(t)});et=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.void,received:n.parsedType}),w}return M(e.data)}};et.create=t=>new et({typeName:b.ZodVoid,..._(t)});me=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return m(r,{code:d.invalid_type,expected:p.array,received:r.parsedType}),w;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(m(r,{code:i?d.too_big:d.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(m(r,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(m(r,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new W(r,i,r.path,a)))).then(i=>I.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new W(r,i,r.path,a)));return I.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};me.create=(t,e)=>new me({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,..._(e)});j=class t extends x{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(),r=S.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return m(u,{code:d.invalid_type,expected:p.object,received:u.parsedType}),w}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof re&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=o[u],g=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new W(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof re){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(m(s,{code:d.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let g=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new W(s,g,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let g=await l.key,v=await l.value;u.push({key:g,value:v,alwaysSet:l.alwaysSet})}return u}).then(u=>I.mergeObjectSync(n,u)):I.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of S.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of S.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Xe(this)}partial(e){let r={};for(let n of S.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of S.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof J;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return ms(S.objectKeys(this.shape))}};j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:re.create(),typeName:b.ZodObject,..._(e)});j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:re.create(),typeName:b.ZodObject,..._(e)});j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:re.create(),typeName:b.ZodObject,..._(e)});De=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new F(a.ctx.common.issues));return m(r,{code:d.invalid_union,unionErrors:i}),w}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new F(c));return m(r,{code:d.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}};De.create=(t,e)=>new De({options:t,typeName:b.ZodUnion,..._(e)});de=t=>t instanceof Me?de(t.schema):t instanceof Y?de(t.innerType()):t instanceof Le?[t.value]:t instanceof Fe?t.options:t instanceof je?S.objectValues(t.enum):t instanceof ze?de(t._def.innerType):t instanceof Oe?[void 0]:t instanceof Ie?[null]:t instanceof J?[void 0,...de(t.unwrap())]:t instanceof ae?[null,...de(t.unwrap())]:t instanceof bt||t instanceof Ze?de(t.unwrap()):t instanceof Ue?de(t._def.innerType):[],Wt=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return m(r,{code:d.invalid_type,expected:p.object,received:r.parsedType}),w;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(m(r,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=de(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,..._(n)})}};Ne=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Gt(o)||Gt(i))return w;let a=Hr(o.value,i.value);return a.valid?((Jt(o)||Jt(i))&&r.dirty(),{status:r.value,value:a.data}):(m(n,{code:d.invalid_intersection_types}),w)};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(([o,i])=>s(o,i)):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}))}};Ne.create=(t,e,r)=>new Ne({left:t,right:e,typeName:b.ZodIntersection,..._(r)});ie=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return m(n,{code:d.invalid_type,expected:p.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return m(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new W(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>I.mergeArray(r,i)):I.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ie.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:t,typeName:b.ZodTuple,rest:null,..._(e)})};Yt=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return m(n,{code:d.invalid_type,expected:p.object,received:n.parsedType}),w;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new W(n,a,n.path,a)),value:i._parse(new W(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?I.mergeObjectAsync(r,s):I.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:b.ZodRecord,..._(n)}):new t({keyType:we.create(),valueType:e,typeName:b.ZodRecord,..._(r)})}},tt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return m(n,{code:d.invalid_type,expected:p.map,received:n.parsedType}),w;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new W(n,a,n.path,[u,"key"])),value:o._parse(new W(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return w;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return w;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};tt.create=(t,e,r)=>new tt({valueType:e,keyType:t,typeName:b.ZodMap,..._(r)});rt=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return m(n,{code:d.invalid_type,expected:p.set,received:n.parsedType}),w;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return w;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new W(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};rt.create=(t,e)=>new rt({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,..._(e)});qt=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return m(r,{code:d.invalid_type,expected:p.function,received:r.parsedType}),w;function n(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ye(),le].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ye(),le].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ve){let a=this;return M(async function(...c){let u=new F([]),l=await a._def.args.parseAsync(c,o).catch(k=>{throw u.addIssue(n(c,k)),u}),g=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(g,o).catch(k=>{throw u.addIssue(s(g,k)),u})})}else{let a=this;return M(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new F([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),g=a._def.returns.safeParse(l,o);if(!g.success)throw new F([s(l,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ie.create(e).rest(fe.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||ie.create([]).rest(fe.create()),returns:r||fe.create(),typeName:b.ZodFunction,..._(n)})}},Me=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Me.create=(t,e)=>new Me({getter:t,typeName:b.ZodLazy,..._(e)});Le=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return m(r,{received:r.data,code:d.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};Le.create=(t,e)=>new Le({value:t,typeName:b.ZodLiteral,..._(e)});Fe=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{expected:S.joinValues(n),received:r.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{received:r.data,code:d.invalid_enum_value,options:n}),w}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Fe.create=ms;je=class extends x{_parse(e){let r=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=S.objectValues(r);return m(n,{expected:S.joinValues(s),received:n.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=S.objectValues(r);return m(n,{received:n.data,code:d.invalid_enum_value,options:s}),w}return M(e.data)}get enum(){return this._def.values}};je.create=(t,e)=>new je({values:t,typeName:b.ZodNativeEnum,..._(e)});ve=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return m(r,{code:d.invalid_type,expected:p.promise,received:r.parsedType}),w;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return M(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ve.create=(t,e)=>new ve({type:t,typeName:b.ZodPromise,..._(e)});Y=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{m(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return w;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?w:c.status==="dirty"?Ae(c.value):r.value==="dirty"?Ae(c.value):c});{if(r.value==="aborted")return w;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?w:a.status==="dirty"?Ae(a.value):r.value==="dirty"?Ae(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ye(i))return w;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ye(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):w);S.assertNever(s)}};Y.create=(t,e,r)=>new Y({schema:t,typeName:b.ZodEffects,effect:e,..._(r)});Y.createWithPreprocess=(t,e,r)=>new Y({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,..._(r)});J=class extends x{_parse(e){return this._getType(e)===p.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};J.create=(t,e)=>new J({innerType:t,typeName:b.ZodOptional,..._(e)});ae=class extends x{_parse(e){return this._getType(e)===p.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ae.create=(t,e)=>new ae({innerType:t,typeName:b.ZodNullable,..._(e)});ze=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ze.create=(t,e)=>new ze({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});Ue=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qe(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ue.create=(t,e)=>new Ue({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});nt=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};nt.create=t=>new nt({typeName:b.ZodNaN,..._(t)});wa=Symbol("zod_brand"),bt=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vt=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),Ae(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:b.ZodPipeline})}},Ze=class extends x{_parse(e){let r=this._def.innerType._parse(e),n=s=>(ye(s)&&(s.value=Object.freeze(s.value)),s);return qe(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Ze.create=(t,e)=>new Ze({innerType:t,typeName:b.ZodReadonly,..._(e)});ba={object:j.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(b||(b={}));va=(t,e={message:`Input not instance of ${t.name}`})=>ps(r=>r instanceof t,e),hs=we.create,gs=Re.create,ka=nt.create,_a=Ce.create,ys=$e.create,xa=Pe.create,Sa=Qe.create,Ea=Oe.create,Ta=Ie.create,Aa=be.create,Ra=fe.create,Ca=re.create,$a=et.create,Pa=me.create,Oa=j.create,Ia=j.strictCreate,Da=De.create,Na=Wt.create,Ma=Ne.create,La=ie.create,Fa=Yt.create,ja=tt.create,za=rt.create,Ua=qt.create,Za=Me.create,Ha=Le.create,Ba=Fe.create,Va=je.create,Ka=ve.create,Ga=Y.create,Ja=J.create,Wa=ae.create,Ya=Y.createWithPreprocess,qa=vt.create,Xa=()=>hs().optional(),Qa=()=>gs().optional(),ec=()=>ys().optional(),tc={string:(t=>we.create({...t,coerce:!0})),number:(t=>Re.create({...t,coerce:!0})),boolean:(t=>$e.create({...t,coerce:!0})),bigint:(t=>Ce.create({...t,coerce:!0})),date:(t=>Pe.create({...t,coerce:!0}))},rc=w});var f={};te(f,{BRAND:()=>wa,DIRTY:()=>Ae,EMPTY_PATH:()=>Yi,INVALID:()=>w,NEVER:()=>rc,OK:()=>M,ParseStatus:()=>I,Schema:()=>x,ZodAny:()=>be,ZodArray:()=>me,ZodBigInt:()=>Ce,ZodBoolean:()=>$e,ZodBranded:()=>bt,ZodCatch:()=>Ue,ZodDate:()=>Pe,ZodDefault:()=>ze,ZodDiscriminatedUnion:()=>Wt,ZodEffects:()=>Y,ZodEnum:()=>Fe,ZodError:()=>F,ZodFirstPartyTypeKind:()=>b,ZodFunction:()=>qt,ZodIntersection:()=>Ne,ZodIssueCode:()=>d,ZodLazy:()=>Me,ZodLiteral:()=>Le,ZodMap:()=>tt,ZodNaN:()=>nt,ZodNativeEnum:()=>je,ZodNever:()=>re,ZodNull:()=>Ie,ZodNullable:()=>ae,ZodNumber:()=>Re,ZodObject:()=>j,ZodOptional:()=>J,ZodParsedType:()=>p,ZodPipeline:()=>vt,ZodPromise:()=>ve,ZodReadonly:()=>Ze,ZodRecord:()=>Yt,ZodSchema:()=>x,ZodSet:()=>rt,ZodString:()=>we,ZodSymbol:()=>Qe,ZodTransformer:()=>Y,ZodTuple:()=>ie,ZodType:()=>x,ZodUndefined:()=>Oe,ZodUnion:()=>De,ZodUnknown:()=>fe,ZodVoid:()=>et,addIssueToContext:()=>m,any:()=>Aa,array:()=>Pa,bigint:()=>_a,boolean:()=>ys,coerce:()=>tc,custom:()=>ps,date:()=>xa,datetimeRegex:()=>fs,defaultErrorMap:()=>le,discriminatedUnion:()=>Na,effect:()=>Ga,enum:()=>Ba,function:()=>Ua,getErrorMap:()=>Ye,getParsedType:()=>oe,instanceof:()=>va,intersection:()=>Ma,isAborted:()=>Gt,isAsync:()=>qe,isDirty:()=>Jt,isValid:()=>ye,late:()=>ba,lazy:()=>Za,literal:()=>Ha,makeIssue:()=>wt,map:()=>ja,nan:()=>ka,nativeEnum:()=>Va,never:()=>Ca,null:()=>Ta,nullable:()=>Wa,number:()=>gs,object:()=>Oa,objectUtil:()=>jr,oboolean:()=>ec,onumber:()=>Qa,optional:()=>Ja,ostring:()=>Xa,pipeline:()=>qa,preprocess:()=>Ya,promise:()=>Ka,quotelessJson:()=>Gi,record:()=>Fa,set:()=>za,setErrorMap:()=>Wi,strictObject:()=>Ia,string:()=>hs,symbol:()=>Sa,transformer:()=>Ga,tuple:()=>La,undefined:()=>Ea,union:()=>Da,unknown:()=>Ra,util:()=>S,void:()=>$a});var Br=E(()=>{Kt();Ur();is();yt();ws();Vt()});var st=E(()=>{Br();Br()});import{createHash as nc}from"node:crypto";function ke(t){let e=bs.get(t);return e||(e=nc("sha256").update(`tkr:${t}`).digest("hex").slice(0,16),bs.set(t,e)),e}var sc,oc,ot,bs,kt=E(()=>{"use strict";st();sc=f.enum(["normal","compact","minimal"]),oc=f.enum(["off","light","balanced","max"]),ot=f.object({enabled:f.boolean().default(!0),telemetryOptIn:f.boolean().default(!0),outputVerbosity:sc.default("compact"),reducer:oc.default("off"),filters:f.object({enableAll:f.boolean().default(!0),disabled:f.array(f.string().max(64)).max(100).default([])}).default({enableAll:!0,disabled:[]})}),bs=new Map});var ks={};te(ks,{bundleRefreshFile:()=>_t,claudeCommandFile:()=>xe,claudeCommandsDir:()=>er,contentCacheDir:()=>St,contentCacheFile:()=>Xt,enrollCooldownFile:()=>Vr,installIdFile:()=>it,managedCommandsFile:()=>Qt,skillFile:()=>_e,skillsDir:()=>xt,stateFile:()=>ic,tokmizerHome:()=>y});import vs from"node:os";import{join as q}from"node:path";function y(){return process.env.TOKMIZER_HOME||q(vs.homedir(),".tokmizer")}function ic(){return q(y(),"state.json")}function it(){return q(y(),"install-id")}function Vr(){return q(y(),"enroll-cooldown")}function _t(){return q(y(),"bundle-refresh.json")}function xt(){return q(y(),"skills")}function _e(t){return q(xt(),`${t}.md`)}function St(){return q(y(),"content-cache")}function Xt(t){return q(St(),t)}function Qt(){return q(y(),"managed-commands.json")}function er(){return process.env.TOKMIZER_CLAUDE_COMMANDS_DIR||q(vs.homedir(),".claude","commands")}function xe(t){return q(er(),`${t}.md`)}var D=E(()=>{"use strict"});import at from"node:os";import{createHash as ac,randomUUID as cc}from"node:crypto";import{readFile as _s,writeFile as xs,mkdir as uc}from"node:fs/promises";async function tr(){try{let r=(await _s(it(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(r))return r}catch{}await uc(y(),{recursive:!0});let t=cc();try{return await xs(it(),t,{mode:384,flag:"wx"}),t}catch{try{let e=(await _s(it(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(e))return e}catch{}return await xs(it(),t,{mode:384}),t}}function Kr(t){return ac("sha256").update(t).digest("hex")}function lc(){let t=at.networkInterfaces();for(let e of Object.keys(t))for(let r of t[e]??[])if(!r.internal&&r.mac&&r.mac!=="00:00:00:00:00:00")return r.mac;return"no-mac"}async function X(){let t=await tr(),e=at.hostname(),r=at.platform(),n=at.release(),s=at.cpus(),o=s[0]?.model??"unknown",i=s.length,a=Kr(lc()),c=Kr(at.userInfo().username),u=[e,r,n,o,String(i),a,c,t].join("|");return{fingerprint:Kr(u),installId:t,hostname:e,os:r,osVersion:n,cpuModel:o,cpuCores:i,macHash:a,usernameHash:c}}var He=E(()=>{"use strict";D()});import{join as Gr}from"node:path";import{mkdir as dc,readFile as fc,writeFile as mc,unlink as Ss,rename as pc}from"node:fs/promises";function Et(){try{let t=Intl.DateTimeFormat().resolvedOptions().timeZone;return t&&t.length>0?t:"Etc/UTC"}catch{return"Etc/UTC"}}function Wr(t){return t?.dir??y()}async function T(t){let e=Wr(t);try{let r=await fc(Gr(e,Jr),"utf8"),n=JSON.parse(r),s=n.timeZone;return{...n,lastSettingsRevision:n.lastSettingsRevision??0,get timeZone(){return s??=Et()},bonusActive:n.bonusActive??!1,...n.bonusResetAt!==void 0?{bonusResetAt:n.bonusResetAt}:{}}}catch{return null}}async function rr(t,e){let r=Wr(e);await dc(r,{recursive:!0}),t.installedAt==null&&(t.installedAt=Math.floor(Date.now()/1e3));let n=Gr(r,Jr),s=`${n}.tmp-${process.pid}-${process.hrtime.bigint()}`;await mc(s,JSON.stringify(t,null,2),{mode:384});try{await pc(s,n)}catch(o){try{await Ss(s)}catch{}throw o}}async function nr(t){let e=Wr(t);try{await Ss(Gr(e,Jr))}catch{return}}var Jr,pe=E(()=>{"use strict";D();Jr="state.json"});import{createRequire as hc}from"node:module";function yc(){for(let t of["../package.json","../../package.json"])try{let e=gc(t).version;if(typeof e=="string"&&e)return e}catch{}return"0.0.0"}function ct(t,e){if(!t||!e)return!1;let r=t.split(".").map(s=>parseInt(s,10)),n=e.split(".").map(s=>parseInt(s,10));for(let s=0;s<3;s+=1){let o=r[s]??0,i=n[s]??0;if(Number.isNaN(o)||Number.isNaN(i))return!1;if(o<i)return!0;if(o>i)return!1}return!1}var gc,Q,ut=E(()=>{"use strict";gc=hc(import.meta.url);Q=yc()});var Es,Ts=E(()=>{"use strict";Es=`-----BEGIN PUBLIC KEY-----
|
|
3
|
+
var Ki=Object.defineProperty;var S=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Q=(t,e)=>{for(var r in e)Ki(t,r,{get:e[r],enumerable:!0})};var x,jr,p,se,yt=S(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(x||(x={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(jr||(jr={}));p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),se=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}}});var d,Gi,L,Kt=S(()=>{yt();d=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"]),Gi=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),L=class t 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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))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=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};L.create=t=>new L(t)});var Ji,ce,zr=S(()=>{Kt();yt();Ji=(t,e)=>{let r;switch(t.code){case d.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:x.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case d.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case d.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=e.defaultError,x.assertNever(t)}return{message:r}},ce=Ji});function Yi(t){is=t}function We(){return is}var is,Gt=S(()=>{zr();is=ce});function m(t,e){let r=We(),n=wt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ce?void 0:ce].filter(s=>!!s)});t.common.issues.push(n)}var wt,Wi,O,b,Ae,N,Jt,Yt,ge,qe,Ur=S(()=>{Gt();zr();wt=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},Wi=[];O=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return b;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return b;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},b=Object.freeze({status:"aborted"}),Ae=t=>({status:"dirty",value:t}),N=t=>({status:"valid",value:t}),Jt=t=>t.status==="aborted",Yt=t=>t.status==="dirty",ge=t=>t.status==="valid",qe=t=>typeof Promise<"u"&&t instanceof Promise});var as=S(()=>{});var h,cs=S(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}))});function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||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:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function fs(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ma(t){return new RegExp(`^${fs(t)}$`)}function ms(t){let e=`${ds}T${fs(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function pa(t,e){return!!((e==="v4"||!e)&&ia.test(t)||(e==="v6"||!e)&&ca.test(t))}function ha(t,e){if(!ra.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.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 ga(t,e){return!!((e==="v4"||!e)&&aa.test(t)||(e==="v6"||!e)&&ua.test(t))}function ya(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Xe(t){if(t instanceof F){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=J.create(Xe(n))}return new F({...t._def,shape:()=>e})}else return t instanceof de?new de({...t._def,type:Xe(t.element)}):t instanceof J?J.create(Xe(t.unwrap())):t instanceof ie?ie.create(Xe(t.unwrap())):t instanceof oe?oe.create(t.items.map(e=>Xe(e))):t}function Hr(t,e){let r=se(t),n=se(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=x.objectKeys(e),o=x.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Hr(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Hr(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ps(t,e){return new Fe({values:t,typeName:k.ZodEnum,...v(e)})}function ls(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function hs(t,e={},r){return t?we.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=ls(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=ls(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):we.create()}var Y,us,_,qi,Xi,Qi,ea,ta,ra,na,sa,oa,Zr,ia,aa,ca,ua,la,da,ds,fa,ye,Re,Ce,$e,Pe,Qe,Oe,Ie,we,le,ee,et,de,F,De,ue,Wt,Ne,oe,qt,tt,rt,Xt,Me,Le,Fe,je,be,W,J,ie,ze,Ue,nt,wa,bt,kt,Ze,ba,k,ka,gs,ys,va,_a,ws,xa,Sa,Ea,Ta,Aa,Ra,Ca,$a,Pa,Oa,Ia,Da,Na,Ma,La,Fa,ja,za,Ua,Za,Ha,Ba,Va,Ka,Ga,Ja,Ya,Wa,qa,Xa,Qa,ec,tc,rc,bs=S(()=>{Kt();Gt();cs();Ur();yt();Y=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,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}},us=(t,e)=>{if(ge(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new L(t.common.issues);return this._error=r,this._error}}};_=class{get description(){return this._def.description}_getType(e){return se(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new O,ctx:{common:e.parent.common,data:e.data,parsedType:se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(qe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:se(e)},s=this._parseSync({data:e,path:n.path,parent:n});return us(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:se(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ge(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ge(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:se(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(qe(s)?s:Promise.resolve(s));return us(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new W({schema:this,typeName:k.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:r=>this["~validate"](r)}}optional(){return J.create(this,this._def)}nullable(){return ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return de.create(this)}promise(){return be.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Ne.create(this,e,this._def)}transform(e){return new W({...v(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ze({...v(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new bt({typeName:k.ZodBranded,type:this,...v(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ue({...v(this._def),innerType:this,catchValue:r,typeName:k.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return kt.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qi=/^c[^\s-]{8,}$/i,Xi=/^[0-9a-z]+$/,Qi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ea=/^[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,ta=/^[a-z0-9_-]{21}$/i,ra=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,na=/^[-+]?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)?)??$/,sa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ia=/^(?:(?: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])$/,aa=/^(?:(?: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])$/,ca=/^(([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]))$/,ua=/^(([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])$/,la=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,da=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ds="((\\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])))",fa=new RegExp(`^${ds}$`);ye=class t extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.string,received:o.parsedType}),b}let n=new O,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")sa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Zr||(Zr=new RegExp(oa,"u")),Zr.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ea.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")ta.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Xi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:d.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:d.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?ms(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?fa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?ma(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?na.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?pa(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?ha(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"jwt",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ga(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cidr",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?la.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?da.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64url",code:d.invalid_string,message:o.message}),n.dirty()):x.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.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,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ye.create=t=>new ye({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...v(t)});Re=class t extends _{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)!==p.number){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.number,received:o.parsedType}),b}let n,s=new O;for(let o of this._def.checks)o.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?ya(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_finite,message:o.message}),s.dirty()):x.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.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,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Re.create=t=>new Re({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...v(t)});Ce=class t extends _{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)!==p.bigint)return this._getInvalidInput(e);let n,s=new O;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):x.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.bigint,received:r.parsedType}),b}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ce.create=t=>new Ce({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...v(t)});$e=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.boolean,received:n.parsedType}),b}return N(e.data)}};$e.create=t=>new $e({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...v(t)});Pe=class t extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.date,received:o.parsedType}),b}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_date}),b}let n=new O,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):x.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Pe.create=t=>new Pe({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...v(t)});Qe=class extends _{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.symbol,received:n.parsedType}),b}return N(e.data)}};Qe.create=t=>new Qe({typeName:k.ZodSymbol,...v(t)});Oe=class extends _{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.undefined,received:n.parsedType}),b}return N(e.data)}};Oe.create=t=>new Oe({typeName:k.ZodUndefined,...v(t)});Ie=class extends _{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.null,received:n.parsedType}),b}return N(e.data)}};Ie.create=t=>new Ie({typeName:k.ZodNull,...v(t)});we=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return N(e.data)}};we.create=t=>new we({typeName:k.ZodAny,...v(t)});le=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return N(e.data)}};le.create=t=>new le({typeName:k.ZodUnknown,...v(t)});ee=class extends _{_parse(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.never,received:r.parsedType}),b}};ee.create=t=>new ee({typeName:k.ZodNever,...v(t)});et=class extends _{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.void,received:n.parsedType}),b}return N(e.data)}};et.create=t=>new et({typeName:k.ZodVoid,...v(t)});de=class t extends _{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return m(r,{code:d.invalid_type,expected:p.array,received:r.parsedType}),b;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(m(r,{code:i?d.too_big:d.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(m(r,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(m(r,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Y(r,i,r.path,a)))).then(i=>O.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Y(r,i,r.path,a)));return O.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};de.create=(t,e)=>new de({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...v(e)});F=class t extends _{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(),r=x.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return m(u,{code:d.invalid_type,expected:p.object,received:u.parsedType}),b}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ee&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=o[u],g=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Y(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ee){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(m(s,{code:d.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let g=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Y(s,g,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let g=await l.key,w=await l.value;u.push({key:g,value:w,alwaysSet:l.alwaysSet})}return u}).then(u=>O.mergeObjectSync(n,u)):O.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of x.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Xe(this)}partial(e){let r={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof J;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return ps(x.objectKeys(this.shape))}};F.create=(t,e)=>new F({shape:()=>t,unknownKeys:"strip",catchall:ee.create(),typeName:k.ZodObject,...v(e)});F.strictCreate=(t,e)=>new F({shape:()=>t,unknownKeys:"strict",catchall:ee.create(),typeName:k.ZodObject,...v(e)});F.lazycreate=(t,e)=>new F({shape:t,unknownKeys:"strip",catchall:ee.create(),typeName:k.ZodObject,...v(e)});De=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new L(a.ctx.common.issues));return m(r,{code:d.invalid_union,unionErrors:i}),b}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new L(c));return m(r,{code:d.invalid_union,unionErrors:a}),b}}get options(){return this._def.options}};De.create=(t,e)=>new De({options:t,typeName:k.ZodUnion,...v(e)});ue=t=>t instanceof Me?ue(t.schema):t instanceof W?ue(t.innerType()):t instanceof Le?[t.value]:t instanceof Fe?t.options:t instanceof je?x.objectValues(t.enum):t instanceof ze?ue(t._def.innerType):t instanceof Oe?[void 0]:t instanceof Ie?[null]:t instanceof J?[void 0,...ue(t.unwrap())]:t instanceof ie?[null,...ue(t.unwrap())]:t instanceof bt||t instanceof Ze?ue(t.unwrap()):t instanceof Ue?ue(t._def.innerType):[],Wt=class t extends _{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return m(r,{code:d.invalid_type,expected:p.object,received:r.parsedType}),b;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(m(r,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=ue(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...v(n)})}};Ne=class extends _{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Jt(o)||Jt(i))return b;let a=Hr(o.value,i.value);return a.valid?((Yt(o)||Yt(i))&&r.dirty(),{status:r.value,value:a.data}):(m(n,{code:d.invalid_intersection_types}),b)};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(([o,i])=>s(o,i)):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}))}};Ne.create=(t,e,r)=>new Ne({left:t,right:e,typeName:k.ZodIntersection,...v(r)});oe=class t extends _{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return m(n,{code:d.invalid_type,expected:p.array,received:n.parsedType}),b;if(n.data.length<this._def.items.length)return m(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Y(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>O.mergeArray(r,i)):O.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};oe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:t,typeName:k.ZodTuple,rest:null,...v(e)})};qt=class t extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return m(n,{code:d.invalid_type,expected:p.object,received:n.parsedType}),b;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Y(n,a,n.path,a)),value:i._parse(new Y(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?O.mergeObjectAsync(r,s):O.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof _?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...v(n)}):new t({keyType:ye.create(),valueType:e,typeName:k.ZodRecord,...v(r)})}},tt=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return m(n,{code:d.invalid_type,expected:p.map,received:n.parsedType}),b;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Y(n,a,n.path,[u,"key"])),value:o._parse(new Y(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return b;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return b;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};tt.create=(t,e,r)=>new tt({valueType:e,keyType:t,typeName:k.ZodMap,...v(r)});rt=class t extends _{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return m(n,{code:d.invalid_type,expected:p.set,received:n.parsedType}),b;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return b;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Y(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};rt.create=(t,e)=>new rt({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...v(e)});Xt=class t extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return m(r,{code:d.invalid_type,expected:p.function,received:r.parsedType}),b;function n(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,We(),ce].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,We(),ce].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof be){let a=this;return N(async function(...c){let u=new L([]),l=await a._def.args.parseAsync(c,o).catch(E=>{throw u.addIssue(n(c,E)),u}),g=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(g,o).catch(E=>{throw u.addIssue(s(g,E)),u})})}else{let a=this;return N(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new L([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),g=a._def.returns.safeParse(l,o);if(!g.success)throw new L([s(l,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:oe.create(e).rest(le.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||oe.create([]).rest(le.create()),returns:r||le.create(),typeName:k.ZodFunction,...v(n)})}},Me=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Me.create=(t,e)=>new Me({getter:t,typeName:k.ZodLazy,...v(e)});Le=class extends _{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return m(r,{received:r.data,code:d.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}};Le.create=(t,e)=>new Le({value:t,typeName:k.ZodLiteral,...v(e)});Fe=class t extends _{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{expected:x.joinValues(n),received:r.parsedType,code:d.invalid_type}),b}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{received:r.data,code:d.invalid_enum_value,options:n}),b}return N(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Fe.create=ps;je=class extends _{_parse(e){let r=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=x.objectValues(r);return m(n,{expected:x.joinValues(s),received:n.parsedType,code:d.invalid_type}),b}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(r);return m(n,{received:n.data,code:d.invalid_enum_value,options:s}),b}return N(e.data)}get enum(){return this._def.values}};je.create=(t,e)=>new je({values:t,typeName:k.ZodNativeEnum,...v(e)});be=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return m(r,{code:d.invalid_type,expected:p.promise,received:r.parsedType}),b;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return N(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};be.create=(t,e)=>new be({type:t,typeName:k.ZodPromise,...v(e)});W=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{m(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return b;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?b:c.status==="dirty"?Ae(c.value):r.value==="dirty"?Ae(c.value):c});{if(r.value==="aborted")return b;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?b:a.status==="dirty"?Ae(a.value):r.value==="dirty"?Ae(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?b:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?b:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ge(i))return b;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ge(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):b);x.assertNever(s)}};W.create=(t,e,r)=>new W({schema:t,typeName:k.ZodEffects,effect:e,...v(r)});W.createWithPreprocess=(t,e,r)=>new W({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...v(r)});J=class extends _{_parse(e){return this._getType(e)===p.undefined?N(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};J.create=(t,e)=>new J({innerType:t,typeName:k.ZodOptional,...v(e)});ie=class extends _{_parse(e){return this._getType(e)===p.null?N(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ie.create=(t,e)=>new ie({innerType:t,typeName:k.ZodNullable,...v(e)});ze=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ze.create=(t,e)=>new ze({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});Ue=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qe(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ue.create=(t,e)=>new Ue({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});nt=class extends _{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.nan,received:n.parsedType}),b}return{status:"valid",value:e.data}}};nt.create=t=>new nt({typeName:k.ZodNaN,...v(t)});wa=Symbol("zod_brand"),bt=class extends _{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},kt=class t extends _{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?b:o.status==="dirty"?(r.dirty(),Ae(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?b:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:k.ZodPipeline})}},Ze=class extends _{_parse(e){let r=this._def.innerType._parse(e),n=s=>(ge(s)&&(s.value=Object.freeze(s.value)),s);return qe(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Ze.create=(t,e)=>new Ze({innerType:t,typeName:k.ZodReadonly,...v(e)});ba={object:F.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(k||(k={}));ka=(t,e={message:`Input not instance of ${t.name}`})=>hs(r=>r instanceof t,e),gs=ye.create,ys=Re.create,va=nt.create,_a=Ce.create,ws=$e.create,xa=Pe.create,Sa=Qe.create,Ea=Oe.create,Ta=Ie.create,Aa=we.create,Ra=le.create,Ca=ee.create,$a=et.create,Pa=de.create,Oa=F.create,Ia=F.strictCreate,Da=De.create,Na=Wt.create,Ma=Ne.create,La=oe.create,Fa=qt.create,ja=tt.create,za=rt.create,Ua=Xt.create,Za=Me.create,Ha=Le.create,Ba=Fe.create,Va=je.create,Ka=be.create,Ga=W.create,Ja=J.create,Ya=ie.create,Wa=W.createWithPreprocess,qa=kt.create,Xa=()=>gs().optional(),Qa=()=>ys().optional(),ec=()=>ws().optional(),tc={string:(t=>ye.create({...t,coerce:!0})),number:(t=>Re.create({...t,coerce:!0})),boolean:(t=>$e.create({...t,coerce:!0})),bigint:(t=>Ce.create({...t,coerce:!0})),date:(t=>Pe.create({...t,coerce:!0}))},rc=b});var f={};Q(f,{BRAND:()=>wa,DIRTY:()=>Ae,EMPTY_PATH:()=>Wi,INVALID:()=>b,NEVER:()=>rc,OK:()=>N,ParseStatus:()=>O,Schema:()=>_,ZodAny:()=>we,ZodArray:()=>de,ZodBigInt:()=>Ce,ZodBoolean:()=>$e,ZodBranded:()=>bt,ZodCatch:()=>Ue,ZodDate:()=>Pe,ZodDefault:()=>ze,ZodDiscriminatedUnion:()=>Wt,ZodEffects:()=>W,ZodEnum:()=>Fe,ZodError:()=>L,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>Xt,ZodIntersection:()=>Ne,ZodIssueCode:()=>d,ZodLazy:()=>Me,ZodLiteral:()=>Le,ZodMap:()=>tt,ZodNaN:()=>nt,ZodNativeEnum:()=>je,ZodNever:()=>ee,ZodNull:()=>Ie,ZodNullable:()=>ie,ZodNumber:()=>Re,ZodObject:()=>F,ZodOptional:()=>J,ZodParsedType:()=>p,ZodPipeline:()=>kt,ZodPromise:()=>be,ZodReadonly:()=>Ze,ZodRecord:()=>qt,ZodSchema:()=>_,ZodSet:()=>rt,ZodString:()=>ye,ZodSymbol:()=>Qe,ZodTransformer:()=>W,ZodTuple:()=>oe,ZodType:()=>_,ZodUndefined:()=>Oe,ZodUnion:()=>De,ZodUnknown:()=>le,ZodVoid:()=>et,addIssueToContext:()=>m,any:()=>Aa,array:()=>Pa,bigint:()=>_a,boolean:()=>ws,coerce:()=>tc,custom:()=>hs,date:()=>xa,datetimeRegex:()=>ms,defaultErrorMap:()=>ce,discriminatedUnion:()=>Na,effect:()=>Ga,enum:()=>Ba,function:()=>Ua,getErrorMap:()=>We,getParsedType:()=>se,instanceof:()=>ka,intersection:()=>Ma,isAborted:()=>Jt,isAsync:()=>qe,isDirty:()=>Yt,isValid:()=>ge,late:()=>ba,lazy:()=>Za,literal:()=>Ha,makeIssue:()=>wt,map:()=>ja,nan:()=>va,nativeEnum:()=>Va,never:()=>Ca,null:()=>Ta,nullable:()=>Ya,number:()=>ys,object:()=>Oa,objectUtil:()=>jr,oboolean:()=>ec,onumber:()=>Qa,optional:()=>Ja,ostring:()=>Xa,pipeline:()=>qa,preprocess:()=>Wa,promise:()=>Ka,quotelessJson:()=>Gi,record:()=>Fa,set:()=>za,setErrorMap:()=>Yi,strictObject:()=>Ia,string:()=>gs,symbol:()=>Sa,transformer:()=>Ga,tuple:()=>La,undefined:()=>Ea,union:()=>Da,unknown:()=>Ra,util:()=>x,void:()=>$a});var Br=S(()=>{Gt();Ur();as();yt();bs();Kt()});var st=S(()=>{Br();Br()});import{createHash as nc}from"node:crypto";function ke(t){let e=ks.get(t);return e||(e=nc("sha256").update(`tkr:${t}`).digest("hex").slice(0,16),ks.set(t,e)),e}var sc,oc,ot,ks,vt=S(()=>{"use strict";st();sc=f.enum(["normal","compact","minimal"]),oc=f.enum(["off","light","balanced","max"]),ot=f.object({enabled:f.boolean().default(!0),telemetryOptIn:f.boolean().default(!0),outputVerbosity:sc.default("compact"),reducer:oc.default("off"),filters:f.object({enableAll:f.boolean().default(!0),disabled:f.array(f.string().max(64)).max(100).default([])}).default({enableAll:!0,disabled:[]})}),ks=new Map});var _s={};Q(_s,{bundleRefreshFile:()=>_t,claudeCommandFile:()=>_e,claudeCommandsDir:()=>tr,contentCacheDir:()=>St,contentCacheFile:()=>Qt,enrollCooldownFile:()=>Vr,installIdFile:()=>it,managedCommandsFile:()=>er,skillFile:()=>ve,skillsDir:()=>xt,stateFile:()=>ic,tokmizerHome:()=>y});import vs from"node:os";import{join as q}from"node:path";function y(){return process.env.TOKMIZER_HOME||q(vs.homedir(),".tokmizer")}function ic(){return q(y(),"state.json")}function it(){return q(y(),"install-id")}function Vr(){return q(y(),"enroll-cooldown")}function _t(){return q(y(),"bundle-refresh.json")}function xt(){return q(y(),"skills")}function ve(t){return q(xt(),`${t}.md`)}function St(){return q(y(),"content-cache")}function Qt(t){return q(St(),t)}function er(){return q(y(),"managed-commands.json")}function tr(){return process.env.TOKMIZER_CLAUDE_COMMANDS_DIR||q(vs.homedir(),".claude","commands")}function _e(t){return q(tr(),`${t}.md`)}var I=S(()=>{"use strict"});import at from"node:os";import{createHash as ac,randomUUID as cc}from"node:crypto";import{readFile as xs,writeFile as Ss,mkdir as uc}from"node:fs/promises";async function rr(){try{let r=(await xs(it(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(r))return r}catch{}await uc(y(),{recursive:!0});let t=cc();try{return await Ss(it(),t,{mode:384,flag:"wx"}),t}catch{try{let e=(await xs(it(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(e))return e}catch{}return await Ss(it(),t,{mode:384}),t}}function Kr(t){return ac("sha256").update(t).digest("hex")}function lc(){let t=at.networkInterfaces();for(let e of Object.keys(t))for(let r of t[e]??[])if(!r.internal&&r.mac&&r.mac!=="00:00:00:00:00:00")return r.mac;return"no-mac"}async function X(){let t=await rr(),e=at.hostname(),r=at.platform(),n=at.release(),s=at.cpus(),o=s[0]?.model??"unknown",i=s.length,a=Kr(lc()),c=Kr(at.userInfo().username),u=[e,r,n,o,String(i),a,c,t].join("|");return{fingerprint:Kr(u),installId:t,hostname:e,os:r,osVersion:n,cpuModel:o,cpuCores:i,macHash:a,usernameHash:c}}var He=S(()=>{"use strict";I()});import{join as Gr}from"node:path";import{mkdir as dc,readFile as fc,writeFile as mc,unlink as Es,rename as pc}from"node:fs/promises";function Et(){try{let t=Intl.DateTimeFormat().resolvedOptions().timeZone;return t&&t.length>0?t:"Etc/UTC"}catch{return"Etc/UTC"}}function Yr(t){return t?.dir??y()}async function T(t){let e=Yr(t);try{let r=await fc(Gr(e,Jr),"utf8"),n=JSON.parse(r),s=n.timeZone;return{...n,lastSettingsRevision:n.lastSettingsRevision??0,get timeZone(){return s??=Et()},bonusActive:n.bonusActive??!1,...n.bonusResetAt!==void 0?{bonusResetAt:n.bonusResetAt}:{}}}catch{return null}}async function nr(t,e){let r=Yr(e);await dc(r,{recursive:!0}),t.installedAt==null&&(t.installedAt=Math.floor(Date.now()/1e3));let n=Gr(r,Jr),s=`${n}.tmp-${process.pid}-${process.hrtime.bigint()}`;await mc(s,JSON.stringify(t,null,2),{mode:384});try{await pc(s,n)}catch(o){try{await Es(s)}catch{}throw o}}async function sr(t){let e=Yr(t);try{await Es(Gr(e,Jr))}catch{return}}var Jr,fe=S(()=>{"use strict";I();Jr="state.json"});import{createRequire as hc}from"node:module";function yc(){for(let t of["../package.json","../../package.json"])try{let e=gc(t).version;if(typeof e=="string"&&e)return e}catch{}return"0.0.0"}function xe(t,e){if(!t||!e)return!1;let r=t.split(".").map(s=>parseInt(s,10)),n=e.split(".").map(s=>parseInt(s,10));for(let s=0;s<3;s+=1){let o=r[s]??0,i=n[s]??0;if(Number.isNaN(o)||Number.isNaN(i))return!1;if(o<i)return!0;if(o>i)return!1}return!1}var gc,B,ct=S(()=>{"use strict";gc=hc(import.meta.url);B=yc()});var Ts,As=S(()=>{"use strict";Ts=`-----BEGIN PUBLIC KEY-----
|
|
4
4
|
MCowBQYDK2VwAyEAj/kMlXlhTIGHRKxOKMuGFa1S1ybxxwgdYcAE0YM9fgU=
|
|
5
5
|
-----END PUBLIC KEY-----
|
|
6
|
-
`});import{createHmac as wc,createPublicKey as bc,verify as
|
|
7
|
-
`)}function _c(t,e,r,n){try{let s=bc({key:n,format:"pem"});return
|
|
8
|
-
`,Em=64*1024});var
|
|
9
|
-
`)}catch{}}function Su(t){try{mn(y(),{recursive:!0}),fn(hn(),String(Date.now()))}catch{}xu(`spawn failed: ${t.message}`)}function Eu(){try{hu(hn(),{force:!0})}catch{}}async function
|
|
6
|
+
`});import{createHmac as wc,createPublicKey as bc,verify as kc}from"node:crypto";function Tt(){return((process.env.TOKMIZER_DEV==="1"?process.env.TOKMIZER_RESP_SIGNING_PUBLIC_KEY_PEM:void 0)??Ts).replace(/\\n/g,`
|
|
7
|
+
`)}function _c(t,e,r,n){try{let s=bc({key:n,format:"pem"});return kc(null,Buffer.from(`${e}.${t}`,"utf8"),s,Buffer.from(r,"base64url"))}catch{return!1}}async function Ee(t){let e=await t.text(),r=Tt(),n=t.headers?.get?.("x-tokmizer-resp-ts")??null;if(n!==null){let i=Number(n);if(!Number.isFinite(i)||Date.now()-i>vc)throw new Se("http","stale server response (resp-ts outside freshness window)")}if(!r||!r.includes("BEGIN PUBLIC KEY"))throw new Se("http","no signing public key configured; refusing to trust server response");let s=t.headers?.get?.("x-tokmizer-resp-sig")??null,o=Number(n);if(!s||n===null||!Number.isFinite(o))throw new Se("http","missing server response signature");if(!_c(e,o,s,r))throw new Se("http","invalid server response signature");return JSON.parse(e)}function xc(t,e,r){return wc("sha256",r).update(`${e}.${t}`).digest("hex")}async function j(t,e,r,n){let s=Date.now(),o=r===void 0?"":JSON.stringify(r),i=n.signingSecret?xc(o,s,n.signingSecret):"0".repeat(64),a={"content-type":"application/json","x-tokmizer-fingerprint":n.fingerprint,"x-tokmizer-install-id":n.installId,"x-tokmizer-sig":i,"x-tokmizer-ts":String(s),"x-tokmizer-plugin-version":B};n.bearer&&(a.authorization=`Bearer ${n.bearer}`);let c=n.timeoutMs??5e3,u=t!=="GET"&&t!=="DELETE",l={method:t,headers:a,signal:AbortSignal.timeout(c)};u&&(l.body=o);try{return await fetch(`${n.baseUrl}${e}`,l)}catch(g){let w=g.name;throw w==="TimeoutError"||w==="AbortError"?new Se("timeout",`${t} ${e} timed out after ${c}ms`):new Se("network",`${t} ${e} failed: ${g.message}`)}}var vc,Se,Be=S(()=>{"use strict";ct();As();vc=300*1e3;Se=class extends Error{constructor(r,n,s){super(n);this.kind=r;this.status=s;this.name="TransportError"}kind;status}});import{readFile as Ys,writeFile as Ws,mkdir as qs,chmod as Zc,rm as $t,rename as Xs,readdir as Hc}from"node:fs/promises";import{randomUUID as Bc}from"node:crypto";import{join as lt}from"node:path";import{setTimeout as Ks}from"node:timers/promises";async function z(){try{let t=await Ys(lt(y(),rn),"utf8"),e=JSON.parse(t);return ot.parse({...Gs,...e})}catch{return Gs}}async function nn(t){await qs(y(),{recursive:!0});let e=lt(y(),rn),r=`${e}.tmp-${process.pid}-${process.hrtime.bigint()}`;await Ws(r,JSON.stringify(t,null,2),{mode:384});try{await Zc(r,384),await Xs(r,e)}catch(n){try{await $t(r,{force:!0})}catch{}throw n}}async function Js(t){let e=[];for(let r of await Hc(t)){let n=/^([1-9]\d*)-[0-9a-f-]{36}\.json$/.exec(r);if(!n)continue;let s=lt(t,r);try{process.kill(Number(n[1]),0)}catch(o){let i=o.code;if(i==="ESRCH"){await $t(s,{force:!0});continue}if(i!=="EPERM")throw o}try{let o=JSON.parse(await Ys(s,"utf8"));if(!Number.isSafeInteger(o)||o<0)throw new Error("Invalid local settings lock");e.push({id:r,ticket:o})}catch(o){if(o.code!=="ENOENT")throw o}}return e}async function Qs(t){let e=Vc.parse(t),r=lt(y(),"settings-cache-locks");await qs(r,{recursive:!0,mode:448});let n=`${process.pid}-${Bc()}.json`,s=lt(r,n),o=`${s}.tmp`,i=performance.now()+3e3,a=async c=>{for(await Ws(o,String(c),{mode:384});;)try{await Xs(o,s);return}catch(u){let l=u.code;if(process.platform!=="win32"||l!=="EPERM"&&l!=="EBUSY"||performance.now()>=i)throw u;await Ks(10)}};try{await a(0);let c=Math.max(0,...(await Js(r)).map(u=>u.ticket))+1;if(!Number.isSafeInteger(c))throw new Error("Invalid local settings lock");for(await a(c);;){if(!(await Js(r)).some(l=>l.id!==n&&(l.ticket===0||l.ticket<c||l.ticket===c&&l.id<n))){let l=await z(),g=ot.parse({...l,...e,filters:{...l.filters,...e.filters}});return await nn(g),g}if(performance.now()>=i)throw new Error("Timed out waiting for local settings lock after 3 seconds; another process may still be updating settings");await Ks(10)}}finally{await Promise.all([$t(s,{force:!0}),$t(o,{force:!0})])}}async function eo(){try{await $t(lt(y(),rn),{force:!0})}catch{}}var rn,Gs,Vc,Pt=S(()=>{"use strict";vt();I();rn="settings-cache.json",Gs=ot.parse({}),Vc=ot.partial().extend({filters:ot.shape.filters.removeDefault().partial().optional()})});var ur,sn=S(()=>{"use strict";st();ur=f.object({slug:f.string().min(1).max(64),description:f.string().max(255).optional(),match_command:f.string().min(1),priority:f.number().int().default(50),strip_ansi:f.boolean().default(!1),strip_lines_matching:f.array(f.string()).default([]),keep_failures:f.boolean().default(!1),fold_passing:f.boolean().default(!1),fold_passing_threshold:f.number().int().positive().max(1e3).optional(),mask_abs_paths:f.boolean().default(!1),preserve_exact:f.boolean().default(!1),truncate_lines_at:f.number().int().positive().max(1e4).optional(),max_lines:f.number().int().positive().max(1e5).optional(),scale_with_level:f.boolean().default(!0),transform:f.string().max(64).optional(),on_empty:f.string().max(255).optional()})});function on(t){return JSON.stringify(t)+lr}function*so(t){let e=0;for(;;){let r=t.indexOf(lr,e);if(r<0)return;yield t.slice(e,r),e=r+1}}function Ot(){return`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Yc,Wc,qc,Xc,_m,xm,Sm,no,lr,Em,oo=S(()=>{"use strict";st();sn();Yc=f.object({id:f.string().min(1).max(64),op:f.literal("filter"),cmd:f.string().min(1).max(2048),plan:f.enum(["trial","smart","pro"]),allowed:f.array(f.string().min(1).max(64)).max(512).optional(),installId:f.string().min(1).max(64).optional()}),Wc=f.object({id:f.string().min(1).max(64),op:f.literal("ping")}),qc=f.object({id:f.string().min(1).max(64),op:f.literal("shutdown"),installId:f.string().min(1).max(64)}),Xc=f.object({id:f.string().min(1).max(64),op:f.literal("reload"),installId:f.string().min(1).max(64).optional()}),_m=f.discriminatedUnion("op",[Yc,Wc,qc,Xc]),xm=f.object({id:f.string(),ok:f.literal(!0),data:f.unknown()}),Sm=f.object({id:f.string(),ok:f.literal(!1),err:f.string(),retryAfterMs:f.number().int().nonnegative().optional()}),no=f.object({filter:ur.nullable(),cacheHit:f.boolean().optional()}),lr=`
|
|
8
|
+
`,Em=64*1024});var co={};Q(co,{IDLE_TIMEOUT_MS:()=>uu,PARENT_WATCH_INTERVAL_MS:()=>cu,cleanupStaleSocket:()=>dr,isParentAlive:()=>lu,socketPath:()=>dt});import Qc from"node:os";import{join as It}from"node:path";import{existsSync as eu,statSync as tu,lstatSync as io,unlinkSync as ru,mkdirSync as nu,chmodSync as su}from"node:fs";import{createHash as ou}from"node:crypto";function iu(t){let e=ou("sha256").update(y()).digest("hex").slice(0,8),r=It(Qc.tmpdir(),`tkr-${t}-${e}`),n=It(r,"d.sock");if(Buffer.byteLength(n)>an)throw new Error("Temporary directory path is too long for IPC");return ao(r,t),n}function au(t,e){try{let r=io(t);return r.isDirectory()&&r.uid===e&&(r.mode&63)===0}catch{return!1}}function ao(t,e){nu(t,{recursive:!0,mode:448});let r=io(t);if(!r.isDirectory()||r.uid!==e)throw new Error("Unsafe IPC directory");su(t,448)}function dt(){if(process.platform==="win32")return{path:`\\\\.\\pipe\\tokmizer-${process.env.USERNAME??"tokmizer"}`,isPipe:!0};let t=typeof process.getuid=="function"?process.getuid():0,e=process.env.XDG_RUNTIME_DIR;if(e&&au(e,t)){let s=It(e,`tokmizer-${t}.sock`);if(Buffer.byteLength(s)<=an)return{path:s,isPipe:!1}}let r=It(y(),"run"),n=It(r,"daemon.sock");return Buffer.byteLength(n)>an?{path:iu(t),isPipe:!1}:(ao(r,t),{path:n,isPipe:!1})}async function dr(){let{path:t,isPipe:e}=dt();if(e||!eu(t))return;try{if(!tu(t).isSocket())return}catch{return}let r=await import("node:net");if(!await new Promise(s=>{let o=r.createConnection(t),i=a=>{o.removeAllListeners();try{o.destroy()}catch{}s(a)};o.once("connect",()=>i(!0)),o.once("error",a=>{let c=a.code;i(c!=="ECONNREFUSED"&&c!=="ENOENT")}),setTimeout(()=>i(!0),250)}))try{ru(t)}catch{}}function lu(){let t=process.ppid;if(!t||t===1)return!1;try{return process.kill(t,0),!0}catch{return!1}}var an,cu,uu,cn=S(()=>{"use strict";I();an=100;cu=3e4,uu=5*6e4});var ft={};Q(ft,{connectDaemon:()=>ho,shutdownDaemon:()=>po});import{createConnection as du}from"node:net";import{spawn as fu}from"node:child_process";import{existsSync as fo,openSync as un,closeSync as uo,unlinkSync as dn,writeFileSync as fn,mkdirSync as mn,readFileSync as mu,appendFileSync as pu,rmSync as hu,statSync as gu}from"node:fs";import{dirname as yu,join as pn}from"node:path";import{fileURLToPath as wu}from"node:url";function hn(){return pn(y(),"daemon.spawn.fail")}function gn(){return pn(y(),"daemon.log")}function _u(){try{let t=Number(mu(hn(),"utf8"));return Number.isFinite(t)&&Date.now()-t<ku}catch{return!1}}function xu(t){try{mn(y(),{recursive:!0});let e=gn();try{gu(e).size>vu&&dn(e)}catch{}pu(e,`${new Date().toISOString()} ${t}
|
|
9
|
+
`)}catch{}}function Su(t){try{mn(y(),{recursive:!0}),fn(hn(),String(Date.now()))}catch{}xu(`spawn failed: ${t.message}`)}function Eu(){try{hu(hn(),{force:!0})}catch{}}async function fr(t,e){return new Promise((r,n)=>{let s=du(t),o=a=>{if(s.removeAllListeners("connect"),s.removeAllListeners("error"),clearTimeout(i),a){try{s.destroy()}catch{}n(a)}else r(s)},i=setTimeout(()=>o(new Error("connect timeout")),e);s.once("connect",()=>o(null)),s.once("error",a=>o(a))})}function Tu(){return process.env.TOKMIZER_DAEMON_BIN?process.env.TOKMIZER_DAEMON_BIN:wu(new URL("../bin/tkr-daemon.js",import.meta.url))}async function ln(t,e=3e3){let r=Math.ceil(e/75),n=process.platform==="win32";for(let s=0;s<r;s++){if(n)try{return(await fr(t,75)).destroy(),!0}catch{}else if(fo(t))return!0;await new Promise(o=>setTimeout(o,75))}return!1}async function Au(t){let e=Tu();if(!fo(e))throw new Error(`tkr-daemon binary not found at ${e}`);let{path:r}=dt(),n=process.platform==="win32"?y():yu(r);try{mn(n,{recursive:!0})}catch{}let s=pn(n,"daemon.spawn.lock"),o=null;try{o=un(s,"wx"),fn(o,String(process.pid))}catch(i){if(i.code==="EEXIST"){if(await ln(r,5e3))return;try{dn(s)}catch{}try{o=un(s,"wx"),fn(o,String(process.pid))}catch(c){if(c.code==="EEXIST"){await ln(r,5e3);return}throw c}}else throw i}try{let i=null;try{i=un(gn(),"a")}catch{}if(fu(process.execPath,[e],{detached:!0,stdio:["ignore","ignore",i??"ignore"],env:{...process.env,TOKMIZER_DAEMON_INSTALL_ID:t}}).unref(),i!==null)try{uo(i)}catch{}if(!await ln(r,3e3))throw new Error("tkr-daemon failed to bind socket within 3s")}finally{if(o!==null){try{uo(o)}catch{}try{dn(s)}catch{}}}}async function po(t={}){let{path:e}=t.socketPath?{path:t.socketPath}:dt(),r=await rr();try{let n=await fr(e,mo);n.write(on({id:Ot(),op:"shutdown",installId:r})),await new Promise(s=>setTimeout(s,150));try{n.destroy()}catch{}return!0}catch{return!1}}async function Ru(t,e){let r=Date.now()+e;for(;Date.now()<r;){try{(await fr(t,250)).destroy()}catch{return!0}await new Promise(n=>setTimeout(n,100))}return!1}async function ho(t={}){let{path:e}=t.socketPath?{path:t.socketPath}:dt(),r=await rr(),n=null,s=0,o=!1;for(;s<=lo;)try{n=await fr(e,mo),Eu();break}catch{if(s+=1,s>lo)throw new Error(`tkr-daemon unreachable at ${e}`);if(_u())throw new Error(`tkr-daemon spawn on cooldown (see ${gn()})`);await dr();try{await Au(r),o=!0}catch(l){throw Su(l),l}}if(!n)throw new Error("tkr-daemon: socket setup failed");let i=new Map,a="";n.setEncoding("utf8"),n.on("data",l=>{a+=l;let g=-1;for(let E=0;E<a.length;E++)a[E]===lr&&(g=E);if(g<0)return;let w=[];for(let E of so(a.slice(0,g+1)))w.push(E);a=a.slice(g+1);for(let E of w)if(E)try{let $=JSON.parse(E),Z=i.get($.id);if(!Z)continue;clearTimeout(Z.timer),i.delete($.id),Z.resolve($)}catch{}}),n.on("close",()=>{for(let l of i.values())clearTimeout(l.timer),l.reject(new Error("daemon socket closed"));i.clear()}),n.on("error",()=>{});function c(l){return new Promise((g,w)=>{if(n.destroyed||!n.writable){w(new Error("daemon socket closed"));return}let E=setTimeout(()=>{i.delete(l.id),w(new Error(`daemon request timeout (${l.op})`))},bu);i.set(l.id,{resolve:g,reject:w,timer:E}),n.write(on(l))})}let u={filter:async(l,g,w)=>{let E=await c({id:Ot(),op:"filter",cmd:l.slice(0,2048),plan:g,...w&&w.length>0?{allowed:w.slice(0,512)}:{},installId:r});if(!E.ok)return null;let $=no.safeParse(E.data);return $.success?$.data.filter:null},ping:async()=>{let l=await c({id:Ot(),op:"ping"});if(!l.ok)throw new Error(l.err);return l.data},reload:async()=>{let l=await c({id:Ot(),op:"reload",installId:r});if(!l.ok)throw new Error(l.err);return l.data},close:()=>{try{n.destroy()}catch{}}};if(!t.skipVersionCheck&&!o){let l=!1;try{let g=await u.ping();if(g.version&&xe(B,g.version))throw new Error(`newer daemon ${g.version} already running`);l=g.version!==B}catch(g){throw u.close(),g}if(l){try{await po(t.socketPath?{socketPath:t.socketPath}:{})}catch{}u.close();let g=await Ru(e,2e3);if(await dr(),!g)throw new Error("stale daemon still running after shutdown request");return ho({...t,skipVersionCheck:!0})}}return u}var mo,bu,lo,ku,vu,mt=S(()=>{"use strict";oo();cn();I();He();ct();mo=500,bu=3e3,lo=1,ku=6e4,vu=256*1024});import{readFileSync as Cu,renameSync as $u,statSync as Pu,writeFileSync as Ou}from"node:fs";function yn(t,e,r){try{if(Pu(t).size<=e)return;let n=Cu(t,"utf8").split(`
|
|
10
10
|
`).filter(a=>a.trim()!==""),s=[],o=0;for(let a=n.length-1;a>=0;a-=1){let c=n[a],u=Buffer.byteLength(c)+1;if(o+u>r)break;s.push(c),o+=u}s.reverse();let i=`${t}.tmp-${process.pid}`;Ou(i,s.length?`${s.join(`
|
|
11
11
|
`)}
|
|
12
|
-
`:"",{mode:384}),$u(i,t)}catch{}}var wn=
|
|
13
|
-
`),await Nu(u,e)}catch{return"error"}return i}function
|
|
14
|
-
`,{mode:384}),yn(e,
|
|
15
|
-
`,{mode:384}),sl(r,384)}catch{return}}function
|
|
12
|
+
`:"",{mode:384}),$u(i,t)}catch{}}var wn=S(()=>{"use strict"});var ko={};Q(ko,{codexHookCommand:()=>vn,codexHookInstalled:()=>bn,codexHooksFile:()=>pt,ensureCodexHook:()=>kn});import{readFile as Iu,writeFile as Du,rename as Nu,mkdir as Mu,copyFile as Lu}from"node:fs/promises";import{existsSync as go,readFileSync as Fu,accessSync as ju,constants as zu}from"node:fs";import{join as mr}from"node:path";import Uu from"node:os";function pt(){return mr(process.env.CODEX_HOME||mr(Uu.homedir(),".codex"),"hooks.json")}function bo(t){return(t.hooks??[]).find(e=>typeof e.command=="string"&&e.command.includes(wo))}function bn(){try{return(JSON.parse(Fu(pt(),"utf8")).hooks?.PreToolUse??[]).some(e=>bo(e)!=null)}catch{return!1}}async function kn(t){let e=pt(),r={},n=go(e);if(n)try{if(r=JSON.parse(await Iu(e,"utf8")),!r||typeof r!="object"||Array.isArray(r))return"error"}catch{return"error"}let s=r.hooks&&typeof r.hooks=="object"?r.hooks:{},o=Array.isArray(s.PreToolUse)?s.PreToolUse:[],i="added",a=o.map(bo).find(c=>c!=null);if(a){if(a.command===t)return"present";a.command=t,i="updated"}else o.push({matcher:"Bash",hooks:[{type:"command",command:t,timeout:10}]});s.PreToolUse=o,r.hooks=s;try{await Mu(mr(e,".."),{recursive:!0});let c=`${e}.tkr-bak`;n&&!go(c)&&await Lu(e,c);let u=`${e}.tmp-${process.pid}`;await Du(u,`${JSON.stringify(r,null,2)}
|
|
13
|
+
`),await Nu(u,e)}catch{return"error"}return i}function yo(t){return`'${t.replace(/'/g,"'\\''")}'`}function vn(t,e){if(process.platform!=="win32")for(let r of t.split(":")){if(!r||r.includes("node_modules"))continue;let n=mr(r,wo);try{return ju(n,zu.X_OK),yo(n)}catch{}}return`node ${yo(e)}`}var wo,_n=S(()=>{"use strict";wo="tkr-codex-hook"});var pr={};Q(pr,{autoUpdateEnabled:()=>En,claimSelfUpdateSlot:()=>Ro,defaultDeps:()=>el,maybeSpawnSelfUpdate:()=>rl,selfUpdate:()=>Xu,setAutoUpdate:()=>Wu});import{spawn as Eo}from"node:child_process";import{accessSync as Zu,constants as Hu,existsSync as Dt,mkdirSync as To,readFileSync as Ao,rmSync as Bu,writeFileSync as Sn,appendFileSync as Vu}from"node:fs";import{fileURLToPath as Ku}from"node:url";import{join as te}from"node:path";import Gu from"node:os";function En(){return process.env.TOKMIZER_AUTO_UPDATE==="0"?!1:!Dt(xn())}function Wu(t){if(t){Bu(xn(),{force:!0});return}To(y(),{recursive:!0,mode:448}),Sn(xn(),String(Date.now()))}function Ro(t=Date.now()){try{let e=Number(Ao(xo(),"utf8"));if(Number.isFinite(e)&&t-e<Ju)return!1}catch{}try{To(y(),{recursive:!0,mode:448}),Sn(xo(),String(t))}catch{return!1}return!0}function qu(t){try{let e=te(y(),"self-update.log");Vu(e,`${new Date().toISOString()} ${t}
|
|
14
|
+
`,{mode:384}),yn(e,_o,_o/2)}catch{}}async function Xu(t){if(!En())return["disabled"];let e=t.latest;if(!e||!vo.test(e))return["no-version"];let r=[],n=[],s=(await t.run("npm",["root","-g"]).catch(()=>({code:1,stdout:""}))).stdout.trim(),o=s?t.npmVersion(s):void 0;if(o)if(!xe(o,e))n.push(o);else if(!t.writable(s))r.push("npm needs permission");else{let a=await t.run("npm",["i","-g",`@tokmizer/plugin@${e}`,"--no-audit","--no-fund"]).catch(()=>({code:1,stdout:""})),c=t.npmVersion(s);a.code===0&&c===e?(r.push(`npm ${o} -> ${e}`),n.push(e)):r.push(`npm failed (${o})`)}if(process.platform!=="win32"){let a=await t.run("brew",["list","--versions","tokmizer"]).catch(()=>({code:1,stdout:""})),c=a.code===0?a.stdout.trim().split(/\s+/)[1]:void 0;if(c&&vo.test(c))if(!xe(c,e))n.push(c);else{let u=await t.run("brew",["upgrade","tokmizer"],{...process.env,HOMEBREW_NO_INSTALL_CLEANUP:"1"}).catch(()=>({code:1,stdout:""}));u.code===0?(r.push(`brew ${c} -> ${e}`),n.push(e)):/untrusted tap/i.test(u.stderr??"")?r.push("brew tap not trusted: run brew trust norwelltw/tokmizer"):r.push(`brew failed (${c})`)}}if(r.some(a=>a.includes("->"))&&await t.run("tkr",["shims-refresh"]).catch(()=>({code:1,stdout:""})),n.some(a=>!xe(a,Yu))&&t.codexInstalled()&&!Dt(So())){let a=await t.ensureCodexHook(s).catch(()=>"error");if(a!=="error"){try{Sn(So(),String(Date.now()))}catch{}r.push(`codex hook ${a}`)}}for(let a of r)qu(a);return r}function Qu(t,e,r){return new Promise(n=>{let s=Eo(t,e,{env:r??process.env,shell:process.platform==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),o="",i="";s.stdout?.on("data",c=>{o+=c.toString("utf8")}),s.stderr?.on("data",c=>{i.length<8192&&(i+=c.toString("utf8"))});let a=setTimeout(()=>s.kill("SIGTERM"),10*6e4);s.on("error",()=>{clearTimeout(a),n({code:127,stdout:""})}),s.on("close",c=>{clearTimeout(a),n({code:c??1,stdout:o,stderr:i})})})}function el(t){return{latest:t,run:Qu,npmVersion:e=>{try{let r=JSON.parse(Ao(te(e,"@tokmizer","plugin","package.json"),"utf8")).version;return typeof r=="string"?r:void 0}catch{return}},writable:e=>{try{return Zu(e,Hu.W_OK),!0}catch{return!1}},codexInstalled:()=>Dt(process.env.CODEX_HOME||te(Gu.homedir(),".codex")),ensureCodexHook:async e=>{let{ensureCodexHook:r,codexHookCommand:n}=await Promise.resolve().then(()=>(_n(),ko)),s=te(e,"@tokmizer","plugin","dist","bin","tkr-codex-hook.js"),o=n(process.env.PATH??"",s);return o.startsWith("node ")&&!Dt(s)?"error":r(o)}}}function tl(){let t=Ku(new URL(".",import.meta.url));for(let e of[te(t),te(t,"..")])if(Dt(te(e,"bin","tkr.js")))return e;return null}function rl(){try{if(!En())return;let t=tl();if(!t||!Ro())return;let e=Eo(process.execPath,[te(t,"bin","tkr.js"),"self-update"],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,TOKMIZER_SELF_UPDATE_CHILD:"1"}});e.on("error",()=>{}),e.unref()}catch{}}var vo,Ju,Yu,_o,xn,xo,So,hr=S(()=>{"use strict";I();ct();wn();vo=/^\d+\.\d+\.\d+$/,Ju=6*36e5,Yu="0.9.34",_o=64*1024,xn=()=>te(y(),"auto-update-off"),xo=()=>te(y(),"self-update-last"),So=()=>te(y(),"codex-hook-offered")});function Nt(t){let e=t;for(let[r,n]of nl)e=e.replace(r,n);return e}var nl,Tn=S(()=>{"use strict";nl=[[/(authorization\s*:\s*)([A-Za-z][A-Za-z0-9._-]*)\s+[^\s'"]+/gi,"$1$2 [REDACTED]"],[/(authorization\s*:\s*)[A-Za-z0-9._\-+/=]{8,}/gi,"$1[REDACTED]"],[/(bearer\s+)[A-Za-z0-9._\-+/=]{8,}/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-b|--cookie)[=\s]+['"]?)[^\s'";=]+=[^\s'";]+(?:\s*;\s*[^\s'";=]+=[^\s'";]+)*/gi,"$1[REDACTED]"],[/((?:^|[\s'"])(?:Set-)?Cookie\s*:\s*)[^\s'";=]+=[^\s'";]+(?:\s*;\s*[^\s'";=]+=[^\s'";]+)*/gi,"$1[REDACTED]"],[/(--?(?:password|passwd|passphrase|apipass|pass|pwd|token|api[-_]?key|secret|bearer|cookie|jwt)(?:-[a-z0-9]+)*[=\s]+)\S+/gi,"$1[REDACTED]"],[/((?:^|\s)-b[=\s]?['"]?)[^\s'"=]+=[^\s'"]+/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-u[=\s]?|(?:--user|-a)[=\s])['"]?[^\s:/'"]*:)(\/[^/\s'"][^\s'"]*|[^\s/'"0-9][^\s'"]*|[0-9][^\s'"]*[^\s'"0-9][^\s'"]*)/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-u[=\s]?|(?:--user|-a)[=\s])['"]?[^\s:/'"]*[^\s:/'"0-9][^\s:/'"]*:)(?:\/[^/\s'"]|[^\s/'"])[^\s'"]*/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-u[=\s]?|(?:--user|-a)[=\s])['"]?:)(?:\/[^/\s'"]|[^\s/'"])[^\s'"]*/gi,"$1[REDACTED]"],[/((?:[A-Za-z0-9]+-){0,8}(?:X-Api-Key|Private-Token|[A-Za-z0-9]+-(?:Token|Key|Auth|Secret))\s*:\s*)[^\s'"]+/gi,"$1[REDACTED]"],[/((?:^|[\s'"])(?:Set-)?Cookie\s*:\s*)[^\s'"]+/gi,"$1[REDACTED]"],[/(-i\s+)(\/[^\s]+|~\/[^\s]+|[A-Z]:\\[^\s]+)/g,"$1[REDACTED]"],[/([a-zA-Z][a-zA-Z0-9+.-]{0,31}:\/\/[^:/\s@]*:)[^\s@]+(@[^@/\s]+)/g,"$1[REDACTED]$2"],[/(AWS_(?:ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN)\s*=\s*)\S+/g,"$1[REDACTED]"],[/(GOOGLE_APPLICATION_CREDENTIALS\s*=\s*)\S+/g,"$1[REDACTED]"],[/(AZURE_(?:CLIENT_SECRET|TENANT_ID|CLIENT_ID)\s*=\s*)\S+/g,"$1[REDACTED]"],[/(sk-(?:proj-)?[A-Za-z0-9_-]{20,})/g,"sk-[REDACTED]"],[/\b(OPENAI_API_KEY\s*=\s*)\S+/g,"$1[REDACTED]"],[/\b(ANTHROPIC_API_KEY\s*=\s*)\S+/g,"$1[REDACTED]"],[/(sk-ant-[A-Za-z0-9_-]{20,})/g,"sk-ant-[REDACTED]"],[/\b(GH(?:_|ITHUB_)?TOKEN\s*=\s*)\S+/g,"$1[REDACTED]"],[/\b(GITLAB_TOKEN\s*=\s*)\S+/g,"$1[REDACTED]"],[/\b(SLACK_(?:BOT_)?TOKEN\s*=\s*)\S+/g,"$1[REDACTED]"],[/(xox[bpsoa]-[A-Za-z0-9-]{10,})/g,"xox[REDACTED]"],[/(xapp-[A-Za-z0-9-]{10,})/g,"[REDACTED]"],[/(sk_(?:test|live)_[A-Za-z0-9]{16,})/g,"sk_[REDACTED]"],[/(gh[a-z])_[A-Za-z0-9]{20,}/g,"$1_[REDACTED]"],[/(github_pat)_[A-Za-z0-9_]{20,}/g,"$1_[REDACTED]"],[/(gl(?:pat|rt|soat|imt|dt|ft|agent|oas|cbt|ptt))-[A-Za-z0-9_-]{16,}/g,"$1-[REDACTED]"],[/(npm_[A-Za-z0-9_-]{20,})/g,"npm_[REDACTED]"],[/(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA)[0-9A-Z]{16,}/g,"[REDACTED_AWS_KEY]"],[/AIza[A-Za-z0-9_-]{35}/g,"[REDACTED_GOOGLE_KEY]"],[/hv[sb]\.[A-Za-z0-9_-]{20,}/g,"[REDACTED_VAULT_TOKEN]"],[/dop_v1_[A-Za-z0-9]{40,}/g,"[REDACTED]"],[/dckr_pat_[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/pypi-[A-Za-z0-9_-]{16,}/g,"[REDACTED]"],[/rk_(?:live|test)_[A-Za-z0-9]{16,}/g,"[REDACTED]"],[/whsec_[A-Za-z0-9]{16,}/g,"[REDACTED]"],[/SG\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/(eyJ[A-Za-z0-9_-]{6,}(?:\.[A-Za-z0-9_-]{4,}){1,2})/g,"[REDACTED_JWT]"],[/-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\s\S]*?-----END[^\n]*-----|\r?\n[A-Za-z0-9+/=][A-Za-z0-9+/=\r\n]*)?/g,"[REDACTED_PEM]"],[/\b((?:--?)?[A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PASS|APIKEY|KEY|CRED|CREDS|CREDENTIAL|CREDENTIALS|AUTH|_PWD)[A-Za-z0-9_]*['"]?\s*=\s*)(?:"[^"]*"|'[^']*'|[^"'\s]\S*)/gi,"$1[REDACTED]"],[/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PASS|APIKEY|KEY|CRED|CREDS|CREDENTIAL|CREDENTIALS|_PWD)[A-Za-z0-9_]*['"]?\s*:\s*)(?:"[^"]*"|'[^']*'|[^\s'",}]+)/gi,"$1[REDACTED]"],[/((?:^|[\s'"{,])['"]?(?:[A-Za-z0-9_]+_)?auth['"]?\s*:\s*)(?:"[^"]*"|'[^']*'|[^\s'",}]+)/gi,"$1[REDACTED]"],[/(\bpwd\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^/~\s][^\s;'"]*)/gi,"$1[REDACTED]"],[/([=:]\s*["']?)[A-Za-z0-9_\-+/=]{40,}/g,"$1[REDACTED]"]]});import{join as yr}from"node:path";import{appendFileSync as $o,chmodSync as sl,existsSync as Mt,mkdirSync as Cn,readFileSync as On,renameSync as $n,rmdirSync as Po,statSync as In,unlinkSync as ht,utimesSync as ol,writeFileSync as Dn}from"node:fs";function Nn(t){return yr(Ft(),`${t}.lock`)}function al(t){let e=Nn(t);try{return Cn(Ft(),{recursive:!0,mode:448}),Cn(e),!0}catch{try{Date.now()-In(e).mtimeMs>il&&Po(e)}catch{return!1}return!1}}function cl(t){try{ol(Nn(t),new Date,new Date)}catch{return}}function ul(t){try{Po(Nn(t))}catch{return}}function Ft(){return yr(y(),"spool")}function gr(t){return yr(Ft(),`${t}.jsonl`)}function wr(t){return yr(Ft(),`${t}.pending.jsonl`)}function br(t,e){try{Cn(Ft(),{recursive:!0,mode:448});let r=gr(t);if(Mt(r)&&In(r).size>=Pn)return;$o(r,JSON.stringify(e)+`
|
|
15
|
+
`,{mode:384}),sl(r,384)}catch{return}}function Co(t,e){$o(t,On(e,"utf8"),{mode:384}),Dn(e,"",{mode:384});try{ht(e)}catch{return}}function ll(t){if(In(t).size<=Pn)return;let e=On(t,"utf8").split(`
|
|
16
16
|
`).filter(s=>s.trim()),r=0,n=[];for(let s=e.length-1;s>=0;s--){let o=e[s]??"";if(r+=Buffer.byteLength(o,"utf8")+1,r>Pn)break;n.unshift(o)}Dn(t,n.length?n.join(`
|
|
17
17
|
`)+`
|
|
18
|
-
`:"",{mode:384})}function dl(t){try{let e=
|
|
19
|
-
`))if(o.trim())try{s.push(JSON.parse(o))}catch{continue}return s.length===0?(
|
|
18
|
+
`:"",{mode:384})}function dl(t){try{let e=wr(t),r=gr(t),n=`${r}.merging`;if(Mt(n)&&Co(e,n),Mt(e))Mt(r)&&($n(r,n),Co(e,n));else{if(!Mt(r))return[];$n(r,e)}ll(e);let s=[];for(let o of On(e,"utf8").split(`
|
|
19
|
+
`))if(o.trim())try{s.push(JSON.parse(o))}catch{continue}return s.length===0?(ht(e),[]):s}catch{return[]}}function Oo(t){try{ht(wr(t))}catch{return}}function fl(t,e){if(e.length===0){Oo(t);return}let r=wr(t),n=`${r}.tmp`;Dn(n,e.map(s=>JSON.stringify(s)).join(`
|
|
20
20
|
`)+`
|
|
21
|
-
`,{mode:384}),$n(n,r)}async function
|
|
22
|
-
`)}async function Bl(t,e){if(V.platform()==="win32")return 0;try{if(await
|
|
23
|
-
`)}async function Je(t){let e=
|
|
21
|
+
`,{mode:384}),$n(n,r)}async function kr(t,e,r={}){if(Rn.has(t)||!al(t))return"fail";Rn.add(t);try{if(!(await z()).telemetryOptIn)return Lt(t),"empty";let n=dl(t);if(n.length===0)return"empty";let s=await T();if(!s)return"fail";if(r.requirePro&&s.plan!=="pro")return Oo(t),"ok";let o=r.baseUrl??process.env.TOKMIZER_BASE_URL??"https://tokmizer.com",i=await X();for(let a=0;a<n.length;a+=An){if(!(await z()).telemetryOptIn)return Lt(t),"empty";cl(t);let c=await j("POST",e,{events:n.slice(a,a+An)},{baseUrl:o,bearer:s.jwt,signingSecret:s.signingSecret,fingerprint:i.fingerprint,installId:i.installId});if(!c.ok)return c.status===401||c.status===403?"auth":"fail";fl(t,n.slice(a+An))}return"ok"}catch{return"fail"}finally{Rn.delete(t),ul(t)}}function Lt(t){try{ht(gr(t))}catch{}try{ht(`${gr(t)}.merging`)}catch{}try{ht(wr(t))}catch{return}}var Pn,An,il,Rn,vr=S(()=>{"use strict";I();fe();He();Be();Pt();Pn=512*1024,An=100,il=12e4,Rn=new Set});var Do={};Q(Do,{commandName:()=>_r,flushTelemetry:()=>kl,recordTelemetry:()=>Mn});function Io(t){let e=t.toLowerCase();return e.startsWith("git")||gl.has(e)}function _r(t){let e=t.trim().split(/\s+/).filter(a=>a.length>0),r=0;for(;r<e.length&&hl.test(e[r]??"");)r+=1;let n=e[r];if(!n||!ml.test(n)||n.length>wl||Io(n)||yl.test(n)||Nt(n)!==n)return"";let s=e[r+1];return s&&Io(s)?"":(s&&bl.has(n.toLowerCase())&&pl.test(s)?`${n} ${s}`:n).slice(0,64)}async function Mn(t){if(!t.telemetryOptIn)return;let e=_r(t.cmd),r=e&&Nt(e)===e?e:"other",n=t.sessionId?t.sessionId.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64):"";br("telemetry",{cmd:r,tokensSaved:Math.max(0,Math.round(t.tokensSaved)),...t.tokensRestored?{tokensRestored:Math.max(0,Math.round(t.tokensRestored))}:{},...t.rawTokens!=null?{rawTokens:Math.max(0,Math.round(t.rawTokens))}:{},optimized:t.optimized,...n?{sessionId:n}:{},...t.host?{host:t.host}:{}})}async function kl(t){return kr("telemetry","/api/v1/telemetry",{baseUrl:t})}var ml,pl,hl,gl,yl,wl,bl,xr=S(()=>{"use strict";Tn();vr();ml=/^[a-z0-9][a-z0-9._-]*$/i,pl=/^[a-z][a-z-]+$/,hl=/^[A-Za-z_][A-Za-z0-9_]*=/,gl=new Set(["gh","glab","gup","hub","gist"]),yl=/^(gh[a-z]_|github_pat_|gl(?:pat|rt|soat|imt|dt|ft|agent|oas)-|npm_|xox|sk-|sk_|eyj|a(?:kia|sia|gpa|ida|roa|npa)|aiza|hv[sb]\.)/i,wl=24,bl=new Set(["docker","podman","npm","pnpm","yarn","npx","bun","deno","cargo","rustup","go","pip","pip3","uv","poetry","brew","apt","apt-get","dnf","yum","pacman","kubectl","helm","terraform","aws","gcloud","az","systemctl","composer","bundle","gem","dotnet","prisma","tkr","rtk","token"])});var No={};Q(No,{flush:()=>_l,recordEvent:()=>vl});async function vl(t){if(t.plan!=="pro"||!(await z()).telemetryOptIn)return;let e=_r(t.cmd);!e||Nt(e)!==e||br("learn",{cmd:e,filterId:t.filterId==null?null:ke(t.filterId),rawBytes:t.rawBytes,filteredBytes:t.filteredBytes})}async function _l(t){return kr("learn","/api/v1/learn",{baseUrl:t,requirePro:!0})}var Mo=S(()=>{"use strict";xr();Tn();vr();vt();Pt()});function Bn(t){return Zn.filter(e=>Hn.has(e.host)===t).flatMap(e=>e.vars)}function Rr(t=process.env){let e=process.platform,r=e==="darwin"||e==="linux"||e==="win32"?e:"other",n=process.arch;for(let s of Zn)if(s.vars.some(o=>t[o]))return{host:s.host,source:"env",os:r,arch:n,shimRecommended:!Hn.has(s.host)};return{host:"shell",source:"fallback",os:r,arch:n,shimRecommended:!0}}function Bo(t){return Hn.has(t)?"native-hooks":"shell-shim"}var Zn,Zp,Hn,Vn=S(()=>{"use strict";Zn=[{host:"claude-code",vars:["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE","CLAUDE_CODE_VERSION","ANTHROPIC_CLAUDE_CODE"]},{host:"codex",vars:["CODEX_VERSION","CODEX_CLI","OPENAI_CODEX","CODEX_THREAD_ID","CODEX_SESSION_ID"]},{host:"cursor",vars:["CURSOR_VERSION","CURSOR_TRACE_ID"]},{host:"cline",vars:["CLINE_VERSION","CLINE_API_KEY"]},{host:"aider",vars:["AIDER_VERSION","AIDER_MODEL"]},{host:"gemini-cli",vars:["GEMINI_CLI_VERSION","GEMINI_API_KEY"]},{host:"windsurf",vars:["WINDSURF_VERSION","WINDSURF_USER"]},{host:"copilot",vars:["GITHUB_COPILOT_VERSION","COPILOT_INTEGRATION_ID"]}],Zp=[...Zn.map(t=>t.host),"shell"],Hn=new Set(["claude-code","codex"])});var Xo={};Q(Xo,{ensurePathInRc:()=>Zt,ensureShimPath:()=>Dr,envWithoutShimDir:()=>Zl,installShims:()=>Je,listShimmableCommands:()=>Hl,powershellProfilePath:()=>qo,powershellProfileSnippet:()=>Wo,refreshShimsIfStale:()=>Bl,refreshStaleShims:()=>Jo,resolveShimJsPath:()=>ae,shellRcLine:()=>pe,shimsDir:()=>D,shimsInstalled:()=>Ht,uninstallShims:()=>Jn,unixWrapperScript:()=>Or,windowsWrapperScript:()=>Yo});import{mkdir as Kn,writeFile as Ut,readFile as $r,unlink as Gn,chmod as Go,rename as jl}from"node:fs/promises";import{existsSync as Ge}from"node:fs";import{delimiter as Vo,join as M,dirname as Cr}from"node:path";import{fileURLToPath as zl}from"node:url";import{execFileSync as Ul}from"node:child_process";import V from"node:os";function D(){return M(y(),"shims")}function Zl(){let t=D(),e={...process.env},r=process.platform==="win32"?"Path":"PATH",s=(e[r]??e.PATH??"").split(Vo).filter(o=>o&&o!==t);return e[r]=s.join(Vo),r==="Path"&&(e.PATH=e[r]),e}function Ht(){try{let t=V.platform()==="win32";return Ge(M(D(),t?"git.cmd":"git"))}catch{return!1}}function Hl(){return[...Pr]}function zt(t){return`'${t.replace(/'/g,"'\\''")}'`}function Ko(t){return`"${t.map(e=>`\${${e}:-}`).join("")}"`}function Or(t,e){return["#!/bin/sh",`if [ -n ${Ko(Bn(!0))} ] || { [ -z ${Ko(Bn(!1))} ] && [ ! -t 1 ]; }; then`," set -f",` _tk_d=${zt(D())}`,` _tk_c=${zt(e)}`," _tk_o=$IFS; IFS=:; _tk_p=; _tk_x="," for _tk_e in $PATH; do",' [ -n "$_tk_e" ] || continue',' [ "$_tk_e" -ef "$_tk_d" ] && continue'," _tk_p=${_tk_p:+$_tk_p:}$_tk_e",' [ -z "$_tk_x" ] && [ -f "$_tk_e/$_tk_c" ] && [ -x "$_tk_e/$_tk_c" ] && _tk_x=$_tk_e/$_tk_c'," done"," IFS=$_tk_o; PATH=$_tk_p; export PATH; set +f",' [ -n "$_tk_x" ] || { echo "$_tk_c: command not found" >&2; exit 127; }',' exec "$_tk_x" "$@"',"fi",`exec node ${zt(t)} --as ${zt(e)} "$@"`,""].join(`
|
|
22
|
+
`)}async function Bl(t,e){if(V.platform()==="win32")return 0;try{if(await $r(M(D(),e),"utf8")===Or(t,e))return 0}catch{return 0}return Jo(t)}async function Jo(t){if(V.platform()==="win32")return 0;let e=D();if(!Ge(e))return 0;let r=0;for(let n of Pr){let s=M(e,n),o=Or(t,n),i;try{i=await $r(s,"utf8")}catch{continue}if(i===o)continue;let a=`${s}.${process.pid}.tmp`;try{await Ut(a,o,{mode:493}),await Go(a,493),await jl(a,s),r+=1}catch{try{await Gn(a)}catch{}}}return r}function Yo(t,e){return["@echo off",`node "${t}" --as "${e}" %*`,""].join(`\r
|
|
23
|
+
`)}async function Je(t){let e=D();await Kn(e,{recursive:!0,mode:448});let r=[],n=V.platform()==="win32";for(let s of Pr){let o=n?M(e,`${s}.cmd`):M(e,s);if(Ge(o))try{await Gn(o)}catch{}n?await Ut(o,Yo(t,s)):(await Ut(o,Or(t,s),{mode:493}),await Go(o,493)),r.push(s)}return r}async function Jn(){let t=D();if(!Ge(t))return 0;let e=0,r=V.platform()==="win32";for(let n of Pr){let s=r?M(t,`${n}.cmd`):M(t,n);try{await Gn(s),e+=1}catch{}}return e}function pe(t=!1){let e=t?`'${D().replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`:zt(D());return`${Ir}
|
|
24
24
|
${t?`set -gx PATH ${e} $PATH`:`export PATH=${e}:"$PATH"`}
|
|
25
|
-
`}async function Zt(t,e=!1){try{await Kn(
|
|
25
|
+
`}async function Zt(t,e=!1){try{await Kn(Cr(t),{recursive:!0});let r=Ge(t)?await $r(t,"utf8"):"";return r.includes(Ir)?"present":(await Ut(t,`${r.replace(/\n*$/,`
|
|
26
26
|
`)}
|
|
27
|
-
${
|
|
28
|
-
$env:Path = '${
|
|
29
|
-
`}function
|
|
27
|
+
${pe(e)}`,{mode:384}),"added")}catch{return"missing"}}function Wo(){return`${Ir}
|
|
28
|
+
$env:Path = '${D().replace(/'/g,"''")};' + $env:Path
|
|
29
|
+
`}function qo(){let t=V.platform()==="win32"?Ul("powershell.exe",["-NoProfile","-NonInteractive","-Command","[Environment]::GetFolderPath('MyDocuments')"],{encoding:"utf8",windowsHide:!0}).trim():M(V.homedir(),"Documents");return M(t||M(V.homedir(),"Documents"),"PowerShell","profile.ps1")}async function Dr(){if(V.platform()==="win32"){let o=M(V.homedir(),"Documents","PowerShell","profile.ps1"),i=Wo();try{o=qo();let a=!1;for(let c of[o,M(Cr(Cr(o)),"WindowsPowerShell","profile.ps1")]){await Kn(Cr(c),{recursive:!0});let u=Ge(c)?await $r(c,"utf8"):"";u.includes(Ir)||(await Ut(c,`${u.replace(/\n*$/,`
|
|
30
30
|
`)}
|
|
31
|
-
${i}`),a=!0)}return{status:a?"added":"present",target:o,manual:i}}catch{return{status:"missing",target:o,manual:i}}}let t=process.env.SHELL??"",e=t.endsWith("/fish"),r=e?".config/fish/config.fish":t.endsWith("/zsh")?".zshrc":t.endsWith("/bash")?".bashrc":".profile",n=
|
|
31
|
+
${i}`),a=!0)}return{status:a?"added":"present",target:o,manual:i}}catch{return{status:"missing",target:o,manual:i}}}let t=process.env.SHELL??"",e=t.endsWith("/fish"),r=e?".config/fish/config.fish":t.endsWith("/zsh")?".zshrc":t.endsWith("/bash")?".bashrc":".profile",n=M(V.homedir(),r),s=await Zt(n,e);if(t.endsWith("/bash")&&s!=="missing"){let o=[".bash_profile",".bash_login",".profile"].map(a=>M(V.homedir(),a)).find(Ge)??M(V.homedir(),".bash_profile"),i=await Zt(o);if(i==="missing")return{status:"missing",target:o,manual:pe()};if(i==="added")return{status:"added",target:o,manual:pe()}}return{status:s,target:n,manual:pe(e)}}function ae(){return process.env.TOKMIZER_SHIM_JS?process.env.TOKMIZER_SHIM_JS:zl(new URL("../bin/tkr-shim.js",import.meta.url))}var Pr,Ir,Nr=S(()=>{"use strict";I();Vn();Pr=["git","npm","yarn","pnpm","docker","kubectl","terraform","tofu","cargo","go","mvn","gradle","rg","grep","find","ls","cat","tail","head","ps","lsof","ssh","scp","rsync","curl","wget","jq","yq","make"];Ir="# tokmizer-shim PATH (managed by tokmizer)"});var Di={};Q(Di,{TAP_FORMULA_PATHS:()=>Oi,brewTapStatus:()=>fd,formulaWedged:()=>Ii});import{readFileSync as ld}from"node:fs";function Ii(t){return/^(?:<{7}|={7}|>{7})/m.test(t)}function fd(t=Oi){for(let e of t)try{return{path:e,wedged:Ii(ld(e,"utf8"))}}catch{}return null}var dd,Oi,Ni=S(()=>{"use strict";dd=["/opt/homebrew/Library/Taps","/usr/local/Homebrew/Library/Taps","/home/linuxbrew/.linuxbrew/Homebrew/Library/Taps"],Oi=dd.map(t=>`${t}/norwelltw/homebrew-tokmizer/Formula/tokmizer.rb`)});function Li(t,e,r,n=e){let s=Mi.get(n);s||(s=new Map,Mi.set(n,s));let o=JSON.stringify([t,r?[...r].sort():null]),i=s.get(o);if(i!==void 0)return i;let a=null;for(let c of e)r&&!r.has(ke(c.slug))||c.matchRegex.test(t)&&(!a||c.priority>a.priority)&&(a=c);if(s.size>=md){let c=s.keys().next().value;c&&s.delete(c)}return s.set(o,a),a}var Mi,md,Fi=S(()=>{"use strict";vt();Mi=new WeakMap,md=256});import{createCipheriv as Ch,createDecipheriv as pd,hkdfSync as hd,randomBytes as $h}from"node:crypto";function wd(t){return Buffer.from(hd("sha256",Buffer.from(t,"utf8"),gd,yd,32))}function ji(t,e){let r=wd(e),n=Buffer.from(t,"base64url"),s=n.subarray(0,12),o=n.subarray(12,28),i=n.subarray(28),a=pd("aes-256-gcm",r,s);return a.setAuthTag(o),Buffer.concat([a.update(i),a.final()]).toString("utf8")}var gd,yd,zi=S(()=>{"use strict";gd=Buffer.from("tokmizer-bundle-enc-v1"),yd=Buffer.from("rules-bundle")});import{chmodSync as bd,readFileSync as kd,writeFileSync as vd,mkdirSync as _d,renameSync as xd}from"node:fs";import{join as Ui}from"node:path";function ts(){return Ui(y(),"bundle-cache.json")}function Zi(t){try{let e=y();_d(e,{recursive:!0});let r={...t,fetchedAt:Date.now()},n=Ui(e,`bundle-cache.${process.pid}.tmp`);vd(n,JSON.stringify(r),{mode:384}),xd(n,ts()),bd(ts(),384)}catch{}}function Hi(){try{let t=kd(ts(),"utf8"),e=Sd.safeParse(JSON.parse(t));return e.success?e.data:null}catch{return null}}var Sd,Bi=S(()=>{"use strict";st();I();Sd=f.object({payload:f.string().min(1),signature:f.string().min(1),enc:f.literal("v1"),fetchedAt:f.number().int().nonnegative()})});var ss={};Q(ss,{BundleFetchError:()=>Bt,bundleExpired:()=>$d,fetchBundle:()=>Id,healOn401:()=>Od,maxBundleAgeMs:()=>rs,runtimeFromCache:()=>Dd,runtimeFromEnvelope:()=>ns});import{createPublicKey as Ed,verify as Td}from"node:crypto";function rs(){let t=Number(process.env.TOKMIZER_MAX_BUNDLE_AGE_MS);return Number.isFinite(t)&&t>0?t:Cd}function $d(t,e=Date.now()){return e-t.fetchedAt>rs()}function Pd(t,e){let r=Tt();if(!r||!r.includes("BEGIN PUBLIC KEY"))throw new Error("tkr-daemon: no valid signing public key configured (set TOKMIZER_RESP_SIGNING_PUBLIC_KEY_PEM at build time).");let n=Ed({key:r,format:"pem"});if(!Td(null,Buffer.from(t.payload,"utf8"),n,Buffer.from(t.signature,"base64url")))throw new Error("tkr-daemon: rules bundle signature invalid");return JSON.parse(ji(t.payload,e))}async function Od(t,e,r){if(t instanceof Bt&&(t.status===401||t.status===403))try{return await r.heartbeat(e),await r.fetchBundle(e)}catch(n){return r.log(`initial fetch failed after heartbeat: ${n.message}`),null}return r.log(`initial fetch failed: ${t.message}`),null}async function Id(t){let e=await T();if(!e||!e.jwt)throw new Error("tkr-daemon: not activated (no JWT)");if(!e.signingSecret)throw new Error("tkr-daemon: not activated (no signing secret)");let r=await j("GET","/api/v1/rules/bundle",void 0,{baseUrl:t,bearer:e.jwt,signingSecret:e.signingSecret,fingerprint:e.fingerprint??"0".repeat(64),installId:e.installId,timeoutMs:1e4});if(!r.ok)throw new Bt(r.status);let n=Rd.parse(await r.json()),s=ns(n,e.signingSecret);return Zi(n),s}function ns(t,e){let r=Pd(t,e),n=Ad.parse(r);if(Date.now()-n.signedAt>rs())throw new Error("tkr-daemon: rules bundle is stale");let s=new Map;for(let o of n.filters)s.set(o.slug,{...o,matchRegex:new RegExp(o.match_command)});return{bundleVersion:n.bundleVersion,signedAt:n.signedAt,ruleCount:s.size,startedAt:Date.now(),fetchedAt:Date.now(),selectFor:(o,i,a)=>Li(o,s.values(),a?new Set(a):null,s)}}async function Dd(){try{let t=Hi();if(!t)return null;let e=await T();return e?.signingSecret?ns(t,e.signingSecret):null}catch{return null}}var Ad,Rd,Cd,Bt,os=S(()=>{"use strict";st();sn();Fi();fe();Be();zi();Bi();Ad=f.object({bundleVersion:f.number().int().nonnegative(),signedAt:f.number().int(),filters:f.array(ur)}),Rd=f.object({payload:f.string().min(1),signature:f.string().min(1),enc:f.literal("v1")}),Cd=10080*60*1e3;Bt=class extends Error{status;constructor(e){super(`tkr-daemon: bundle fetch failed ${e}`),this.status=e}}});import Qo from"node:readline/promises";import{stdin as Yn,stdout as K}from"node:process";import Vl from"node:os";import{join as Kl}from"node:path";var H={welcome:"Link your Tokmizer account.",needToken:"Tokmizer already works on this device. Linking attaches it to your account.",getToken:"Sign in at tokmizer.com, then grab your key from your dashboard.",askToken:"Paste your dashboard key, then press Enter:",activating:"Linking...",activated:t=>`Linked. You are on the ${t} plan.`,failed:t=>`Activation failed: ${t}`,suspended:t=>`Your token is suspended. ${t}`,revoked:"Your token has been revoked. Contact support at tokmizer.com/contact",rotated:"Token rotated. Paste your new token from tokmizer.com/dashboard/token",offline:"Network required. Tokmizer needs an internet connection.",deviceCap:"Device limit reached. Manage devices at tokmizer.com/dashboard/devices"};function Fr(t,e){return t===null?e!==null?` \u26A0 engine offline \u2014 compression continues on ${e} cached rules (details: tkr doctor)
|
|
32
32
|
`:` \u26A0 optimizer engine offline \u2014 run: tkr doctor
|
|
33
|
-
`:t===0
|
|
34
|
-
`:""}
|
|
33
|
+
`:t===0?e!==null&&e>0?"":` \u26A0 optimizer engine reconnecting \u2014 savings resume shortly (details: tkr doctor)
|
|
34
|
+
`:""}vt();He();fe();Be();I();import{readFile as xl,writeFile as jo,mkdir as Sl}from"node:fs/promises";Be();fe();He();import{createPublicKey as Sc,verify as Ec}from"node:crypto";function Tc(t,e){let r=Tt();if(!r||!r.includes("BEGIN PUBLIC KEY"))throw new Error("Tokmizer plugin: no valid signing public key. Set TOKMIZER_RESP_SIGNING_PUBLIC_KEY_PEM or rebuild plugin against a prod key.");let n=Sc({key:r,format:"pem"});try{let s=Buffer.from(e,"base64url");return Ec(null,Buffer.from(t,"utf8"),n,s)}catch{return!1}}var Ac=/^[a-z0-9][a-z0-9-]*$/;async function Rs(t){let e=await T();if(!e)throw new Error("Plugin not activated.");let r=await X(),n=await j("GET","/api/v1/skills/bundle",void 0,{baseUrl:t,bearer:e.jwt,signingSecret:e.signingSecret,fingerprint:r.fingerprint,installId:r.installId,timeoutMs:8e3});if(!n.ok)throw new Error(`bundle fetch failed ${n.status}`);let s=await Ee(n),o=[];for(let i of s.bundles){if(!Ac.test(i.slug))throw new Error(`invalid bundle slug ${i.slug}`);let a=[...i.fragments].sort((c,u)=>c.position-u.position);for(let c of a)if(!Tc(c.body,c.hash))throw new Error(`fragment signature mismatch on ${i.slug}[${c.position}]`);o.push({slug:i.slug,version:i.version,body:a.map(c=>c.body).join(`
|
|
35
35
|
|
|
36
|
-
`)})}return o}
|
|
36
|
+
`)})}return o}I();import{chmod as qr,mkdir as or,readFile as At,writeFile as ir,stat as Xr,readdir as Rc,rm as $s}from"node:fs/promises";var Ps="managed-by: tokmizer",Wr=["tkr","tkr-gain","tkr-status","tkr-link","tkr-unlink","tkr-compression","tkr-telemetry","tkr-update","tkr-yolo"],Cc=["power","tkr-reducer"];async function Os(){try{let t=JSON.parse(await At(er(),"utf8"));return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}async function Is(t){try{await or(y(),{recursive:!0}),await ir(er(),JSON.stringify(t),{mode:384})}catch{}}var $c=3600*1e3,Cs=10080*60*1e3;function Ds(){let t=Number(process.env.TOKMIZER_MAX_BUNDLE_AGE_MS);return Number.isFinite(t)&&t>0?Math.min(t,Cs):Cs}async function Ns(t){try{let e=await Xr(ve(t)),r=Date.now()-e.mtimeMs;return r<$c&&r<=Ds()}catch{return!1}}async function Ms(t,e){await or(xt(),{recursive:!0}),await ir(ve(t),e,{mode:384}),await qr(ve(t),384)}async function Rt(t){let e=new Set(t),r;try{r=await Rc(xt())}catch{return}for(let n of r){if(!n.endsWith(".md"))continue;let s=n.slice(0,-3);if(!e.has(s))try{await $s(ve(s))}catch{}}}async function Ls(t,e){await or(tr(),{recursive:!0});try{if(!(await At(_e(t),"utf8")).includes(Ps))return}catch{}await ir(_e(t),e,{mode:384}),await qr(_e(t),384);let r=await Os();r.includes(t)||await Is([...r,t])}async function Ct(t){let e=new Set([...t,...Wr]),r=await Os(),n=new Set([...r,...Cc]);for(let s of n)if(!e.has(s))try{if(!(await At(_e(s),"utf8")).includes(Ps))continue;await $s(_e(s))}catch{}await Is(r.filter(s=>e.has(s)))}async function Fs(){let t=0;for(let e of Wr)await Qr(e)&&t++;return{installed:t,total:Wr.length}}async function Qr(t){try{return await Xr(_e(t)),!0}catch{return!1}}async function en(t){try{await or(y(),{recursive:!0}),await ir(_t(),JSON.stringify({at:Date.now(),error:t}),{mode:384}),await qr(_t(),384)}catch{}}async function ar(){try{return JSON.parse(await At(_t(),"utf8"))}catch{return null}}async function cr(t){try{let e=await Xr(ve(t));return Date.now()-e.mtimeMs>Ds()?null:await At(ve(t),"utf8")}catch{return null}}import{chmod as qf,mkdir as Xf,readFile as Mc,writeFile as Qf,stat as Zs,readdir as Lc,rm as Us,rename as em}from"node:fs/promises";I();import{join as Fc}from"node:path";I();import{randomUUID as Pc}from"node:crypto";import{readFileSync as Oc}from"node:fs";import{mkdir as Ic,rename as Dc,rm as js,writeFile as Nc}from"node:fs/promises";import{join as zs}from"node:path";function ut(){try{return Oc(zs(y(),"yolo-mode"),"utf8")==="on"}catch{return!1}}async function Ve(t){let e=y(),r=zs(e,"yolo-mode");if(!t){await js(r,{force:!0});return}await Ic(e,{recursive:!0,mode:448});let n=`${r}.tmp-${process.pid}-${Pc()}`;try{await Nc(n,"on",{mode:384,flag:"wx"}),await Dc(n,r)}finally{await js(n,{force:!0})}}var Hs=10080*60*1e3,jc=100*1024*1024,sm=2*1024*1024,zc=/^[0-9a-f]{8,64}$/i;function tn(t,e,r=process.env){let n=Number(r[t]);return Number.isFinite(n)&&n>0?n:e}async function Bs(t){if(!t)return{stderr:`usage: tkr restore <hash>
|
|
37
37
|
`,code:1};let e=await Uc(t);return e==null?{stderr:`tkr restore: no cached content for ${t}
|
|
38
|
-
`,code:1,restoredTokens:0}:{stdout:e,code:0,restoredTokens:Math.round(Buffer.byteLength(e,"utf8")/4)}}async function Uc(t){if(!zc.test(t))return null;try{let e=await
|
|
38
|
+
`,code:1,restoredTokens:0}:{stdout:e,code:0,restoredTokens:Math.round(Buffer.byteLength(e,"utf8")/4)}}async function Uc(t){if(!zc.test(t))return null;try{let e=await Zs(Qt(t));return Date.now()-e.mtimeMs>tn("TOKMIZER_CCR_MAX_AGE_MS",Hs)?null:await Mc(Qt(t),"utf8")}catch{return null}}async function Vs(){let t;try{t=await Lc(St())}catch{return}let e=tn("TOKMIZER_CCR_MAX_AGE_MS",Hs),r=tn("TOKMIZER_CCR_DIR_CAP_BYTES",jc),n=Date.now(),s=[];for(let i of t){let a=Fc(St(),i);try{let c=await Zs(a);n-c.mtimeMs>e?await Us(a):s.push({path:a,mtimeMs:c.mtimeMs,size:c.size})}catch{}}let o=s.reduce((i,a)=>i+a.size,0);if(!(o<=r)){s.sort((i,a)=>i.mtimeMs-a.mtimeMs);for(let i of s){if(o<=r)break;try{await Us(i.path),o-=i.size}catch{}}}}fe();He();Be();Pt();async function to(t,e){let r=await T();if(!r)throw new Error("Not activated. Run: tkr link");if(r.linked===!1){if(t==="GET")return{plan:r.plan,settings:await z()};let a=await Qs(e);return{plan:r.plan,settings:a}}let n=process.env.TOKMIZER_BASE_URL??"https://tokmizer.com",s=await X(),o=await j(t,"/api/v1/settings",e,{baseUrl:n,bearer:r.jwt,signingSecret:r.signingSecret,fingerprint:s.fingerprint,installId:s.installId,timeoutMs:8e3});if(!o.ok)throw new Error(`Settings ${t} failed: ${o.status}`);let i=await Ee(o);return await nn(i.settings),i}async function Ke(){return to("GET")}async function Te(t){return to("PATCH",t)}var Kc=new Set(["__proto__","constructor","prototype"]);function Gc(t,e,r){let n=e.split(".");if(n.some(o=>Kc.has(o)))throw new Error(`invalid settings key: ${e}`);let s=t;for(let o=0;o<n.length-1;o++){let i=n[o];(typeof s[i]!="object"||s[i]===null)&&(s[i]={}),s=s[i]}s[n[n.length-1]]=r}function Jc(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+$/.test(t))return Number.parseInt(t,10);if(t.startsWith("[")||t.startsWith("{"))try{return JSON.parse(t)}catch{}return t}function ro(t,e){let r=Jc(e),n={};return Gc(n,t,r),n}ct();var Lo="-command",Fo=3;async function Ln(){try{let{connectDaemon:t}=await Promise.resolve().then(()=>(mt(),ft)),e=await t();try{await e.reload()}finally{e.close()}}catch{}}async function Fn(t,e){if(!(!e&&await Ns("power"))){try{let r=await Rs(t),n=[],s=[];for(let o of r)if(o.slug.endsWith(Lo)){let i=o.slug.slice(0,-Lo.length);await Ls(i,o.body),s.push(i)}else await Ms(o.slug,o.body),n.push(o.slug);await Rt(n),await Ct(s),await en(null)}catch(r){await en(r instanceof Error?r.message:String(r))}try{await Vs()}catch{}}}async function El(t,e){let r;for(let n=0;n<e.attempts;n++)try{return await t()}catch(s){if(r=s,n===e.attempts-1)break;let o=500*Math.pow(3,n)+Math.floor(Math.random()*300);await new Promise(i=>setTimeout(i,o))}throw r}async function Sr(t){let e=await X(),r=Et(),n={token:t.token,...t.email?{email:t.email}:{},pluginVersion:B,timeZone:r,...e},s=await El(()=>j("POST","/api/v1/license/activate",n,{baseUrl:t.baseUrl,bearer:t.token,fingerprint:e.fingerprint,installId:e.installId,timeoutMs:1e4}),{attempts:3});if(!s.ok){if(s.status>=500)throw new Error("Tokmizer servers are temporarily unreachable. Try again in a minute.");let a=await s.text();throw Tl(a)==="device_cap"?new Error(H.deviceCap):new Error(H.failed(`${s.status} ${a}`))}let o=await Ee(s),i={token:t.token,jwt:o.jwt,signingSecret:o.signingSecret,plan:o.plan,status:o.status,trialEndsAt:o.trialEndsAt,subEndsAt:o.subEndsAt,jwtVersion:o.jwtVersion,installId:e.installId,fingerprint:e.fingerprint,pluginVersion:B,...t.email||o.boundEmail?{email:t.email??o.boundEmail??""}:{},timeZone:r,bonusActive:!1,linked:!0,lastHeartbeatOkAt:Date.now(),...Array.isArray(o.allowedFilters)&&o.allowedFilters.length>0?{allowedFilters:o.allowedFilters.map(ke)}:{}};return await nr(i),await Ln(),await Fn(t.baseUrl,!0),i}function Tl(t){try{let e=JSON.parse(t);return typeof e.code=="string"?e.code:null}catch{return null}}function Al(t){try{return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}catch{return new Date().toISOString().slice(0,10)}}async function jt(t,e){let r=await T();return r&&r.token!==t.token?!1:(await nr(e),!0)}async function jn(t){let e=await T();if(!e)return null;let r=await X(),n=e.timeZone??Et(),s={ts:Date.now(),localDate:Al(n),timeZone:n},o;try{o=await j("POST","/api/v1/license/heartbeat",s,{baseUrl:t,bearer:e.jwt,signingSecret:e.signingSecret,fingerprint:r.fingerprint,installId:r.installId,timeoutMs:5e3})}catch{return e}if(o.status===401){let w=(e.heartbeatAuthFails??0)+1,E={...e,heartbeatAuthFails:w},$=e.linked??(!!e.email||e.plan==="smart"||e.plan==="pro");if(w>=Fo&&$&&(E.relinkRequired=!0),!await jt(e,E))return null;if(w>=Fo&&!$){try{await jo(`${y()}/state.replaced.json`,JSON.stringify(e),{mode:384})}catch{}try{return await zo(t)}catch{return null}}return null}if(o.status===451){let w=await T();if(w&&w.token!==e.token)return null;await sr();try{await Rt([]),await Ct([])}catch{}return null}if(o.status===426)return await jt(e,{...e,updateRequired:!0}),null;if(o.status===423)return await jt(e,{...e,relinkRequired:!0}),null;if(!o.ok){if(o.status===400)try{(await o.json())?.code==="stale_ts"&&await jt(e,{...e,clockSkewDetected:!0})}catch{}return e}let i;try{i=await Ee(o)}catch{return e}let a=i.settingsRevision??0,c=e.lastSettingsRevision??0,u=a>c,l=i.plan!==e.plan,g={...e,jwt:i.jwt,plan:i.plan,status:i.status,trialEndsAt:i.trialEndsAt,subEndsAt:i.subEndsAt,jwtVersion:i.jwtVersion,lastSettingsRevision:c,lastHeartbeatOkAt:Date.now(),heartbeatAuthFails:0,relinkRequired:!1,updateRequired:!1,clockSkewDetected:!1,timeZone:n,bonusActive:i.bonusActive??!1,...i.bonusResetAt!==void 0?{bonusResetAt:i.bonusResetAt}:{},...i.latestPluginVersion?{latestPluginVersion:i.latestPluginVersion}:{},...Array.isArray(i.allowedFilters)?{allowedFilters:i.allowedFilters.map(ke)}:{}};if(u)try{await Ke(),g.lastSettingsRevision=a}catch{}if(!await jt(e,g))return T();if(process.env.TOKMIZER_SELF_UPDATE_CHILD!=="1")try{let{maybeSpawnSelfUpdate:w}=await Promise.resolve().then(()=>(hr(),pr));w()}catch{}(u||l)&&await Ln(),await Fn(t,u||l);try{let{flushTelemetry:w}=await Promise.resolve().then(()=>(xr(),Do)),{flush:E}=await Promise.resolve().then(()=>(Mo(),No));await w(t),await E(t)}catch{}return g}var Rl=5*6e4;function Cl(){return process.env.TOKMIZER_BASE_URL??"https://tokmizer.com"}async function zo(t){let e=await X(),r=Et(),n={pluginVersion:B,timeZone:r,...e},s=await j("POST","/api/v1/license/enroll",n,{baseUrl:t,fingerprint:e.fingerprint,installId:e.installId,timeoutMs:4e3});if(!s.ok)throw new Error(`enroll failed ${s.status}`);let o=await Ee(s),i={token:o.token,jwt:o.jwt,signingSecret:o.signingSecret,plan:o.plan,status:o.status,trialEndsAt:o.trialEndsAt,subEndsAt:o.subEndsAt,jwtVersion:o.jwtVersion,installId:e.installId,fingerprint:e.fingerprint,pluginVersion:B,email:"",timeZone:r,bonusActive:!1,linked:!1,lastHeartbeatOkAt:Date.now(),...Array.isArray(o.allowedFilters)&&o.allowedFilters.length>0?{allowedFilters:o.allowedFilters.map(ke)}:{}};return await nr(i),await Ln(),await Fn(t,!0),i}function $l(){let t=process.env.CI;return t&&t!=="false"&&t!=="0"?!0:!!process.env.GITHUB_ACTIONS}async function me(t){let e=await T();if(e)return e;if($l())return null;let r=Vr();try{let n=await xl(r,"utf8"),s=Number(n);if(Number.isFinite(s)&&Date.now()-s<Rl)return null}catch{}try{return await zo(t??Cl())}catch{return await Sl(y(),{recursive:!0}),await jo(r,String(Date.now()),{mode:384}),null}}fe();import Ol from"node:readline/promises";import{stdin as Il,stdout as U}from"node:process";function Er(t,e=!1){return!0}fe();function Pl(){let t=Number(process.env.TOKMIZER_OFFLINE_GRACE_MS);return Number.isFinite(t)&&t>0?t:6048e5}function Uo(t,e=Date.now()){let r=t.lastHeartbeatOkAt;if(typeof r=="number"&&e-r>Pl())return!0;if(t.subEndsAt){let n=Date.parse(t.subEndsAt);if(Number.isFinite(n)&&e>n)return!0}return!1}function Tr(t,e=Date.now()){return t.plan}function Ar(t,e=Date.now()){return t.bonusActive??!1}var Dl={enabled:!0,outputVerbosity:"compact",filters:{enableAll:!0,disabled:[]}},Nl=`
|
|
39
39
|
Help improve Tokmizer
|
|
40
40
|
We can collect the NAME of the commands you run, like "git" or "docker",
|
|
41
41
|
and whether we managed to compress them. Never their arguments, your output,
|
|
@@ -43,129 +43,129 @@ your file paths, or anything inside them. It just shows us which commands to
|
|
|
43
43
|
optimize next, so you save even more over time. You can change this anytime
|
|
44
44
|
in your settings.
|
|
45
45
|
|
|
46
|
-
`;async function Ml(t){return
|
|
46
|
+
`;async function Ml(t){return U.write(Nl),zn(t,"Share anonymous command names to help improve filters?",!0)}async function Zo(t,e,r){let n=(await t.question(`${e} [${r}]: `)).trim();return n.length===0?r:n}async function zn(t,e,r){let n=r?"Y/n":"y/N",s=(await t.question(`${e} [${n}]: `)).trim().toLowerCase();return s===""?r:s==="y"||s==="yes"}async function Ll(t,e,r,n){let s=(await t.question(`${e} (${r.join(" / ")}) [${n}]: `)).trim().toLowerCase();return s.length===0?n:r.find(i=>i===s)??n}async function Fl(t,e,r){U.write(`
|
|
47
47
|
Let us walk through each setting. Press Enter to keep the default.
|
|
48
48
|
|
|
49
|
-
`);let n=await zn(t,"Enable Tokmizer optimizations?",!0),s=await Ll(t,"Output verbosity",["normal","compact","minimal"],"normal"),o=await zn(t,"Enable all built-in filters?",!0),i=[];o||(i=(await
|
|
49
|
+
`);let n=await zn(t,"Enable Tokmizer optimizations?",!0),s=await Ll(t,"Output verbosity",["normal","compact","minimal"],"normal"),o=await zn(t,"Enable all built-in filters?",!0),i=[];o||(i=(await Zo(t,"Comma-separated slugs to DISABLE (e.g. git,grep)","")).split(",").map(u=>u.trim()).filter(u=>u.length>0));let a={enabled:n,outputVerbosity:s,filters:{enableAll:o,disabled:i}};return Er(e,r)?U.write(`
|
|
50
50
|
/power is available right now on this token.
|
|
51
|
-
`):e==="smart"&&
|
|
51
|
+
`):e==="smart"&&U.write(`
|
|
52
52
|
/power is included with Pro.
|
|
53
53
|
It is NOT available on this token today.
|
|
54
|
-
`),a}async function Un(t,e=!1){let r=Ol.createInterface({input:Il,output:
|
|
54
|
+
`),a}async function Un(t,e=!1){let r=Ol.createInterface({input:Il,output:U});try{let n=e?" (bonus window active)":"";U.write(`
|
|
55
55
|
Configure Tokmizer (current plan: ${t}${n})
|
|
56
56
|
|
|
57
|
-
`),
|
|
58
|
-
`),
|
|
57
|
+
`),U.write(` 1) Recommended - sane defaults, ready to go
|
|
58
|
+
`),U.write(` 2) Custom - walk through each option
|
|
59
59
|
|
|
60
|
-
`);let o=await
|
|
60
|
+
`);let o=await Zo(r,"Choose 1 or 2","1")==="2"?await Fl(r,t,e):{...Dl},i=await Ml(r),a={...o,telemetryOptIn:i};U.write(`
|
|
61
61
|
Saving...
|
|
62
|
-
`);let c=await Te(a);await Ve(!1),
|
|
63
|
-
`),
|
|
64
|
-
`),
|
|
65
|
-
`),
|
|
62
|
+
`);let c=await Te(a);await Ve(!1),U.write(`Done.
|
|
63
|
+
`),U.write(`YOLO: off (this machine only)
|
|
64
|
+
`),U.write(`${JSON.stringify(c.settings,null,2)}
|
|
65
|
+
`),U.write(`
|
|
66
66
|
You can re-run this any time with: tkr settings configure
|
|
67
|
-
`),
|
|
67
|
+
`),U.write((await T())?.linked===!1?`These settings are saved only on this machine.
|
|
68
68
|
`:`Or edit at: https://tokmizer.com/dashboard/settings
|
|
69
|
-
`)}finally{r.close()}}async function
|
|
70
|
-
`);return}let r=
|
|
71
|
-
${
|
|
72
|
-
${
|
|
69
|
+
`)}finally{r.close()}}async function Ho(){let t=await Ke(),e=await T(),r=e?Tr({...e,plan:t.plan}):t.plan,n=e?Ar(e):!1;await Un(r,n)}Nr();async function ei(t){let e=await T();if(e){K.write(H.activated(e.plan)+`
|
|
70
|
+
`);return}let r=Qo.createInterface({input:Yn,output:K}),n=null,s=!1;try{K.write(`${H.welcome}
|
|
71
|
+
${H.needToken}
|
|
72
|
+
${H.getToken}
|
|
73
73
|
|
|
74
|
-
`);let o=(await r.question(`${
|
|
75
|
-
`);let i=await
|
|
74
|
+
`);let o=(await r.question(`${H.askToken} `)).trim();K.write(`${H.activating}
|
|
75
|
+
`);let i=await Sr({token:o,baseUrl:t});K.write(H.activated(i.plan)+`
|
|
76
76
|
`),n=i.plan,s=i.bonusActive??!1}catch(o){let i=o instanceof Error?o.message:String(o);K.write(`${i}
|
|
77
|
-
`),process.exitCode=1}finally{r.close()}n&&(await Un(n,s),await Gl())}async function Gl(){try{if(
|
|
77
|
+
`),process.exitCode=1}finally{r.close()}n&&(await Un(n,s),await Gl())}async function Gl(){try{if(Yn.isTTY){let t=Qo.createInterface({input:Yn,output:K});try{let e=(await t.question("Also optimize your commands outside the agent (terminal)? [y/N] ")).trim().toLowerCase();if(e==="y"||e==="yes"){let r=await Je(ae());K.write(`Installed ${r.length} shims.
|
|
78
78
|
`);let n=Kl(Vl.homedir(),(process.env.SHELL??"").includes("zsh")?".zshrc":".bashrc"),s=await Zt(n);s==="added"?K.write(`Added PATH to ${n}. Open a new terminal.
|
|
79
79
|
`):s==="missing"&&K.write(`Add this to your shell rc:
|
|
80
|
-
${
|
|
80
|
+
${pe()}`)}}finally{t.close()}}}catch{}try{let{connectDaemon:t}=await Promise.resolve().then(()=>(mt(),ft)),e=await t();await e.ping(),e.close(),K.write(` Engine: \u2705 active
|
|
81
81
|
`)}catch{K.write(` Engine: starts on first use
|
|
82
82
|
`)}K.write(`
|
|
83
83
|
\u2705 Ready. tokmizer optimizes your commands automatically.
|
|
84
84
|
Run "tkr gain" anytime to see your savings.
|
|
85
|
-
`)}
|
|
86
|
-
`).filter(u=>u.trim()!==""),o=s.length,i=0;for(;o>0;){let u=Buffer.byteLength(s[o-1])+1;if(i+u>r)break;i+=u,o-=1}let a=
|
|
85
|
+
`)}fe();ct();He();Be();Vn();I();import{readFile as oi,rm as ri}from"node:fs/promises";import{appendFileSync as Yl,chmodSync as Wl,mkdirSync as ql,readFileSync as ii,renameSync as ai,rmSync as ci,statSync as ui,writeFileSync as Xn}from"node:fs";import{dirname as Xl,join as li}from"node:path";var Wn={anthropic:3,openai:2.5,google:2,vertex:3.3,bedrock:3.5,openrouter:3.5},Jl={"claude-code":"anthropic",codex:"openai",copilot:"openai","gemini-cli":"google",cursor:"anthropic",windsurf:"anthropic",cline:"anthropic",aider:"anthropic",shell:"anthropic"};function ti(t){return t?Jl[t]??"anthropic":"anthropic"}function qn(t){let e=0,r=0;for(let n of Object.keys(t)){let s=t[n]??0;s<=0||(e+=s,r+=s/1e6*(Wn[n]??Wn.anthropic))}return e<=0?Wn.anthropic:r/(e/1e6)}var Ql="stats.jsonl",ed="stats-ledger.json",ni=2*1024*1024,td=3e4;function Mr(){return{n:0,nc:0,r:0,f:0,or:0,of:0,x:0,sn:0,sr:0,sf:0,mr:0,mf:0,rn:0,rb:0,tn:0,tr:0,tf:0,t0:null,t1:null,cmds:{},prov:{}}}function di(t){let e=t.trim();if(!e)return null;try{let r=JSON.parse(e);return typeof r.t!="number"||!Number.isFinite(r.t)||r.t<0||r.t>864e10||typeof r.r!="number"||!Number.isSafeInteger(r.r)||r.r<0||typeof r.f!="number"||!Number.isSafeInteger(r.f)||r.f<0||r.r+r.f===0?null:{t:r.t,r:r.r,f:r.f,m:r.m===1,...typeof r.h=="string"?{h:r.h}:{},...typeof r.k=="string"?{k:r.k}:{},...typeof r.c=="string"&&r.c?{c:r.c}:{}}}catch{return null}}function fi(t,e){if(e.m){t.mr+=e.r,t.mf+=e.f;return}if(e.k==="restore"&&(t.rn+=1,t.rb+=e.f),t.n+=1,t.or+=e.r,t.of+=e.f,e.f>e.r&&(t.x+=1),e.h==="shell"&&(t.tn+=1,t.tr+=e.r,t.tf+=e.f),t.t0=t.t0==null?e.t:Math.min(t.t0,e.t),t.t1=t.t1==null?e.t:Math.max(t.t1,e.t),e.c){let r=t.cmds[e.c]??{n:0,nc:0,r:0,f:0,sh:!1};r.n+=1,e.f<e.r&&(r.nc+=1,r.rr=(r.rr??0)+e.r,r.rf=(r.rf??0)+e.f),(e.k==="sh"||e.k==="restore")&&(r.sh=!0),r.r+=e.r,r.f+=e.f,t.cmds[e.c]=r}if(e.f<e.r){t.nc+=1,t.r+=e.r,t.f+=e.f,e.k==="sh"&&(t.sn+=1,t.sr+=e.r,t.sf+=e.f);let r=ti(e.h),n=t.prov[r]??{r:0,f:0};n.r+=e.r,n.f+=e.f,t.prov[r]=n}}function rd(t,e){for(let r of["n","nc","r","f","or","of","x","sn","sr","sf","mr","mf","rn","rb","tn","tr","tf"])t[r]+=e[r];e.t0!=null&&(t.t0=t.t0==null?e.t0:Math.min(t.t0,e.t0)),e.t1!=null&&(t.t1=t.t1==null?e.t1:Math.max(t.t1,e.t1));for(let[r,n]of Object.entries(e.cmds)){let s=t.cmds[r]??{n:0,nc:0,r:0,f:0,sh:!1};s.n+=n.n,s.nc+=n.nc,s.r+=n.r,s.f+=n.f,s.rr=(s.rr??0)+(n.rr??0),s.rf=(s.rf??0)+(n.rf??0),s.sh=s.sh||n.sh,t.cmds[r]=s}for(let[r,n]of Object.entries(e.prov)){let s=t.prov[r]??{r:0,f:0};s.r+=n.r,s.f+=n.f,t.prov[r]=s}}function Qn(t){let e=new Date(t*1e3);return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function es(t){return li(Xl(t),ed)}function mi(t){let e=es(t),r;try{r=ii(e,"utf8")}catch{return{}}try{let n=JSON.parse(r);if(!n.days||typeof n.days!="object")throw new Error("invalid ledger");let s={};for(let[o,i]of Object.entries(n.days))!/^\d{4}-\d{2}-\d{2}$/.test(o)||!i||typeof i!="object"||(s[o]={...Mr(),...i});return s}catch{try{ai(e,`${e}.corrupt-${Date.now()}`)}catch{}return{}}}function si(t,e){let r=`${t}.tmp-${process.pid}`;Xn(r,e,{mode:384}),ai(r,t)}function nd(t){try{return Xn(t,String(process.pid),{flag:"wx",mode:384}),!0}catch{}try{return Date.now()-ui(t).mtimeMs<td?!1:(ci(t,{force:!0}),Xn(t,String(process.pid),{flag:"wx",mode:384}),!0)}catch{return!1}}function sd(t,e=ni,r=ni/2){try{if(ui(t).size<=e)return}catch{return}let n=`${t}.lock`;if(nd(n))try{let s=ii(t,"utf8").split(`
|
|
86
|
+
`).filter(u=>u.trim()!==""),o=s.length,i=0;for(;o>0;){let u=Buffer.byteLength(s[o-1])+1;if(i+u>r)break;i+=u,o-=1}let a=mi(t);for(let u of s.slice(0,o)){let l=di(u);if(!l)continue;let g=Qn(l.t),w=a[g]??Mr();fi(w,l),a[g]=w}let c=s.slice(o);si(t,c.length?`${c.join(`
|
|
87
87
|
`)}
|
|
88
|
-
`:""),
|
|
89
|
-
`)){let i=
|
|
90
|
-
`).filter(n=>n.trim()!=="").length;return await
|
|
91
|
-
`;try{ql(y(),{recursive:!0,mode:448}),
|
|
92
|
-
Watch this session live: tkr session`;let r=t.
|
|
93
|
-
`)}async function
|
|
94
|
-
`)}
|
|
95
|
-
`).filter(r=>r.trim()!=="").length;return ad(t,{force:!0}),e}catch{return 0}}function
|
|
96
|
-
`).filter(o=>o.trim()!=="")}catch{return{sessionId:null,total:0,routed:0,pct:0}}e.length>
|
|
97
|
-
`)}vr();
|
|
88
|
+
`:""),si(es(t),JSON.stringify({v:1,days:a}))}catch{return}finally{ci(n,{force:!0})}}async function pi(t,e){let r=e>0?Qn(e):"",n=new Map;for(let[o,i]of Object.entries(mi(t)))o>=r&&n.set(o,i);let s="";try{s=await oi(t,"utf8")}catch{}for(let o of s.split(`
|
|
89
|
+
`)){let i=di(o);if(!i||i.t<e)continue;let a=Qn(i.t),c=n.get(a)??Mr();fi(c,i),n.set(a,c)}return n}function Lr(){return li(y(),Ql)}async function hi(t=Lr()){try{let r=(await oi(t,"utf8")).split(`
|
|
90
|
+
`).filter(n=>n.trim()!=="").length;return await ri(t,{force:!0}),await ri(es(t),{force:!0}),r}catch{return 0}}function gi(t,e,r=Lr(),n=!1,s,o,i){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e)||t<0||e<0||t+e===0)return;let a=s?`,"h":${JSON.stringify(s)}`:"",c=o?`,"k":${JSON.stringify(o)}`:"",u=i?`,"c":${JSON.stringify(i.slice(0,24))}`:"",l=`{"t":${Math.floor(Date.now()/1e3)},"r":${t},"f":${e}${n?',"m":1':""}${a}${c}${u}}
|
|
91
|
+
`;try{ql(y(),{recursive:!0,mode:448}),Yl(r,l,{mode:384}),Wl(r,384),sd(r)}catch{return}}function C(t){return Math.ceil(t/4)}function yi(t){if(!t.count)return null;let e=Math.round(t.compressedCount/t.count*100),r=(t.byCommand??[]).filter(s=>!s.native&&s.compressedCount===0).sort((s,o)=>o.count-s.count).slice(0,3).map(s=>s.cmd),n=r.length?` \xB7 top unchanged: ${r.join(", ")}`:"";return`${e}% of recorded outputs reduced (${t.compressedCount}/${t.count})${n}`}async function Ye(t=Lr(),e=0){let r=Mr();for(let P of(await pi(t,e)).values())rd(r,P);let n=C(r.r),s=C(r.f),o=Math.max(0,n-s),i=n?Math.round(o/n*100):0,a=Math.floor(Date.now()/1e3),c=r.t0!=null?Math.max(1,Math.ceil((a-r.t0)/86400)):1,u=Math.max(0,C(r.mr)-C(r.mf)),l={};for(let[P,R]of Object.entries(r.prov))l[P]=Math.max(0,C(R.r)-C(R.f));let g=Object.entries(r.cmds).map(([P,R])=>{let A=C(R.r),re=A-C(R.f),ne=C(R.rr??0),Vt=ne?Math.round((ne-C(R.rf??0))/ne*100):0;return{cmd:P,count:R.n,compressedCount:R.nc,savedTokens:re,avgPct:A?Math.round(re/A*100):0,reducedPct:Vt,native:!R.sh}}).sort((P,R)=>R.savedTokens-P.savedTokens).slice(0,10),w=C(r.sr),E=w?Math.round((w-C(r.sf))/w*100):0,$=C(r.or),Z=C(r.of);return{count:r.n,compressedCount:r.nc,rawTokens:n,filteredTokens:s,savedTokens:o,modeledSavedTokens:u,savedPct:i,sinceDays:c,savedByProvider:l,shellCompressedCount:r.sn,shellSavedPct:E,byCommand:g,observed:{count:r.n,rawTokens:$,filteredTokens:Z,savedTokens:$-Z,savedPct:r.or?Math.round((r.or-r.of)/r.or*1e4)/100:null,expandedCount:r.x},agent:{count:r.n-r.tn,rawTokens:C(r.or-r.tr),filteredTokens:C(r.of-r.tf),savedPct:r.or-r.tr?Math.round((r.or-r.tr-(r.of-r.tf))/(r.or-r.tr)*1e4)/100:null},terminal:{count:r.tn,rawTokens:C(r.tr),savedTokens:C(r.tr)-C(r.tf)},restoration:{count:r.rn,tokens:C(r.rb)},window:{firstAt:r.t0,lastAt:r.t1},measurement:{scope:"tool-output",legacyScope:"reduced-outputs",tokenMethod:"bytes/4",tokenCounts:"estimated",billing:"not-measured"}}}function he(t){return t<0?`-${he(-t)}`:t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":String(t)}function wi(t){return t<0?`-${wi(-t)}`:t>0&&t<.01?"<$0.01":`$${t.toFixed(2)}`}function gt(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}var bi="\x1B[38;2;245;176;65m",ki="\x1B[0m";function vi(t,e){let r="\u2588".repeat(t);return e?`${bi}${r}${ki}`:r}function _i(t,e){if(t.count===0)return` No data yet. Run a few commands to measure your output savings.
|
|
92
|
+
Watch this session live: tkr session`;let r=t.agent??{count:t.count,rawTokens:t.observed?.rawTokens??t.rawTokens,filteredTokens:t.observed?.filteredTokens??t.filteredTokens,savedPct:t.observed?.savedPct??t.savedPct},n=r.rawTokens-r.filteredTokens,s=r.rawTokens?Math.round(n/r.rawTokens*1e3)/10:0,o=w=>new Date(w*1e3).toISOString().slice(0,10),i=t.window?.firstAt!=null?` (since ${o(t.window.firstAt)})`:"",a=w=>` ${w.padEnd(16)}`,c=Math.max(0,Math.min(24,Math.round(Math.max(0,s)/100*24))),u=vi(c,e.color)+"\u2591".repeat(24-c),l=wi(n/1e6*e.pricePerMtok),g=t.terminal?.count??0;return[` Tokmizer savings \xB7 ${e.subtitle??"all time"}${i}`," "+"\u2550".repeat(60),"",`${a("Commands")}${gt(r.count)} \xB7 ${gt(t.compressedCount)} reduced`,`${a("Tokens in")}${he(r.rawTokens)}`,`${a("Tokens out")}${he(r.filteredTokens)}`,`${a(n>=0?"Tokens saved":"Tokens added")}${he(Math.abs(n))} (${Math.abs(s)} %)`,`${a("Efficiency")}${u} ${Math.max(0,s)} %`,...e.periods?.length?["",...e.periods.map(w=>`${a(w.label)}${he(w.savedTokens)} saved \xB7 ${gt(w.count)} commands`)]:[],`${a("API value")}${l} at $${e.pricePerMtok.toFixed(2)}/M input tokens`,...t.restoration?.count?[`${a("Restored")}${he(t.restoration.tokens)} tokens, deducted`]:[],...t.modeledSavedTokens>0?[`${a("Reducer (est.)")}${he(t.modeledSavedTokens)} tokens, not included`]:[],...od(t.byCommand,e.color),""," Estimates from output size (bytes \xF7 4), not your bill.",...g?[` ${gt(g)} terminal commands with no agent are not counted.`]:[],""].join(`
|
|
93
|
+
`)}async function xi(t=Lr(),e=0){return[...(await pi(t,e)).entries()].filter(([,r])=>r.n>0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({day:r,count:n.n,savedTokens:C(n.or)-C(n.of)}))}function od(t,e){let r=(t??[]).filter(i=>i.savedTokens>0).slice(0,10);if(r.length===0)return[];let n=r[0].savedTokens,s=" "+"\u2500".repeat(60),o=[""," By command",s,` ${" #".padEnd(4)}${"Command".padEnd(20)}${"Runs".padStart(7)}${"Saved".padStart(9)}${"Avg%".padStart(7)} Impact`,s];return r.forEach((i,a)=>{let c=Math.max(1,Math.round(i.savedTokens/n*10)),u=vi(c,e)+"\u2591".repeat(10-c),l=(i.native?`${i.cmd} (tool)`:i.cmd).slice(0,19);o.push(` ${(String(a+1)+".").padStart(3)} ${l.padEnd(20)}${gt(i.count).padStart(7)}${he(i.savedTokens).padStart(9)}${(String(i.avgPct)+" %").padStart(7)} ${u}`)}),o.push(s),o}function Si(t,e){if(t.length===0)return"";let r=(u,l,g)=>` ${u.padEnd(11)}${gt(l).padStart(4)}${he(g).padStart(13)}`,n=" "+"Day".padEnd(11)+"Cmds".padStart(4)+"Saved".padStart(13),s=" "+"\u2500".repeat(31),o=t.map(u=>r(`${u.day.slice(8,10)}/${u.day.slice(5,7)}`,u.count,u.savedTokens)),i=t.reduce((u,l)=>u+l.count,0),a=t.reduce((u,l)=>u+l.savedTokens,0),c=r("Total",i,a);return[n,s,...o,s,e.color?`${bi}${c}${ki}`:c,""].join(`
|
|
94
|
+
`)}I();wn();import{appendFileSync as gh,chmodSync as yh,mkdirSync as wh,existsSync as id,readFileSync as Ai,rmSync as ad}from"node:fs";import{dirname as kh,join as cd}from"node:path";var ud="usage.jsonl",Ei=2e4,xh=2*1024*1024;function Ri(){return cd(y(),ud)}function Ci(t=Ri()){try{if(!id(t))return 0;let e=Ai(t,"utf8").split(`
|
|
95
|
+
`).filter(r=>r.trim()!=="").length;return ad(t,{force:!0}),e}catch{return 0}}function Ti(t){let e=t.trim();if(!e)return null;try{let r=JSON.parse(e);return typeof r.t!="number"||typeof r.s!="string"||typeof r.o!="number"?null:{s:r.s,o:r.o}}catch{return null}}function $i(t=Ri()){let e;try{e=Ai(t,"utf8").split(`
|
|
96
|
+
`).filter(o=>o.trim()!=="")}catch{return{sessionId:null,total:0,routed:0,pct:0}}e.length>Ei&&(e=e.slice(e.length-Ei));let r=null;for(let o=e.length-1;o>=0;o-=1){let i=Ti(e[o]??"");if(i){r=i.s;break}}if(r===null)return{sessionId:null,total:0,routed:0,pct:0};let n=0,s=0;for(let o of e){let i=Ti(o);!i||i.s!==r||(n+=1,i.o===1&&(s+=1))}return{sessionId:r,total:n,routed:s,pct:n?Math.round(s/n*100):0}}function Pi(t){return t.total===0?" No commands yet this session.":[" This session"," "+"\u2500".repeat(40),` ${t.total} commands \xB7 ${t.routed} handled by tkr (${t.pct} %)`," The rest (cd, echo\u2026) has nothing to optimize.",""].join(`
|
|
97
|
+
`)}vr();xr();Pt();Nr();_n();import{fileURLToPath as Nd}from"node:url";var G=process.env.TOKMIZER_BASE_URL??"https://tokmizer.com";function Md(){process.stdout.write(["Usage: tkr <command>",""," link link your account (optional; paste your key)"," link <key> link without prompts"," link --shim [--shim-runner P] install shell-shims (universal compat)"," unlink unlink this machine from your account"," status show current plan + status"," gain [--day|--week|--month|--json] estimated tool-output savings (today / 7 days / 30 days / all time)"," session this session's tkr coverage"," restore <hash> re-fetch the full output behind a [tkr restore \u2026] hint"," discover what's covered (agent + terminal)"," setup-codex one-command setup for OpenAI Codex"," auto-update [on|off|status] keep the tkr CLI up to date on its own (on by default)"," doctor print detected host, OS, adapter"," shim install [--runner P] install shell-shims into ~/.tokmizer/shims"," shim uninstall remove shell-shims"," heartbeat refresh JWT + bundle"," settings show print current settings"," settings set <key> <value> update one setting (key uses dot path, e.g. filters.enableAll true)"," settings configure interactive wizard (recommended or custom)"," settings reset reset all settings to defaults"," compression [level] show or set compression level (light, balanced, max)"," yolo [on|off|status] local aggressive output reduction; content can be lost"," reducer [level] show or set response reducer (off, light, balanced, max)"," telemetry status show telemetry on/off + local record count"," telemetry on | off turn anonymous telemetry on or off"," telemetry forget erase telemetry data stored on this machine",""].join(`
|
|
98
98
|
`))}async function Ld(t){let e=t[0]??"show";if(e==="show"){try{let r=await Ke();process.stdout.write(`Plan: ${r.plan}
|
|
99
99
|
`),process.stdout.write(`${JSON.stringify(r.settings,null,2)}
|
|
100
100
|
`)}catch(r){process.stdout.write(`Settings unavailable; showing local cached settings: ${r instanceof Error?r.message:String(r)}
|
|
101
|
-
`),process.stdout.write(`${JSON.stringify(await
|
|
101
|
+
`),process.stdout.write(`${JSON.stringify(await z(),null,2)}
|
|
102
102
|
`)}return}if(e==="set"){let r=t[1],n=t[2];if(!r||n===void 0){process.stderr.write(`Usage: tkr settings set <key> <value>
|
|
103
|
-
`),process.exitCode=1;return}let s=
|
|
103
|
+
`),process.exitCode=1;return}let s=ro(r,n),o=await Te(s);process.stdout.write(`Updated. ${r} = ${JSON.stringify(n)}
|
|
104
104
|
`),process.stdout.write(`Current: ${JSON.stringify(o.settings,null,2)}
|
|
105
|
-
`);return}if(e==="configure"){await
|
|
105
|
+
`);return}if(e==="configure"){await Ho();return}if(e==="reset"){let r=await Te({enabled:!0,telemetryOptIn:!0,outputVerbosity:"compact",reducer:"off",filters:{enableAll:!0,disabled:[]}});await Ve(!1),process.stdout.write(`Settings reset to defaults.
|
|
106
106
|
`),process.stdout.write(`YOLO: off (this machine only)
|
|
107
107
|
`),process.stdout.write(`${JSON.stringify(r.settings,null,2)}
|
|
108
108
|
`);return}process.stderr.write(`Unknown settings subcommand: ${e}
|
|
109
109
|
`),process.exitCode=1}async function Fd(t){let e=t[0]??"status";if(e==="on"||e==="off"){let r=e==="on";try{let n=await Te({telemetryOptIn:r});process.stdout.write(`Telemetry ${n.settings.telemetryOptIn?"on":"off"}.
|
|
110
110
|
`)}catch(n){process.stdout.write(`${n instanceof Error?n.message:String(n)}
|
|
111
|
-
`),process.exitCode=1}return}if(e==="forget"){Lt("telemetry"),Lt("learn");let r=await
|
|
112
|
-
`);return}if(e==="status"){let r;try{r=(await Ke()).settings.telemetryOptIn?"on":"off"}catch{r=`${(await
|
|
111
|
+
`),process.exitCode=1}return}if(e==="forget"){Lt("telemetry"),Lt("learn");let r=await hi()+Ci();process.stdout.write(`Cleared ${r} local telemetry record${r===1?"":"s"} from this machine.
|
|
112
|
+
`);return}if(e==="status"){let r;try{r=(await Ke()).settings.telemetryOptIn?"on":"off"}catch{r=`${(await z()).telemetryOptIn?"on":"off"} (offline; last known)`}let n=await Ye();process.stdout.write(`Telemetry: ${r}
|
|
113
113
|
${n.count} commands recorded locally.
|
|
114
114
|
Manage: tkr telemetry on | off | forget
|
|
115
115
|
`);return}process.stderr.write(`Unknown telemetry subcommand: ${e}
|
|
116
116
|
`),process.exitCode=1}async function jd(){let t=process.argv[2]??"help",e=process.argv.slice(3);if(t==="yolo"){let r=e[0]??"status";if(e.length>1||!["on","off","status"].includes(r)){process.stderr.write(`Usage: tkr yolo [on|off|status]
|
|
117
117
|
`),process.exitCode=1;return}r==="on"?(process.stderr.write(`Warning: YOLO can discard content and diagnostics. Lost output cannot be restored; command exit codes are preserved.
|
|
118
|
-
`),await Ve(!0)):r==="off"&&await Ve(!1),process.stdout.write(`YOLO: ${
|
|
119
|
-
`);return}if(t==="init"||t==="link"){if(t==="init"&&process.stdout.write("`tkr init` is now `tkr link`. Running link...\n"),e.includes("--shim")){let i=e.indexOf("--shim-runner"),a=i>=0?e[i+1]:
|
|
118
|
+
`),await Ve(!0)):r==="off"&&await Ve(!1),process.stdout.write(`YOLO: ${ut()?"on":"off"} (this machine only)
|
|
119
|
+
`);return}if(t==="init"||t==="link"){if(t==="init"&&process.stdout.write("`tkr init` is now `tkr link`. Running link...\n"),e.includes("--shim")){let i=e.indexOf("--shim-runner"),a=i>=0?e[i+1]:ae(),c=await Je(a??ae());process.stdout.write(`Installed ${c.length} shims into ${D()}
|
|
120
120
|
`),process.stdout.write(`Add this line to your shell rc if not already:
|
|
121
|
-
${
|
|
122
|
-
`),process.exitCode=1;return}let i=r>=0?e[r+1]:"";try{let a=await
|
|
121
|
+
${pe()}`);return}let r=e.indexOf("--email"),n=e.indexOf("--token"),s=e.find(i=>i.startsWith("tokmizer_")),o=n>=0?e[n+1]??"":s??"";if(e.length>0){if(!o){process.stdout.write(`Usage: tkr link <key> (the key from tokmizer.com/dashboard/token, starts with tokmizer_)
|
|
122
|
+
`),process.exitCode=1;return}let i=r>=0?e[r+1]:"";try{let a=await Sr({token:o,baseUrl:G,...i?{email:i}:{}});process.stdout.write(H.activated(a.plan)+`
|
|
123
123
|
`),process.stdout.write(`Review this account's settings: tkr settings show. Adjust them with: tkr settings configure
|
|
124
|
-
`);let c=await
|
|
124
|
+
`);let c=await ar();c?.error&&process.stdout.write(`Note: feature sync failed (${c.error}). Run "tkr heartbeat" to retry.
|
|
125
125
|
`)}catch(a){process.stdout.write(`${a instanceof Error?a.message:String(a)}
|
|
126
|
-
`),process.exitCode=1}return}await
|
|
127
|
-
`);return}if(t==="doctor"){let r=
|
|
128
|
-
`),
|
|
129
|
-
`));return}if(t==="auto-update"){let{autoUpdateEnabled:r,setAutoUpdate:n}=await Promise.resolve().then(()=>(
|
|
126
|
+
`),process.exitCode=1}return}await ei(G);return}if(t==="unlink"){let r=await T();if(r?.jwt&&r.signingSecret)try{let s=await X();await j("POST","/api/v1/license/unlink",{ts:Date.now()},{baseUrl:G,bearer:r.jwt,signingSecret:r.signingSecret,fingerprint:s.fingerprint,installId:s.installId,timeoutMs:4e3})}catch{}await sr();try{await Rt([]),await Ct([])}catch{}await eo();try{let{shutdownDaemon:s}=await Promise.resolve().then(()=>(mt(),ft));await s()}catch{}let n=r?.email?` from ${r.email}`:"";process.stdout.write(`Unlinked this machine${n}. The plugin keeps working without an account; a fresh anonymous token starts on the next online run. Link another account with: tkr link
|
|
127
|
+
`);return}if(t==="doctor"){let r=Rr(),n=await Fs(),{brewTapStatus:s}=await Promise.resolve().then(()=>(Ni(),Di)),o=s(),i=o?.wedged?o.path.replace(/\/Formula\/tokmizer\.rb$/,""):null,a=[`Host: ${r.host} (source: ${r.source})`,`OS: ${r.os}`,`Arch: ${r.arch}`,`Adapter: ${Bo(r.host)}`,`Shim dir: ${D()}`,`Shim: ${Ht()?"installed":"not installed \u2014 run: tkr setup-codex"}`,`Codex: ${bn()?"hook installed":"hook not installed \u2014 run: tkr setup-codex"}`,`Commands: ${n.installed}/${n.total} unprefixed slash commands${n.installed<n.total?" \u2014 restart Claude Code to reinstall":""}`,`Restore: ${process.env.TOKMIZER_CCR_DISABLED==="1"||process.env.TOKMIZER_CCR_DISABLED==="true"?"disabled (TOKMIZER_CCR_DISABLED)":"active"}`,...i?[`Homebrew: tap clone conflicted \u2014 updates are stuck. Fix: git -C ${i} fetch origin && git -C ${i} reset --hard origin/main && brew upgrade tokmizer`]:[],""];try{let{connectDaemon:c}=await Promise.resolve().then(()=>(mt(),ft)),{socketPath:u}=await Promise.resolve().then(()=>(cn(),co)),{path:l}=u(),g=await c(),w=await g.ping();g.close(),a.push(`Daemon: running (pid ${w.pid})`,` socket: ${l}`,` uptime: ${Math.floor(w.uptimeMs/1e3)}s`,` ruleCount: ${w.ruleCount}`,` bundleVersion: ${w.bundleVersion}`,"")}catch(c){a.push(`Daemon: not running (${c.message})`,"")}try{let{readFileSync:c,existsSync:u,statSync:l}=await import("node:fs"),{join:g}=await import("node:path"),{tokmizerHome:w}=await Promise.resolve().then(()=>(I(),_s)),E=w(),$=g(E,"daemon.spawn.fail");if(u($)){let P=Number(c($,"utf8"));a.push(` last spawn failure: ${Number.isFinite(P)?new Date(P).toISOString():"unknown"} (details: ${g(E,"daemon.log")})`)}let Z=g(E,"drift.jsonl");if(u(Z)&&l(Z).size>0){let P=c(Z,"utf8").trim().split(`
|
|
128
|
+
`),R=JSON.parse(P[P.length-1]);a.push(`Drift: ${P.length} unrecognized hook payload shape(s), last on ${R.tool??"?"} (${Z})`,"")}}catch{}try{let c=yi(await Ye());c&&a.push(`Coverage: ${c}`,"")}catch{}process.stdout.write(a.join(`
|
|
129
|
+
`));return}if(t==="auto-update"){let{autoUpdateEnabled:r,setAutoUpdate:n}=await Promise.resolve().then(()=>(hr(),pr)),s=e[0]??"status";if(s==="on"||s==="off")n(s==="on");else if(s!=="status"){process.stderr.write(`Usage: tkr auto-update [on|off|status]
|
|
130
130
|
`),process.exitCode=1;return}process.stdout.write(`auto-update: ${r()?"on":"off"}
|
|
131
|
-
`);return}if(t==="self-update"){let{selfUpdate:r,defaultDeps:n}=await Promise.resolve().then(()=>(
|
|
131
|
+
`);return}if(t==="self-update"){let{selfUpdate:r,defaultDeps:n}=await Promise.resolve().then(()=>(hr(),pr)),s=await T(),o=await r(n(s?.latestPluginVersion));process.stdout.write(`${o.length?o.join(`
|
|
132
132
|
`):"up to date"}
|
|
133
|
-
`);return}if(t==="shims-refresh"){let{refreshStaleShims:r}=await Promise.resolve().then(()=>(
|
|
134
|
-
`);return}if(t==="setup-codex"){await
|
|
135
|
-
${n.manual}`;process.stdout.write([`Installed ${r.length} command shims into ${
|
|
136
|
-
`)),(o==="error"||n.status==="missing")&&(process.exitCode=1);return}if(t==="shim"){let r=e[0]??"install";if(r==="install"){let n=e.indexOf("--runner"),s=n>=0?e[n+1]:
|
|
137
|
-
`);let i=await
|
|
133
|
+
`);return}if(t==="shims-refresh"){let{refreshStaleShims:r}=await Promise.resolve().then(()=>(Nr(),Xo)),n=await r(ae());process.stdout.write(`shims refreshed: ${n}
|
|
134
|
+
`);return}if(t==="setup-codex"){await me(G);let r=await Je(ae()),n=await Dr(),s=Nd(new URL("./tkr-codex-hook.js",import.meta.url)),o=await kn(vn(process.env.PATH??"",s)),i=o==="error"?`Could not update ${pt()}: it is not valid JSON. Fix it, then run tkr setup-codex again.`:`${o==="present"?"Codex hook already set":"Added the tokmizer hook"} in ${pt()}. In Codex, run /hooks once and approve it.`,a=n.status==="added"?`Added the shim path to ${n.target}.`:n.status==="present"?`Shim path already set in ${n.target}.`:`Could not update ${n.target}. Add this to your shell profile:
|
|
135
|
+
${n.manual}`;process.stdout.write([`Installed ${r.length} command shims into ${D()}.`,i,a,"","Last step: open a new terminal and restart Codex so it picks up the change.","Check coverage anytime with: tkr discover","Tokmizer is free. No account is required.",""].join(`
|
|
136
|
+
`)),(o==="error"||n.status==="missing")&&(process.exitCode=1);return}if(t==="shim"){let r=e[0]??"install";if(r==="install"){let n=e.indexOf("--runner"),s=n>=0?e[n+1]:ae(),o=await Je(s??ae());process.stdout.write(`Installed ${o.length} shims into ${D()}
|
|
137
|
+
`);let i=await Dr();if(i.status==="added"?process.stdout.write(`Added PATH to ${i.target}. Open a new terminal to activate.
|
|
138
138
|
`):i.status==="present"?process.stdout.write(`PATH already set in ${i.target}. Open a new terminal if not active.
|
|
139
139
|
`):process.stdout.write(`Add this to your shell profile, then open a new terminal:
|
|
140
|
-
${i.manual}`),i.status==="missing"){process.exitCode=1;return}let a=await T()??await
|
|
140
|
+
${i.manual}`),i.status==="missing"){process.exitCode=1;return}let a=await T()??await me(G);process.stdout.write(a?`Free access is ready. No account is required.
|
|
141
141
|
`:`Free activation is pending. When online, run: tkr status
|
|
142
|
-
`);return}if(r==="uninstall"){let n=await Jn();process.stdout.write(`Removed ${n} shims from ${
|
|
142
|
+
`);return}if(r==="uninstall"){let n=await Jn();process.stdout.write(`Removed ${n} shims from ${D()}
|
|
143
143
|
`);return}process.stderr.write(`Unknown shim subcommand: ${r}
|
|
144
|
-
`),process.exitCode=1;return}if(t==="status"){process.stdout.write(`YOLO: ${
|
|
145
|
-
`);let r=await T()??await
|
|
146
|
-
`);return}let n=
|
|
144
|
+
`),process.exitCode=1;return}if(t==="status"){process.stdout.write(`YOLO: ${ut()?"on":"off"} (this machine only)
|
|
145
|
+
`);let r=await T()??await me(G);if(!r){process.stdout.write(`Free tier starts automatically on the first online run. Could not reach tokmizer.com right now. Retry later, or run: tkr link
|
|
146
|
+
`);return}let n=Er(Tr(r),Ar(r));if(process.stdout.write(`Plan ${r.plan} | Status ${r.status}${r.email?` | Email ${r.email}`:r.plan==="free"?" | Anonymous":""}
|
|
147
147
|
`),process.stdout.write(`power: ${n?"available":"locked"}
|
|
148
|
-
`),n){let s=await Qr("power"),o=await
|
|
149
|
-
`)}}
|
|
148
|
+
`),n){let s=await Qr("power"),o=await cr("power")!==null;if(!s||!o){let i=await ar(),a=i?.error?` (last sync failed: ${i.error})`:"";process.stdout.write(`/power not synced yet${a} \u2014 run: tkr heartbeat
|
|
149
|
+
`)}}Uo(r)&&process.stdout.write(`Offline too long \u2014 reconnect (tkr heartbeat) to refresh your local state.
|
|
150
150
|
`),process.stdout.write(`Everything is included on this token.
|
|
151
151
|
`);return}if(t==="gain"){let r=e[0]??"";if(e.length>1||!["","--json","--jour","--day","--semaine","--week","--mois","--month"].includes(r)){process.stderr.write(`Usage: tkr gain [--day|--week|--month|--json]
|
|
152
|
-
`),process.exitCode=1;return}let n=0,s,o=!1;if(r==="--json"){let[
|
|
153
|
-
`);return}let i=new Date,a=
|
|
154
|
-
|
|
155
|
-
`+
|
|
156
|
-
`),u?.relinkRequired&&(
|
|
157
|
-
`),u?.updateRequired?
|
|
158
|
-
`:
|
|
159
|
-
`),u?.clockSkewDetected&&(
|
|
160
|
-
`);try{let{connectDaemon:
|
|
161
|
-
`);return}if(t==="session"){process.stdout.write(
|
|
152
|
+
`),process.exitCode=1;return}let n=0,s,o=!1;if(r==="--json"){let[A,re]=await Promise.all([Ye(void 0,0),T()]),ne=qn(A.savedByProvider);process.stdout.write(JSON.stringify({...A,savedUsd:Number((A.savedTokens/1e6*ne).toFixed(2)),savedUsdBasis:"reference-input-price",savedUsdScope:"reduced-outputs",netSavedUsd:Number(((A.observed?.savedTokens??A.savedTokens)/1e6*ne).toFixed(2)),netSavedUsdScope:"all-observed-outputs",referencePricePerMtok:ne,plan:re?.plan??"free"})+`
|
|
153
|
+
`);return}let i=new Date,a=A=>Math.floor(new Date(i.getFullYear(),i.getMonth(),i.getDate()-A).getTime()/1e3);r==="--jour"||r==="--day"?(n=a(0),s="today"):r==="--semaine"||r==="--week"?(n=a(6),s="last 7 days",o=!0):(r==="--mois"||r==="--month")&&(n=a(29),s="last 30 days",o=!0);let[c,u,l,g]=await Promise.all([Ye(void 0,n),T(),r===""?Ye(void 0,a(0)):void 0,r===""?Ye(void 0,a(6)):void 0]),w=A=>({savedTokens:A.agent?A.agent.rawTokens-A.agent.filteredTokens:A.observed?.savedTokens??A.savedTokens,count:A.agent?.count??A.count}),E=l&&g?[{label:"Today",...w(l)},{label:"Last 7 days",...w(g)}]:void 0,$=qn(c.savedByProvider),Z=u?.linked??(!!u?.jwt&&u?.plan!=="free"),P=!!process.stdout.isTTY&&!process.env.NO_COLOR,R=_i(c,{color:P,pricePerMtok:$,subtitle:s,periods:E});if(Z||(R+=` Not linked: run tkr link to see these on your dashboard.
|
|
154
|
+
`),o){let A=Si(await xi(void 0,n),{color:P});A&&(R+=`
|
|
155
|
+
`+A)}c.count>0&&!Ht()&&(R+=` To include commands from every terminal: tkr shim install
|
|
156
|
+
`),u?.relinkRequired&&(R+=` \u26A0 dashboard link lost \u2014 run: tkr link <your-token> (from tokmizer.com/dashboard)
|
|
157
|
+
`),u?.updateRequired?R+=` \u26A0 plugin update required \u2014 run: /tkr-update
|
|
158
|
+
`:xe(B,u?.latestPluginVersion)&&(R+=` \u26A0 you run v${B}, v${u?.latestPluginVersion} is out \u2014 older versions undercount savings. Run /tkr-update, then RESTART Claude Code.
|
|
159
|
+
`),u?.clockSkewDetected&&(R+=` \u26A0 system clock looks off \u2014 sync it, then run: tkr heartbeat
|
|
160
|
+
`);try{let{connectDaemon:A}=await Promise.resolve().then(()=>(mt(),ft)),re=await A(),ne=await re.ping();re.close();let Vt=null;if(ne.ruleCount===0){let{runtimeFromCache:Vi}=await Promise.resolve().then(()=>(os(),ss));Vt=(await Vi())?.ruleCount??null}R+=Fr(ne.ruleCount,Vt)}catch{let{runtimeFromCache:A}=await Promise.resolve().then(()=>(os(),ss)),re=await A();R+=Fr(null,re?re.ruleCount:null)}process.stdout.write(R+`
|
|
161
|
+
`);return}if(t==="session"){process.stdout.write(Pi($i())+`
|
|
162
162
|
`);return}if(t==="discover"){let r=Ht(),n=[" tokmizer coverage"," "+"\u2500".repeat(40)," Agent (Claude/Codex) \u2705 optimized automatically",r?" Your terminal \u2705 covered (shims installed)":" Your terminal \u26A0\uFE0F not covered"];r||n.push("",' \u2192 run "tkr shim install" to also cover your commands outside the agent.'),n.push(""),process.stdout.write(n.join(`
|
|
163
163
|
`)+`
|
|
164
|
-
`);return}if(t==="restore"){let r=await
|
|
164
|
+
`);return}if(t==="restore"){let r=await Bs(e[0]);if(r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.code===0&&r.stdout&&gi(0,Buffer.byteLength(r.stdout,"utf8"),void 0,!1,Rr().host,"restore","tkr restore"),r.code===0&&r.restoredTokens){let n=await z();await Mn({cmd:"restore",tokensSaved:0,tokensRestored:r.restoredTokens,optimized:!1,telemetryOptIn:n.telemetryOptIn,host:Rr().host})}process.exitCode=r.code;return}if(t==="heartbeat"){await me(G);let r=Date.now(),n=await jn(G);if(!n||(n.lastHeartbeatOkAt??0)<r){process.stderr.write(`Heartbeat failed
|
|
165
165
|
`),process.exitCode=1;return}process.stdout.write(`OK plan=${n.plan} status=${n.status}
|
|
166
|
-
`);let s=await
|
|
167
|
-
`);return}if(t==="settings"){(e[0]??"show")==="show"&&process.stdout.write(`YOLO: ${
|
|
168
|
-
`),await
|
|
166
|
+
`);let s=await ar();s?.error&&process.stdout.write(`Note: feature sync failed: ${s.error}
|
|
167
|
+
`);return}if(t==="settings"){(e[0]??"show")==="show"&&process.stdout.write(`YOLO: ${ut()?"on":"off"} (this machine only)
|
|
168
|
+
`),await me(G),await Ld(e);return}if(t==="telemetry"){await me(G),await Fd(e);return}if(t==="reducer"){let r=["off","light","balanced","max"],n={off:"default: responses untouched",light:"trims padding, keeps natural prose",balanced:"dense and direct, answer first",max:"telegraphic, every token earns its place"},s=e[0]?.toLowerCase();if(!s){let o=await z(),i=o.reducer==="off"?"":o.enabled?await cr(`reducer-${o.reducer}`)?`Ready for the next Claude Code session.
|
|
169
169
|
`:`Reducer ruleset unavailable; reconnect and run: tkr heartbeat
|
|
170
170
|
`:`Tokmizer is disabled; the reducer is inactive.
|
|
171
171
|
`;process.stdout.write(`Reducer: ${o.reducer}
|
|
@@ -174,14 +174,14 @@ ${i.manual}`),i.status==="missing"){process.exitCode=1;return}let a=await T()??a
|
|
|
174
174
|
Reducer guides Claude Code response style; command output compression is separate.
|
|
175
175
|
`+i+`Change it: tkr reducer <off|light|balanced|max>
|
|
176
176
|
`);return}if(!r.includes(s)){process.stderr.write(`Unknown level: ${e[0]}. Use off, light, balanced or max.
|
|
177
|
-
`),process.exitCode=1;return}await
|
|
177
|
+
`),process.exitCode=1;return}await me(G);try{let o=await Te({reducer:s});if(o.settings.reducer==="off")process.stdout.write(`Reducer off. Claude Code responses back to normal next session.
|
|
178
178
|
`);else if(!o.settings.enabled)process.stdout.write(`Reducer saved as ${o.settings.reducer} for Claude Code. Tokmizer is disabled; enable it with: tkr settings set enabled true
|
|
179
|
-
`);else{if(await jn(G),!await
|
|
179
|
+
`);else{if(await jn(G),!await cr(`reducer-${o.settings.reducer}`)){process.stderr.write(`Reducer saved as ${o.settings.reducer}, but its ruleset is unavailable. Reconnect and run: tkr heartbeat before starting a new Claude Code session.
|
|
180
180
|
`),process.exitCode=1;return}process.stdout.write(`Reducer set to ${o.settings.reducer} for Claude Code. Its response-style instructions load next session.
|
|
181
181
|
`)}}catch(o){let i=o instanceof Error?o.message:String(o);i.includes("plan_required")||i.toLowerCase().includes("smart and pro")?process.stdout.write(`Reducer is not available on this token right now.
|
|
182
182
|
`):process.stdout.write(`${i}
|
|
183
183
|
`),process.exitCode=1}return}if(t==="compression"){if(e.length>1){process.stderr.write(`Usage: tkr compression [light|balanced|max]
|
|
184
|
-
`),process.exitCode=1;return}let r={light:"normal",balanced:"compact",max:"minimal",normal:"normal",compact:"compact",minimal:"minimal"},n={normal:"light",compact:"balanced",minimal:"max"},s=e[0];if(!s){let i=await
|
|
184
|
+
`),process.exitCode=1;return}let r={light:"normal",balanced:"compact",max:"minimal",normal:"normal",compact:"compact",minimal:"minimal"},n={normal:"light",compact:"balanced",minimal:"max"},s=e[0];if(!s){let i=await z(),a=ut();process.stdout.write((a?`Compression: YOLO (this machine only)
|
|
185
185
|
Standard level: ${n[i.outputVerbosity]}
|
|
186
186
|
Content and diagnostics can be lost; discarded output cannot be restored.
|
|
187
187
|
`:`Compression: ${n[i.outputVerbosity]}
|
|
@@ -193,7 +193,7 @@ Change standard level and leave YOLO: tkr compression <light|balanced|max>
|
|
|
193
193
|
Local mode: tkr yolo <on|off|status>
|
|
194
194
|
`);return}let o=Object.hasOwn(r,s.toLowerCase())?r[s.toLowerCase()]:void 0;if(!o){process.stderr.write(`Unknown level: ${s}. Use light, balanced or max.
|
|
195
195
|
`),process.exitCode=1;return}await Ve(!1),process.stdout.write(`YOLO: off (this machine only)
|
|
196
|
-
`);try{await
|
|
196
|
+
`);try{await me(G);let i=await Te({outputVerbosity:o});process.stdout.write(`Compression set to ${n[i.settings.outputVerbosity]}. Applies to your next commands.
|
|
197
197
|
`)}catch(i){process.stderr.write(`Could not update standard compression: ${i instanceof Error?i.message:String(i)}
|
|
198
198
|
`),process.exitCode=1}return}Md(),process.exitCode=["help","--help","-h"].includes(t)?0:1}jd().catch(t=>{process.stderr.write(`${t.message??t}
|
|
199
199
|
`),process.exitCode=1});
|