@tinycloud/web-sdk 3.12.0-beta.7 → 3.12.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/delegations-issued.cjs +1 -1
- package/dist/delegations-issued.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/modules/tcw.d.ts +5 -2
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t;(function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},e.getValidEnumValues=t=>{const a=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of a)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},e.find=(e,t)=>{for(const a of e)if(t(a))return a},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t})(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const a=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),s=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return Number.isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},n=e.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"]);class i extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},a={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,s=0;for(;s<n.path.length;){const a=n.path[s];s===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],s++}}};return s(this),a}static assert(e){if(!(e instanceof i))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,e.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},a=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else a.push(e(s));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}}i.create=e=>new i(e);const r=(t,s)=>{let i;switch(t.code){case n.invalid_type:i=t.received===a.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case n.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case n.unrecognized_keys:i=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case n.invalid_union:i="Invalid input";break;case n.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case n.invalid_enum_value:i=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case n.invalid_arguments:i="Invalid function arguments";break;case n.invalid_return_type:i="Invalid function return type";break;case n.invalid_date:i="Invalid date";break;case n.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case n.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case n.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case n.custom:i="Invalid input";break;case n.invalid_intersection_types:i="Intersection results could not be merged";break;case n.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case n.not_finite:i="Number must be finite";break;default:i=s.defaultError,e.assertNever(t)}return{message:i}};let o=r;var d;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(d||(d={}));function c(e,t){const a=o,s=(e=>{const{data:t,path:a,errorMaps:s,issueData:n}=e,i=[...a,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=s.filter(e=>!!e).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===r?void 0:r].filter(e=>!!e)});e.common.issues.push(s)}class u{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const a=[];for(const s of t){if("aborted"===s.status)return l;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){const a=[];for(const e of t){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return u.mergeObjectSync(e,a)}static mergeObjectSync(e,t){const a={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return l;if("aborted"===n.status)return l;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(a[t.value]=n.value)}return{status:e.value,value:a}}}const l=Object.freeze({status:"aborted"}),h=e=>({status:"dirty",value:e}),p=e=>({status:"valid",value:e}),m=e=>"aborted"===e.status,f=e=>"dirty"===e.status,g=e=>"valid"===e.status,v=e=>"undefined"!=typeof Promise&&e instanceof Promise;class y{constructor(e,t,a,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,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}}const _=(e,t)=>{if(g(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new i(e.common.issues);return this._error=t,this._error}}};function k(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:s,description:n}=e;if(t&&(a||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??a??n.defaultError}},description:n}}class x{get description(){return this._def.description}_getType(e){return s(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:s(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new u,ctx:{common:e.parent.common,data:e.data,parsedType:s(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(v(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){const a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:s(e)},n=this._parseSync({data:e,path:a.path,parent:a});return _(a,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:s(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return g(a)?{value:a.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>g(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:s(e)},n=this._parse({data:e,path:a.path,parent:a}),i=await(v(n)?n:Promise.resolve(n));return _(a,i)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const i=e(t),r=()=>s.addIssue({code:n.custom,...a(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(r(),!1)):!!i||(r(),!1)})}refinement(e,t){return this._refinement((a,s)=>!!e(a)||(s.addIssue("function"==typeof t?t(a,s):t),!1))}_refinement(e){return new ke({schema:this,typeName:Ie.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:e=>this["~validate"](e)}}optional(){return xe.create(this,this._def)}nullable(){return be.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ne.create(this)}promise(){return _e.create(this,this._def)}or(e){return oe.create([this,e],this._def)}and(e){return ce.create(this,e,this._def)}transform(e){return new ke({...k(this._def),schema:this,typeName:Ie.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new we({...k(this._def),innerType:this,defaultValue:t,typeName:Ie.ZodDefault})}brand(){return new Ze({typeName:Ie.ZodBranded,type:this,...k(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Te({...k(this._def),innerType:this,catchValue:t,typeName:Ie.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return Ce.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const b=/^c[^\s-]{8,}$/i,w=/^[0-9a-z]+$/,T=/^[0-9A-HJKMNP-TV-Z]{26}$/i,O=/^[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,Z=/^[a-z0-9_-]{21}$/i,S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,C=/^[-+]?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)?)??$/,N=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let A;const I=/^(?:(?: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])$/,j=/^(?:(?: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])$/,E=/^(([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]))$/,R=/^(([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])$/,$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,P=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,D="((\\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])))",F=new RegExp(`^${D}$`);function L(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function z(e){return new RegExp(`^${L(e)}$`)}function M(e){let t=`${D}T${L(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function V(e,t){return!("v4"!==t&&t||!I.test(e))||!("v6"!==t&&t||!E.test(e))}function U(e,t){if(!S.test(e))return!1;try{const[a]=e.split(".");if(!a)return!1;const s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(s));return!("object"!=typeof n||null===n||"typ"in n&&"JWT"!==n?.typ||!n.alg||t&&n.alg!==t)}catch{return!1}}function K(e,t){return!("v4"!==t&&t||!j.test(e))||!("v6"!==t&&t||!R.test(e))}class B extends x{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==a.string){const e=this._getOrReturnCtx(t);return c(e,{code:n.invalid_type,expected:a.string,received:e.parsedType}),l}const s=new u;let i;for(const a of this._def.checks)if("min"===a.kind)t.data.length<a.value&&(i=this._getOrReturnCtx(t,i),c(i,{code:n.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if("max"===a.kind)t.data.length>a.value&&(i=this._getOrReturnCtx(t,i),c(i,{code:n.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if("length"===a.kind){const e=t.data.length>a.value,r=t.data.length<a.value;(e||r)&&(i=this._getOrReturnCtx(t,i),e?c(i,{code:n.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):r&&c(i,{code:n.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if("email"===a.kind)N.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"email",code:n.invalid_string,message:a.message}),s.dirty());else if("emoji"===a.kind)A||(A=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),A.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"emoji",code:n.invalid_string,message:a.message}),s.dirty());else if("uuid"===a.kind)O.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"uuid",code:n.invalid_string,message:a.message}),s.dirty());else if("nanoid"===a.kind)Z.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"nanoid",code:n.invalid_string,message:a.message}),s.dirty());else if("cuid"===a.kind)b.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"cuid",code:n.invalid_string,message:a.message}),s.dirty());else if("cuid2"===a.kind)w.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"cuid2",code:n.invalid_string,message:a.message}),s.dirty());else if("ulid"===a.kind)T.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"ulid",code:n.invalid_string,message:a.message}),s.dirty());else if("url"===a.kind)try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),c(i,{validation:"url",code:n.invalid_string,message:a.message}),s.dirty()}else"regex"===a.kind?(a.regex.lastIndex=0,a.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"regex",code:n.invalid_string,message:a.message}),s.dirty())):"trim"===a.kind?t.data=t.data.trim():"includes"===a.kind?t.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(t,i),c(i,{code:n.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):"toLowerCase"===a.kind?t.data=t.data.toLowerCase():"toUpperCase"===a.kind?t.data=t.data.toUpperCase():"startsWith"===a.kind?t.data.startsWith(a.value)||(i=this._getOrReturnCtx(t,i),c(i,{code:n.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):"endsWith"===a.kind?t.data.endsWith(a.value)||(i=this._getOrReturnCtx(t,i),c(i,{code:n.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):"datetime"===a.kind?M(a).test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{code:n.invalid_string,validation:"datetime",message:a.message}),s.dirty()):"date"===a.kind?F.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{code:n.invalid_string,validation:"date",message:a.message}),s.dirty()):"time"===a.kind?z(a).test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{code:n.invalid_string,validation:"time",message:a.message}),s.dirty()):"duration"===a.kind?C.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"duration",code:n.invalid_string,message:a.message}),s.dirty()):"ip"===a.kind?V(t.data,a.version)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"ip",code:n.invalid_string,message:a.message}),s.dirty()):"jwt"===a.kind?U(t.data,a.alg)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"jwt",code:n.invalid_string,message:a.message}),s.dirty()):"cidr"===a.kind?K(t.data,a.version)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"cidr",code:n.invalid_string,message:a.message}),s.dirty()):"base64"===a.kind?$.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"base64",code:n.invalid_string,message:a.message}),s.dirty()):"base64url"===a.kind?P.test(t.data)||(i=this._getOrReturnCtx(t,i),c(i,{validation:"base64url",code:n.invalid_string,message:a.message}),s.dirty()):e.assertNever(a);return{status:s.value,value:t.data}}_regex(e,t,a){return this.refinement(t=>e.test(t),{validation:t,code:n.invalid_string,...d.errToObj(a)})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...d.errToObj(e)})}url(e){return this._addCheck({kind:"url",...d.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...d.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...d.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...d.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...d.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...d.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...d.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...d.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...d.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...d.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...d.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...d.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...d.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...d.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...d.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...d.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...d.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...d.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...d.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...d.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...d.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...d.errToObj(t)})}nonempty(e){return this.min(1,d.errToObj(e))}trim(){return new B({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function q(e,t){const a=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=a>s?a:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}B.create=e=>new B({checks:[],typeName:Ie.ZodString,coerce:e?.coerce??!1,...k(e)});class W extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==a.number){const e=this._getOrReturnCtx(t);return c(e,{code:n.invalid_type,expected:a.number,received:e.parsedType}),l}let s;const i=new u;for(const a of this._def.checks)"int"===a.kind?e.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),c(s,{code:n.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):"min"===a.kind?(a.inclusive?t.data<a.value:t.data<=a.value)&&(s=this._getOrReturnCtx(t,s),c(s,{code:n.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):"max"===a.kind?(a.inclusive?t.data>a.value:t.data>=a.value)&&(s=this._getOrReturnCtx(t,s),c(s,{code:n.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):"multipleOf"===a.kind?0!==q(t.data,a.value)&&(s=this._getOrReturnCtx(t,s),c(s,{code:n.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):"finite"===a.kind?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),c(s,{code:n.not_finite,message:a.message}),i.dirty()):e.assertNever(a);return{status:i.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,d.toString(t))}gt(e,t){return this.setLimit("min",e,!1,d.toString(t))}lte(e,t){return this.setLimit("max",e,!0,d.toString(t))}lt(e,t){return this.setLimit("max",e,!1,d.toString(t))}setLimit(e,t,a,s){return new W({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:d.toString(s)}]})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:d.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:d.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:d.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:d.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:d.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:d.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:d.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:d.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:d.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&e.isInteger(t.value))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}}W.create=e=>new W({checks:[],typeName:Ie.ZodNumber,coerce:e?.coerce||!1,...k(e)});class J extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==a.bigint)return this._getInvalidInput(t);let s;const i=new u;for(const a of this._def.checks)"min"===a.kind?(a.inclusive?t.data<a.value:t.data<=a.value)&&(s=this._getOrReturnCtx(t,s),c(s,{code:n.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):"max"===a.kind?(a.inclusive?t.data>a.value:t.data>=a.value)&&(s=this._getOrReturnCtx(t,s),c(s,{code:n.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):"multipleOf"===a.kind?t.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),c(s,{code:n.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):e.assertNever(a);return{status:i.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.bigint,received:t.parsedType}),l}gte(e,t){return this.setLimit("min",e,!0,d.toString(t))}gt(e,t){return this.setLimit("min",e,!1,d.toString(t))}lte(e,t){return this.setLimit("max",e,!0,d.toString(t))}lt(e,t){return this.setLimit("max",e,!1,d.toString(t))}setLimit(e,t,a,s){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:d.toString(s)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:d.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:d.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:d.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:d.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:d.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}J.create=e=>new J({checks:[],typeName:Ie.ZodBigInt,coerce:e?.coerce??!1,...k(e)});class H extends x{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.boolean,received:t.parsedType}),l}return p(e.data)}}H.create=e=>new H({typeName:Ie.ZodBoolean,coerce:e?.coerce||!1,...k(e)});class Q extends x{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==a.date){const e=this._getOrReturnCtx(t);return c(e,{code:n.invalid_type,expected:a.date,received:e.parsedType}),l}if(Number.isNaN(t.data.getTime()))return c(this._getOrReturnCtx(t),{code:n.invalid_date}),l;const s=new u;let i;for(const a of this._def.checks)"min"===a.kind?t.data.getTime()<a.value&&(i=this._getOrReturnCtx(t,i),c(i,{code:n.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):"max"===a.kind?t.data.getTime()>a.value&&(i=this._getOrReturnCtx(t,i),c(i,{code:n.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):e.assertNever(a);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:d.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:d.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Q.create=e=>new Q({checks:[],coerce:e?.coerce||!1,typeName:Ie.ZodDate,...k(e)});class Y extends x{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.symbol,received:t.parsedType}),l}return p(e.data)}}Y.create=e=>new Y({typeName:Ie.ZodSymbol,...k(e)});class G extends x{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.undefined,received:t.parsedType}),l}return p(e.data)}}G.create=e=>new G({typeName:Ie.ZodUndefined,...k(e)});class X extends x{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.null,received:t.parsedType}),l}return p(e.data)}}X.create=e=>new X({typeName:Ie.ZodNull,...k(e)});class ee extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return p(e.data)}}ee.create=e=>new ee({typeName:Ie.ZodAny,...k(e)});class te extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return p(e.data)}}te.create=e=>new te({typeName:Ie.ZodUnknown,...k(e)});class ae extends x{_parse(e){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.never,received:t.parsedType}),l}}ae.create=e=>new ae({typeName:Ie.ZodNever,...k(e)});class se extends x{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.void,received:t.parsedType}),l}return p(e.data)}}se.create=e=>new se({typeName:Ie.ZodVoid,...k(e)});class ne extends x{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),i=this._def;if(t.parsedType!==a.array)return c(t,{code:n.invalid_type,expected:a.array,received:t.parsedType}),l;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(e||a)&&(c(t,{code:e?n.too_big:n.too_small,minimum:a?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(c(t,{code:n.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(c(t,{code:n.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,a)=>i.type._parseAsync(new y(t,e,t.path,a)))).then(e=>u.mergeArray(s,e));const r=[...t.data].map((e,a)=>i.type._parseSync(new y(t,e,t.path,a)));return u.mergeArray(s,r)}get element(){return this._def.type}min(e,t){return new ne({...this._def,minLength:{value:e,message:d.toString(t)}})}max(e,t){return new ne({...this._def,maxLength:{value:e,message:d.toString(t)}})}length(e,t){return new ne({...this._def,exactLength:{value:e,message:d.toString(t)}})}nonempty(e){return this.min(1,e)}}function ie(e){if(e instanceof re){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=xe.create(ie(s))}return new re({...e._def,shape:()=>t})}return e instanceof ne?new ne({...e._def,type:ie(e.element)}):e instanceof xe?xe.create(ie(e.unwrap())):e instanceof be?be.create(ie(e.unwrap())):e instanceof ue?ue.create(e.items.map(e=>ie(e))):e}ne.create=(e,t)=>new ne({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ie.ZodArray,...k(t)});class re extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),a=e.objectKeys(t);return this._cached={shape:t,keys:a},this._cached}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.object,received:t.parsedType}),l}const{status:t,ctx:s}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),o=[];if(!(this._def.catchall instanceof ae&&"strip"===this._def.unknownKeys))for(const e in s.data)r.includes(e)||o.push(e);const d=[];for(const e of r){const t=i[e],a=s.data[e];d.push({key:{status:"valid",value:e},value:t._parse(new y(s,a,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ae){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)d.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)o.length>0&&(c(s,{code:n.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=s.data[t];d.push({key:{status:"valid",value:t},value:e._parse(new y(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of d){const a=await t.key,s=await t.value;e.push({key:a,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>u.mergeObjectSync(t,e)):u.mergeObjectSync(t,d)}get shape(){return this._def.shape()}strict(e){return d.errToObj,new re({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,a)=>{const s=this._def.errorMap?.(t,a).message??a.defaultError;return"unrecognized_keys"===t.code?{message:d.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new re({...this._def,unknownKeys:"strip"})}passthrough(){return new re({...this._def,unknownKeys:"passthrough"})}extend(e){return new re({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new re({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ie.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new re({...this._def,catchall:e})}pick(t){const a={};for(const s of e.objectKeys(t))t[s]&&this.shape[s]&&(a[s]=this.shape[s]);return new re({...this._def,shape:()=>a})}omit(t){const a={};for(const s of e.objectKeys(this.shape))t[s]||(a[s]=this.shape[s]);return new re({...this._def,shape:()=>a})}deepPartial(){return ie(this)}partial(t){const a={};for(const s of e.objectKeys(this.shape)){const e=this.shape[s];t&&!t[s]?a[s]=e:a[s]=e.optional()}return new re({...this._def,shape:()=>a})}required(t){const a={};for(const s of e.objectKeys(this.shape))if(t&&!t[s])a[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof xe;)e=e._def.innerType;a[s]=e}return new re({...this._def,shape:()=>a})}keyof(){return ge(e.objectKeys(this.shape))}}re.create=(e,t)=>new re({shape:()=>e,unknownKeys:"strip",catchall:ae.create(),typeName:Ie.ZodObject,...k(t)}),re.strictCreate=(e,t)=>new re({shape:()=>e,unknownKeys:"strict",catchall:ae.create(),typeName:Ie.ZodObject,...k(t)}),re.lazycreate=(e,t)=>new re({shape:e,unknownKeys:"strip",catchall:ae.create(),typeName:Ie.ZodObject,...k(t)});class oe extends x{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map(async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map(e=>new i(e.ctx.common.issues));return c(t,{code:n.invalid_union,unionErrors:a}),l});{let e;const s=[];for(const n of a){const a={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:a});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:a}),a.common.issues.length&&s.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=s.map(e=>new i(e));return c(t,{code:n.invalid_union,unionErrors:r}),l}}get options(){return this._def.options}}function de(t,n){const i=s(t),r=s(n);if(t===n)return{valid:!0,data:t};if(i===a.object&&r===a.object){const a=e.objectKeys(n),s=e.objectKeys(t).filter(e=>-1!==a.indexOf(e)),i={...t,...n};for(const e of s){const a=de(t[e],n[e]);if(!a.valid)return{valid:!1};i[e]=a.data}return{valid:!0,data:i}}if(i===a.array&&r===a.array){if(t.length!==n.length)return{valid:!1};const e=[];for(let a=0;a<t.length;a++){const s=de(t[a],n[a]);if(!s.valid)return{valid:!1};e.push(s.data)}return{valid:!0,data:e}}return i===a.date&&r===a.date&&+t===+n?{valid:!0,data:t}:{valid:!1}}oe.create=(e,t)=>new oe({options:e,typeName:Ie.ZodUnion,...k(t)});class ce extends x{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=(e,s)=>{if(m(e)||m(s))return l;const i=de(e.value,s.value);return i.valid?((f(e)||f(s))&&t.dirty(),{status:t.value,value:i.data}):(c(a,{code:n.invalid_intersection_types}),l)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}ce.create=(e,t,a)=>new ce({left:e,right:t,typeName:Ie.ZodIntersection,...k(a)});class ue extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.array)return c(s,{code:n.invalid_type,expected:a.array,received:s.parsedType}),l;if(s.data.length<this._def.items.length)return c(s,{code:n.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),l;!this._def.rest&&s.data.length>this._def.items.length&&(c(s,{code:n.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...s.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new y(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(i).then(e=>u.mergeArray(t,e)):u.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new ue({...this._def,rest:e})}}ue.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ue({items:e,typeName:Ie.ZodTuple,rest:null,...k(t)})};class le extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.object)return c(s,{code:n.invalid_type,expected:a.object,received:s.parsedType}),l;const i=[],r=this._def.keyType,o=this._def.valueType;for(const e in s.data)i.push({key:r._parse(new y(s,e,s.path,e)),value:o._parse(new y(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?u.mergeObjectAsync(t,i):u.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,a){return new le(t instanceof x?{keyType:e,valueType:t,typeName:Ie.ZodRecord,...k(a)}:{keyType:B.create(),valueType:e,typeName:Ie.ZodRecord,...k(t)})}}class he extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.map)return c(s,{code:n.invalid_type,expected:a.map,received:s.parsedType}),l;const i=this._def.keyType,r=this._def.valueType,o=[...s.data.entries()].map(([e,t],a)=>({key:i._parse(new y(s,e,s.path,[a,"key"])),value:r._parse(new y(s,t,s.path,[a,"value"]))}));if(s.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const a of o){const s=await a.key,n=await a.value;if("aborted"===s.status||"aborted"===n.status)return l;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const a of o){const s=a.key,n=a.value;if("aborted"===s.status||"aborted"===n.status)return l;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}he.create=(e,t,a)=>new he({valueType:t,keyType:e,typeName:Ie.ZodMap,...k(a)});class pe extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==a.set)return c(s,{code:n.invalid_type,expected:a.set,received:s.parsedType}),l;const i=this._def;null!==i.minSize&&s.data.size<i.minSize.value&&(c(s,{code:n.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&s.data.size>i.maxSize.value&&(c(s,{code:n.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const r=this._def.valueType;function o(e){const a=new Set;for(const s of e){if("aborted"===s.status)return l;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const d=[...s.data.values()].map((e,t)=>r._parse(new y(s,e,s.path,t)));return s.common.async?Promise.all(d).then(e=>o(e)):o(d)}min(e,t){return new pe({...this._def,minSize:{value:e,message:d.toString(t)}})}max(e,t){return new pe({...this._def,maxSize:{value:e,message:d.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}pe.create=(e,t)=>new pe({valueType:e,minSize:null,maxSize:null,typeName:Ie.ZodSet,...k(t)});class me extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}me.create=(e,t)=>new me({getter:e,typeName:Ie.ZodLazy,...k(t)});class fe extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return c(t,{received:t.data,code:n.invalid_literal,expected:this._def.value}),l}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ge(e,t){return new ve({values:e,typeName:Ie.ZodEnum,...k(t)})}fe.create=(e,t)=>new fe({value:e,typeName:Ie.ZodLiteral,...k(t)});class ve extends x{_parse(t){if("string"!=typeof t.data){const a=this._getOrReturnCtx(t),s=this._def.values;return c(a,{expected:e.joinValues(s),received:a.parsedType,code:n.invalid_type}),l}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),a=this._def.values;return c(e,{received:e.data,code:n.invalid_enum_value,options:a}),l}return p(t.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ve.create(e,{...this._def,...t})}exclude(e,t=this._def){return ve.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ve.create=ge;class ye extends x{_parse(t){const s=e.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==a.string&&i.parsedType!==a.number){const t=e.objectValues(s);return c(i,{expected:e.joinValues(t),received:i.parsedType,code:n.invalid_type}),l}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(s);return c(i,{received:i.data,code:n.invalid_enum_value,options:t}),l}return p(t.data)}get enum(){return this._def.values}}ye.create=(e,t)=>new ye({values:e,typeName:Ie.ZodNativeEnum,...k(t)});class _e extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return c(t,{code:n.invalid_type,expected:a.promise,received:t.parsedType}),l;const s=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return p(s.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}_e.create=(e,t)=>new _e({type:e,typeName:Ie.ZodPromise,...k(t)});class ke extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:a,ctx:s}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:e=>{c(s,e),e.fatal?a.abort():a.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(s.data,i);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===a.value)return l;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?l:"dirty"===t.status||"dirty"===a.value?h(t.value):t});{if("aborted"===a.value)return l;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?l:"dirty"===t.status||"dirty"===a.value?h(t.value):t}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const t=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===t.status?l:("dirty"===t.status&&a.dirty(),e(t.value),{status:a.value,value:t.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(t=>"aborted"===t.status?l:("dirty"===t.status&&a.dirty(),e(t.value).then(()=>({status:a.value,value:t.value}))))}if("transform"===n.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!g(e))return l;const t=n.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:t}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>g(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:a.value,value:e})):l)}e.assertNever(n)}}ke.create=(e,t,a)=>new ke({schema:e,typeName:Ie.ZodEffects,effect:t,...k(a)}),ke.createWithPreprocess=(e,t,a)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:Ie.ZodEffects,...k(a)});class xe extends x{_parse(e){return this._getType(e)===a.undefined?p(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}xe.create=(e,t)=>new xe({innerType:e,typeName:Ie.ZodOptional,...k(t)});class be extends x{_parse(e){return this._getType(e)===a.null?p(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}be.create=(e,t)=>new be({innerType:e,typeName:Ie.ZodNullable,...k(t)});class we extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===a.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}we.create=(e,t)=>new we({innerType:e,typeName:Ie.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...k(t)});class Te extends x{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return v(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new i(a.common.issues)},input:a.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new i(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:Ie.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...k(t)});class Oe extends x{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return c(t,{code:n.invalid_type,expected:a.nan,received:t.parsedType}),l}return{status:"valid",value:e.data}}}Oe.create=e=>new Oe({typeName:Ie.ZodNaN,...k(e)}),Symbol("zod_brand");class Ze extends x{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}}class Se extends x{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?l:"dirty"===e.status?(t.dirty(),h(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})();{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?l:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(e,t){return new Se({in:e,out:t,typeName:Ie.ZodPipeline})}}class Ce extends x{_parse(e){const t=this._def.innerType._parse(e),a=e=>(g(e)&&(e.value=Object.freeze(e.value)),e);return v(t)?t.then(e=>a(e)):a(t)}unwrap(){return this._def.innerType}}function Ne(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function Ae(e,t={},a){return e?ee.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Ne(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Ne(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}}):ee.create()}var Ie;Ce.create=(e,t)=>new Ce({innerType:e,typeName:Ie.ZodReadonly,...k(t)}),re.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ie||(Ie={}));const je=B.create,Ee=W.create,Re=(Oe.create,J.create,H.create),$e=(Q.create,Y.create,G.create,X.create,ee.create,te.create),Pe=(ae.create,se.create,ne.create),De=re.create,Fe=(re.strictCreate,oe.create,ce.create,ue.create,le.create),Le=(he.create,pe.create,me.create,fe.create),ze=ve.create,Me=(ye.create,_e.create,ke.create,xe.create,be.create,ke.createWithPreprocess,Se.create,e=>Q.create({...e,coerce:!0}));var Ve=De({kty:je(),crv:je().optional(),x:je().optional(),y:je().optional(),d:je().optional(),e:je().optional(),n:je().optional(),kid:je().optional(),alg:je().optional(),use:je().optional(),key_ops:Pe(je()).optional()}),Ue=ze(["main","session","ingested"]),Ke=De({id:je(),did:je(),type:Ue,jwk:Ve.optional(),priority:Ee()}),Be=(De({code:je(),message:je(),service:Le("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Ae(t=>t instanceof e,t))(Error).optional(),meta:Fe(je(),$e()).optional()}),"NOT_INITIALIZED"),qe="NETWORK_ERROR",We="INVALID_INPUT",Je="INVALID_TOKEN",He=De({cid:je(),delegateDID:je(),spaceId:je(),path:je(),actions:Pe(je()),caveats:Pe(Fe(je(),$e())).optional(),expiry:Me(),isRevoked:Re(),delegatorDID:je().optional(),createdAt:Me().optional(),parentCid:je().optional(),allowSubDelegation:Re().optional(),authHeader:je().optional()}),Qe=(De({cid:je().min(1),status:ze(["active","revoked","expired","unavailable","not_found"]),exists:Re(),active:Re(),revoked:Re(),expired:Re()}).strict().superRefine((e,t)=>{("active"===e.status?e.exists&&e.active&&!e.revoked&&!e.expired:"revoked"===e.status?e.exists&&!e.active&&e.revoked&&!e.expired:"expired"===e.status?e.exists&&!e.active&&!e.revoked&&e.expired:"unavailable"===e.status?e.exists&&!e.active&&!e.revoked&&!e.expired:!(e.exists||e.active||e.revoked||e.expired))||t.addIssue({code:n.custom,message:"delegation status flags do not match status"})}),De({revoked:Le(!0),cid:je().min(1)}).strict()),Ye=De({resource:je().min(1),actions:Pe(je()),caveats:Pe(Fe(je(),$e()))}).strict(),Ge=je().datetime({offset:!0}).transform(e=>new Date(e)),Xe=De({cid:je().min(1),direction:ze(["granted","received"]),delegatorDid:je().min(1),delegateDid:je().min(1),resources:Pe(Ye),parents:Pe(je()),issuedAt:Ge.nullable(),notBefore:Ge.nullable(),expiresAt:Ge.nullable(),status:ze(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:Ge.nullable().optional(),revokedBy:je().optional(),revokedAncestorCid:je().optional()}).strict(),et=De({schemaVersion:Le(2),items:Pe(Xe),nextCursor:je().optional()}).strict(),tt=(De({direction:ze(["granted","received","all","issued"]).optional(),status:ze(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:je().trim().min(1).optional(),limit:Ee().int().min(1).max(100).optional(),cursor:je().min(1).optional()}).strict(),De({resource:je(),action:je(),keys:Pe(Ke),delegation:He,expiresAt:Me().optional()}),De({cid:je(),spaceId:je(),delegator:je(),delegatee:je(),keyId:je().optional(),path:je(),actions:Pe(je()),expiry:Me().optional(),notBefore:Me().optional(),isRevoked:Re(),createdAt:Me(),parentCid:je().optional()}),De({delegateDID:je(),path:je(),actions:Pe(je()),expiry:Me().optional(),disableSubDelegation:Re().optional(),statement:je().optional()}),Pe(He),De({root:He,chain:Pe(He),leaf:He}),ze(["granted","received","all"])),at=(De({direction:tt.optional(),path:je().optional(),actions:Pe(je()).optional(),includeRevoked:Re().optional(),delegator:je().optional(),delegatee:je().optional(),validAt:Me().optional(),limit:Ee().optional(),cursor:je().optional()}),ze(["owned","delegated"])),st=(De({id:je(),name:je().optional(),owner:je(),type:at,permissions:Pe(je()).optional(),expiresAt:Me().optional()}),ze(["base64","compact","ipfs"]));De({token:je(),url:je(),delegation:He,schema:st,expiresAt:Me().optional(),description:je().optional()}),De({data:$e(),delegation:He,spaceId:je(),path:je()}),De({persist:Re().optional(),validateChain:Re().optional(),keyName:je().optional(),createSessionKey:Re().optional(),priority:Ee().optional()}),De({path:je(),actions:Pe(je()).optional(),expiry:Me().optional(),schema:st.optional(),description:je().optional(),baseUrl:je().optional(),allowSubDelegation:Re().optional()}),De({hosts:Pe(je()),accountSpaceId:je().min(1).optional(),session:$e().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:$e().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:$e().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:Ae().optional(),sessionInvocationSigner:Ae().optional(),fetch:$e().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),De({createSessionKey:$e().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:$e().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:$e().refine(e=>"function"==typeof e,{message:"Expected a function"})}),De({siwe:je(),signature:je(),version:Ee(),cid:je().optional()});var nt=De({service:je(),space:je(),path:je(),actions:Pe(je()),caveats:Pe(Fe(je(),$e())).optional()}),it=(De({session:$e().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:je(),spaceId:je(),abilities:Fe(je(),Fe(je(),Pe(je()))),expirationSecs:Ee(),notBeforeSecs:Ee().optional(),disableSubDelegation:Re().optional()}),De({delegation:je(),cid:je(),delegateDID:je(),expiry:Me(),resources:Pe(nt)}),"tinycloud.delegation/revoke"),rt="tinycloud.delegation/list";function ot(e,t,a,s){return{code:e,message:t,service:"delegation",cause:a,meta:s}}var dt="delegation-issued-query-v1";async function ct(e,t,a){const s=await async function(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}(e),n={...a,status:e.status};return 401===e.status||403===e.status?ot("PERMISSION_DENIED",""===s?"The node refused the request":s,void 0,n):400===e.status&&s.includes("invalid delegation query cursor")?ot("INVALID_CURSOR","The node rejected the page cursor; list again from the start",void 0,n):503===e.status?ot("CHAIN_TOO_DEEP","This delegation chain is too long for the node to check right now; try again later",void 0,{...n,retryable:!0}):ot(qe,`${t}: ${e.status} - ${s}`,void 0,n)}async function ut(e,t){const a=e.sessionInvocationSigner;if(!a)return{ok:!1,error:ot(Be,"Listing issued delegations needs a session key signer")};try{const s=await async function(e){if(e.state.issuedQuerySupported)return{ok:!0,data:!0};const t=await e.fetchFn(`${e.host}/info`);if(!t.ok)return{ok:!1,error:ot(qe,`Couldn't read the node's info: ${t.status}`,void 0,{status:t.status})};const a=await t.json();return e.state.issuedQuerySupported=Array.isArray(a.features)&&a.features.includes(dt),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!s.ok)return s;if(!s.data)return{ok:!1,error:ot("UNSUPPORTED_OPERATION","This node doesn't support listing issued delegations yet",void 0,{feature:dt})};const n=await a.sign({[`${a.did()}/delegation`]:{[rt]:[{}]}}),i=await e.fetchFn(`${e.host}/delegation/query`,{method:"POST",headers:{Authorization:n,"content-type":"application/json"},body:JSON.stringify(t)});if(!i.ok)return{ok:!1,error:await ct(i,"Failed to query issued delegations",{})};const r=et.safeParse(await i.json());return r.success?{ok:!0,data:r.data}:{ok:!1,error:ot(Je,"Node returned an invalid delegation query response")}}catch(e){return{ok:!1,error:ot(qe,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function lt(e,t){const{pageSize:a=100,maxItems:s,untilCid:n,...i}=t;if(void 0!==s&&(!Number.isInteger(s)||s<1))return{ok:!1,error:ot(We,"maxItems must be a positive integer")};const r=[],o=new Set;let d;do{const t=Math.min(a,void 0===s?a:s-r.length),n=await e({...i,direction:"issued",limit:t,...void 0===d?{}:{cursor:d}});if(!n.ok)return n;if(r.push(...n.data.items),d=n.data.nextCursor,void 0!==d){if(o.has(d))return{ok:!1,error:ot(Je,"The node returned the same page cursor twice while listing issued delegations")};o.add(d)}}while(void 0!==d&&(void 0===s||r.length<s)&&(void 0===n||!r.some(e=>e.cid===n)));return{ok:!0,data:void 0===s?r:r.slice(0,s)}}async function ht(e,t){if(!t)return{ok:!1,error:ot(We,"cid is required")};const a=e.sessionInvocationSigner;if(!a)return{ok:!1,error:ot(Be,"Revoking an issued delegation needs a session key signer")};try{const s=await a.sign({[`urn:cid:${t}`]:{[it]:[{}]}}),n=await e.fetchFn(`${e.host}/revoke`,{method:"POST",headers:{Authorization:s}});if(!n.ok)return 404===n.status?{ok:!1,error:ot("NOT_FOUND",`Delegation not found: ${t}`)}:{ok:!1,error:await ct(n,"Failed to revoke delegation",{cid:t})};const i=Qe.safeParse(await n.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:ot("REVOCATION_FAILED","Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return{ok:!1,error:ot(qe,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}export{lt as queryAllIssued,ut as queryIssued,ht as revokeIssued};
|
|
1
|
+
var e,t,r={290(e){var t,r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(a,{DecryptTransportResponseError:()=>o}),e.exports=(t=a,((e,t,a,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of n(t))i.call(e,a)||void 0===a||r(e,a,{get:()=>t[a],enumerable:!(o=s(t,a))||o.enumerable});return e})(r({},"__esModule",{value:!0}),t));var o=class extends Error{constructor(e,t,r){super("Node decrypt request failed"),this.status=e,this.permissionHint=t,this.notFoundMessage=r,this.name="DecryptTransportResponseError"}}}},s={};function n(e){var t=s[e];if(void 0!==t)return t.exports;var i=s[e]={exports:{}};return r[e](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const i=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return Number.isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},o=e.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"]);class c extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof c))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,e.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);const u=(t,r)=>{let s;switch(t.code){case o.invalid_type:s=t.received===i.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case o.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:s=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case o.invalid_union:s="Invalid input";break;case o.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case o.invalid_enum_value:s=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case o.invalid_arguments:s="Invalid function arguments";break;case o.invalid_return_type:s="Invalid function return type";break;case o.invalid_date:s="Invalid date";break;case o.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):s="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case o.too_small:s="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case o.too_big:s="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case o.custom:s="Invalid input";break;case o.invalid_intersection_types:s="Intersection results could not be merged";break;case o.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case o.not_finite:s="Number must be finite";break;default:s=r.defaultError,e.assertNever(t)}return{message:s}};let d=u;var l;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(l||(l={}));function h(e,t){const r=d,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],a={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const c=s.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===u?void 0:u].filter(e=>!!e)});e.common.issues.push(s)}class p{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return y;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return p.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return y;if("aborted"===n.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const y=Object.freeze({status:"aborted"}),f=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),g=e=>"aborted"===e.status,v=e=>"dirty"===e.status,_=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;class E{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,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}}const b=(e,t)=>{if(_(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new c(e.common.issues);return this._error=t,this._error}}};function w(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class T{get description(){return this._def.description}_getType(e){return a(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new p,ctx:{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},s=this._parseSync({data:e,path:r.path,parent:r});return b(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return _(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>_(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(k(s)?s:Promise.resolve(s));return b(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new Ne({schema:this,typeName:Le.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:e=>this["~validate"](e)}}optional(){return Oe.create(this,this._def)}nullable(){return Re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return Te.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new Ne({...w(this._def),schema:this,typeName:Le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...w(this._def),innerType:this,defaultValue:t,typeName:Le.ZodDefault})}brand(){return new xe({typeName:Le.ZodBranded,type:this,...w(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ie({...w(this._def),innerType:this,catchValue:t,typeName:Le.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const N=/^c[^\s-]{8,}$/i,O=/^[0-9a-z]+$/,R=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A=/^[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,I=/^[a-z0-9_-]{21}$/i,S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,x=/^[-+]?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)?)??$/,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let P;const C=/^(?:(?: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])$/,U=/^(?:(?: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])$/,L=/^(([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]))$/,$=/^(([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])$/,K=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,V=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,q="((\\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])))",M=new RegExp(`^${q}$`);function F(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function j(e){return new RegExp(`^${F(e)}$`)}function B(e){let t=`${q}T${F(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function H(e,t){return!("v4"!==t&&t||!C.test(e))||!("v6"!==t&&t||!L.test(e))}function Z(e,t){if(!S.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!("object"!=typeof n||null===n||"typ"in n&&"JWT"!==n?.typ||!n.alg||t&&n.alg!==t)}catch{return!1}}function W(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!$.test(e))}class G extends T{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==i.string){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.string,received:e.parsedType}),y}const r=new p;let s;for(const n of this._def.checks)if("min"===n.kind)t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),h(s,{code:o.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty());else if("max"===n.kind)t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),h(s,{code:o.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty());else if("length"===n.kind){const e=t.data.length>n.value,i=t.data.length<n.value;(e||i)&&(s=this._getOrReturnCtx(t,s),e?h(s,{code:o.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&h(s,{code:o.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),r.dirty())}else if("email"===n.kind)D.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"email",code:o.invalid_string,message:n.message}),r.dirty());else if("emoji"===n.kind)P||(P=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),P.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"emoji",code:o.invalid_string,message:n.message}),r.dirty());else if("uuid"===n.kind)A.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"uuid",code:o.invalid_string,message:n.message}),r.dirty());else if("nanoid"===n.kind)I.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"nanoid",code:o.invalid_string,message:n.message}),r.dirty());else if("cuid"===n.kind)N.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"cuid",code:o.invalid_string,message:n.message}),r.dirty());else if("cuid2"===n.kind)O.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"cuid2",code:o.invalid_string,message:n.message}),r.dirty());else if("ulid"===n.kind)R.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"ulid",code:o.invalid_string,message:n.message}),r.dirty());else if("url"===n.kind)try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),h(s,{validation:"url",code:o.invalid_string,message:n.message}),r.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"regex",code:o.invalid_string,message:n.message}),r.dirty())):"trim"===n.kind?t.data=t.data.trim():"includes"===n.kind?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),h(s,{code:o.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()):"toLowerCase"===n.kind?t.data=t.data.toLowerCase():"toUpperCase"===n.kind?t.data=t.data.toUpperCase():"startsWith"===n.kind?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),h(s,{code:o.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()):"endsWith"===n.kind?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),h(s,{code:o.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()):"datetime"===n.kind?B(n).test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{code:o.invalid_string,validation:"datetime",message:n.message}),r.dirty()):"date"===n.kind?M.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{code:o.invalid_string,validation:"date",message:n.message}),r.dirty()):"time"===n.kind?j(n).test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{code:o.invalid_string,validation:"time",message:n.message}),r.dirty()):"duration"===n.kind?x.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"duration",code:o.invalid_string,message:n.message}),r.dirty()):"ip"===n.kind?H(t.data,n.version)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"ip",code:o.invalid_string,message:n.message}),r.dirty()):"jwt"===n.kind?Z(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"jwt",code:o.invalid_string,message:n.message}),r.dirty()):"cidr"===n.kind?W(t.data,n.version)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"cidr",code:o.invalid_string,message:n.message}),r.dirty()):"base64"===n.kind?K.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"base64",code:o.invalid_string,message:n.message}),r.dirty()):"base64url"===n.kind?V.test(t.data)||(s=this._getOrReturnCtx(t,s),h(s,{validation:"base64url",code:o.invalid_string,message:n.message}),r.dirty()):e.assertNever(n);return{status:r.value,value:t.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:o.invalid_string,...l.errToObj(r)})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...l.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.errToObj(e))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function z(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}G.create=e=>new G({checks:[],typeName:Le.ZodString,coerce:e?.coerce??!1,...w(e)});class J extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==i.number){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.number,received:e.parsedType}),y}let r;const s=new p;for(const n of this._def.checks)"int"===n.kind?e.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),h(r,{code:o.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):"multipleOf"===n.kind?0!==z(t.data,n.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_finite,message:n.message}),s.dirty()):e.assertNever(n);return{status:s.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,s){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(s)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&e.isInteger(t.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}J.create=e=>new J({checks:[],typeName:Le.ZodNumber,coerce:e?.coerce||!1,...w(e)});class Q extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==i.bigint)return this._getInvalidInput(t);let r;const s=new p;for(const n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):e.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,s){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(s)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>new Q({checks:[],typeName:Le.ZodBigInt,coerce:e?.coerce??!1,...w(e)});class Y extends T{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.boolean,received:t.parsedType}),y}return m(e.data)}}Y.create=e=>new Y({typeName:Le.ZodBoolean,coerce:e?.coerce||!1,...w(e)});class X extends T{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==i.date){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.date,received:e.parsedType}),y}if(Number.isNaN(t.data.getTime()))return h(this._getOrReturnCtx(t),{code:o.invalid_date}),y;const r=new p;let s;for(const n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),h(s,{code:o.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),h(s,{code:o.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):e.assertNever(n);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}X.create=e=>new X({checks:[],coerce:e?.coerce||!1,typeName:Le.ZodDate,...w(e)});class ee extends T{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.symbol,received:t.parsedType}),y}return m(e.data)}}ee.create=e=>new ee({typeName:Le.ZodSymbol,...w(e)});class te extends T{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.undefined,received:t.parsedType}),y}return m(e.data)}}te.create=e=>new te({typeName:Le.ZodUndefined,...w(e)});class re extends T{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.null,received:t.parsedType}),y}return m(e.data)}}re.create=e=>new re({typeName:Le.ZodNull,...w(e)});class se extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}se.create=e=>new se({typeName:Le.ZodAny,...w(e)});class ne extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}ne.create=e=>new ne({typeName:Le.ZodUnknown,...w(e)});class ie extends T{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.never,received:t.parsedType}),y}}ie.create=e=>new ie({typeName:Le.ZodNever,...w(e)});class ae extends T{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.void,received:t.parsedType}),y}return m(e.data)}}ae.create=e=>new ae({typeName:Le.ZodVoid,...w(e)});class oe extends T{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==i.array)return h(t,{code:o.invalid_type,expected:i.array,received:t.parsedType}),y;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(h(t,{code:e?o.too_big:o.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(h(t,{code:o.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(h(t,{code:o.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new E(t,e,t.path,r)))).then(e=>p.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new E(t,e,t.path,r)));return p.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new oe({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new oe({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new oe({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}function ce(e){if(e instanceof ue){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Oe.create(ce(s))}return new ue({...e._def,shape:()=>t})}return e instanceof oe?new oe({...e._def,type:ce(e.element)}):e instanceof Oe?Oe.create(ce(e.unwrap())):e instanceof Re?Re.create(ce(e.unwrap())):e instanceof fe?fe.create(e.items.map(e=>ce(e))):e}oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Le.ZodArray,...w(t)});class ue extends T{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),r=e.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),y}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),a=[];if(!(this._def.catchall instanceof ie&&"strip"===this._def.unknownKeys))for(const e in r.data)n.includes(e)||a.push(e);const c=[];for(const e of n){const t=s[e],n=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new E(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ie){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(h(r,{code:o.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const s=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new E(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>p.mergeObjectSync(t,e)):p.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new ue({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:l.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Le.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(t){const r={};for(const s of e.objectKeys(t))t[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new ue({...this._def,shape:()=>r})}omit(t){const r={};for(const s of e.objectKeys(this.shape))t[s]||(r[s]=this.shape[s]);return new ue({...this._def,shape:()=>r})}deepPartial(){return ce(this)}partial(t){const r={};for(const s of e.objectKeys(this.shape)){const e=this.shape[s];t&&!t[s]?r[s]=e:r[s]=e.optional()}return new ue({...this._def,shape:()=>r})}required(t){const r={};for(const s of e.objectKeys(this.shape))if(t&&!t[s])r[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof Oe;)e=e._def.innerType;r[s]=e}return new ue({...this._def,shape:()=>r})}keyof(){return Ee(e.objectKeys(this.shape))}}ue.create=(e,t)=>new ue({shape:()=>e,unknownKeys:"strip",catchall:ie.create(),typeName:Le.ZodObject,...w(t)}),ue.strictCreate=(e,t)=>new ue({shape:()=>e,unknownKeys:"strict",catchall:ie.create(),typeName:Le.ZodObject,...w(t)}),ue.lazycreate=(e,t)=>new ue({shape:e,unknownKeys:"strip",catchall:ie.create(),typeName:Le.ZodObject,...w(t)});class de extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new c(e.ctx.common.issues));return h(t,{code:o.invalid_union,unionErrors:r}),y});{let e;const s=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new c(e));return h(t,{code:o.invalid_union,unionErrors:n}),y}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Le.ZodUnion,...w(t)});const le=t=>t instanceof _e?le(t.schema):t instanceof Ne?le(t.innerType()):t instanceof ke?[t.value]:t instanceof be?t.options:t instanceof we?e.objectValues(t.enum):t instanceof Ae?le(t._def.innerType):t instanceof te?[void 0]:t instanceof re?[null]:t instanceof Oe?[void 0,...le(t.unwrap())]:t instanceof Re?[null,...le(t.unwrap())]:t instanceof xe||t instanceof Pe?le(t.unwrap()):t instanceof Ie?le(t._def.innerType):[];class he extends T{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return h(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),y;const r=this.discriminator,s=t.data[r],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const r of t){const t=le(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(s.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);s.set(n,r)}}return new he({typeName:Le.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...w(r)})}}function pe(t,r){const s=a(t),n=a(r);if(t===r)return{valid:!0,data:t};if(s===i.object&&n===i.object){const s=e.objectKeys(r),n=e.objectKeys(t).filter(e=>-1!==s.indexOf(e)),i={...t,...r};for(const e of n){const s=pe(t[e],r[e]);if(!s.valid)return{valid:!1};i[e]=s.data}return{valid:!0,data:i}}if(s===i.array&&n===i.array){if(t.length!==r.length)return{valid:!1};const e=[];for(let s=0;s<t.length;s++){const n=pe(t[s],r[s]);if(!n.valid)return{valid:!1};e.push(n.data)}return{valid:!0,data:e}}return s===i.date&&n===i.date&&+t===+r?{valid:!0,data:t}:{valid:!1}}class ye extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(g(e)||g(s))return y;const n=pe(e.value,s.value);return n.valid?((v(e)||v(s))&&t.dirty(),{status:t.value,value:n.data}):(h(r,{code:o.invalid_intersection_types}),y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ye.create=(e,t,r)=>new ye({left:e,right:t,typeName:Le.ZodIntersection,...w(r)});class fe extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return h(r,{code:o.invalid_type,expected:i.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return h(r,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(h(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new E(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>p.mergeArray(t,e)):p.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new fe({...this._def,rest:e})}}fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fe({items:e,typeName:Le.ZodTuple,rest:null,...w(t)})};class me extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return h(r,{code:o.invalid_type,expected:i.object,received:r.parsedType}),y;const s=[],n=this._def.keyType,a=this._def.valueType;for(const e in r.data)s.push({key:n._parse(new E(r,e,r.path,e)),value:a._parse(new E(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?p.mergeObjectAsync(t,s):p.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new me(t instanceof T?{keyType:e,valueType:t,typeName:Le.ZodRecord,...w(r)}:{keyType:G.create(),valueType:e,typeName:Le.ZodRecord,...w(t)})}}class ge extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return h(r,{code:o.invalid_type,expected:i.map,received:r.parsedType}),y;const s=this._def.keyType,n=this._def.valueType,a=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new E(r,e,r.path,[i,"key"])),value:n._parse(new E(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return y;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return y;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}ge.create=(e,t,r)=>new ge({valueType:t,keyType:e,typeName:Le.ZodMap,...w(r)});class ve extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return h(r,{code:o.invalid_type,expected:i.set,received:r.parsedType}),y;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(h(r,{code:o.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(h(r,{code:o.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function a(e){const r=new Set;for(const s of e){if("aborted"===s.status)return y;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map((e,t)=>n._parse(new E(r,e,r.path,t)));return r.common.async?Promise.all(c).then(e=>a(e)):a(c)}min(e,t){return new ve({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Le.ZodSet,...w(t)});class _e extends T{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}_e.create=(e,t)=>new _e({getter:e,typeName:Le.ZodLazy,...w(t)});class ke extends T{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Ee(e,t){return new be({values:e,typeName:Le.ZodEnum,...w(t)})}ke.create=(e,t)=>new ke({value:e,typeName:Le.ZodLiteral,...w(t)});class be extends T{_parse(t){if("string"!=typeof t.data){const r=this._getOrReturnCtx(t),s=this._def.values;return h(r,{expected:e.joinValues(s),received:r.parsedType,code:o.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),r=this._def.values;return h(e,{received:e.data,code:o.invalid_enum_value,options:r}),y}return m(t.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}be.create=Ee;class we extends T{_parse(t){const r=e.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==i.string&&s.parsedType!==i.number){const t=e.objectValues(r);return h(s,{expected:e.joinValues(t),received:s.parsedType,code:o.invalid_type}),y}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(r);return h(s,{received:s.data,code:o.invalid_enum_value,options:t}),y}return m(t.data)}get enum(){return this._def.values}}we.create=(e,t)=>new we({values:e,typeName:Le.ZodNativeEnum,...w(t)});class Te extends T{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return h(t,{code:o.invalid_type,expected:i.promise,received:t.parsedType}),y;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return m(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Te.create=(e,t)=>new Te({type:e,typeName:Le.ZodPromise,...w(t)});class Ne extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:s}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:e=>{h(s,e),e.fatal?r.abort():r.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(s.data,i);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return y;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?y:"dirty"===t.status||"dirty"===r.value?f(t.value):t});{if("aborted"===r.value)return y;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?y:"dirty"===t.status||"dirty"===r.value?f(t.value):t}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const t=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===t.status?y:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(t=>"aborted"===t.status?y:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===n.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!_(e))return y;const t=n.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>_(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:r.value,value:e})):y)}e.assertNever(n)}}Ne.create=(e,t,r)=>new Ne({schema:e,typeName:Le.ZodEffects,effect:t,...w(r)}),Ne.createWithPreprocess=(e,t,r)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:Le.ZodEffects,...w(r)});class Oe extends T{_parse(e){return this._getType(e)===i.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:Le.ZodOptional,...w(t)});class Re extends T{_parse(e){return this._getType(e)===i.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:Le.ZodNullable,...w(t)});class Ae extends T{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Le.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...w(t)});class Ie extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return k(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Le.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...w(t)});class Se extends T{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}Se.create=e=>new Se({typeName:Le.ZodNaN,...w(e)}),Symbol("zod_brand");class xe extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class De extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),f(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new De({in:e,out:t,typeName:Le.ZodPipeline})}}class Pe extends T{_parse(e){const t=this._def.innerType._parse(e),r=e=>(_(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Ce(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ue(e,t={},r){return e?se.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Ce(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Ce(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):se.create()}var Le;Pe.create=(e,t)=>new Pe({innerType:e,typeName:Le.ZodReadonly,...w(t)}),ue.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Le||(Le={}));const $e=G.create,Ke=J.create,Ve=(Se.create,Q.create,Y.create),qe=(X.create,ee.create,te.create,re.create,se.create,ne.create),Me=(ie.create,ae.create,oe.create),Fe=ue.create,je=(ue.strictCreate,de.create,he.create),Be=(ye.create,fe.create,me.create),He=(ge.create,ve.create,_e.create,ke.create),Ze=be.create,We=(we.create,Te.create,Ne.create,Oe.create,Re.create,Ne.createWithPreprocess,De.create,e=>X.create({...e,coerce:!0}));var Ge=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function ze(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function Je(e){return e.slice(10,e.indexOf("/"))}function Qe(e){return e.slice(e.indexOf("/")+1)}function Ye(e){const t={};for(const r of Ge)Je(r.urn)===e&&(t[ze(Qe(r.urn))]=r.urn);return t}var Xe=Ye("kv"),et={...Ye("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},tt={...Ye("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},rt=Ye("capabilities"),st=(Ye("hooks"),Ye("encryption")),nt=Ye("space"),it=Ge,at="applications",ot="account",ct="applications/",ut="secrets",dt="default",lt="public",ht="agents",pt="tinycloud.encryption",yt=st.NETWORK_CREATE,ft=[dt,at,ot,ut,lt,ht],mt={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:dt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:dt,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:dt,path:"",actions:["read","write"]}]},gt={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:at,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:at,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:at,path:"",actions:["read","write"]}]},vt={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ot,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ot,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ot,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ot,path:"account",actions:["read","write","schema"]}]},_t={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:ut,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:ut,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:ut,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:ut,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:ut,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:ut,path:"",actions:["read"],skipPrefix:!0}]},kt={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:lt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:lt,path:"",actions:["get","list","metadata"]}]},Et={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ht,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ht,path:"",actions:["get","put","del","list","metadata"]}]},bt={[dt]:mt,[at]:gt,[ot]:vt,[ut]:_t,[lt]:kt,[ht]:Et};function wt(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Tt(e,t,r){return!0===r||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function Nt(e,t,r){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const r=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,s="read"===r||"get"===r?Xe.GET:"write"===r||"put"===r?Xe.PUT:"delete"===r||"del"===r?Xe.DEL:"list"===r?Xe.LIST:"metadata"===r?Xe.METADATA:void 0;if(void 0===s)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const n=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${n}`,actions:[s],skipPrefix:!0}})}(e).flatMap(e=>Nt(e,t,r));const s=!0===e.skipPrefix||e.service===pt;return[{service:e.service,space:e.service===pt?"encryption":e.space??r,path:Tt(t,e.path,s),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function Ot(e){const t=new Set(e.filter(e=>e.service!==pt).map(e=>e.space));return function(e){const t=new Map;for(const r of e){const e=`${r.service}\0${r.space}\0${r.path}`,s=t.get(e);if(s)for(const e of r.actions)s.actions.includes(e)||s.actions.push(e);else t.set(e,{...r,actions:[...r.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[rt.READ]}))])}function Rt(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const r=t.includeAccountRegistryPermissions??!0,s=e.map(wt),n=s.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??at;return(e.permissions??[]).flatMap(e=>Nt(e,t,r))});r&&n.push(...At.map(e=>({...e,actions:[...e.actions]})));const i=new Map;for(const e of s){const t=i.get(e.app_id)??[];t.push(wt(e)),i.set(e.app_id,t)}return{manifests:s,resources:Ot(n),delegationTargets:[],registryRecords:r?[...i.entries()].map(([e,t])=>({key:`${ct}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:s.some(e=>e.includePublicSpace??!0)}}([bt[e]],{includeAccountRegistryPermissions:!1})}ft.map(e=>({name:e,manifest:bt[e],persistedAsApplication:e===ut}));var At=Object.freeze([{service:"tinycloud.kv",space:ot,path:ct,actions:[Xe.GET,Xe.PUT,Xe.LIST]},{service:"tinycloud.kv",space:ot,path:"spaces/",actions:[Xe.GET,Xe.PUT,Xe.LIST]},{service:"tinycloud.kv",space:ot,path:"system/bootstrap/complete",actions:[Xe.GET,Xe.PUT]},{service:"tinycloud.delegation",space:ot,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ot,path:"account",actions:[et.READ,et.WRITE,et.SCHEMA]},{service:"tinycloud.capabilities",space:ot,path:"",actions:[rt.READ]}]),It=Rt(dt),St={...It,resources:[...It.resources,...At.map(e=>({...e,actions:[...e.actions]}))]},xt=Object.freeze(Object.fromEntries(ft.map(e=>[e,e===dt?St:Rt(e)]))),Dt=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[yt]}]);Object.freeze(ft.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:xt[e].resources,...e===ot?{rawAbilities:Dt}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[nt.HOST]}]));var Pt=n(290),Ct={NOT_FOUND:"NOT_FOUND",AUTH_EXPIRED:"AUTH_EXPIRED",AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_DELEGATION_REVOKED:"AUTH_DELEGATION_REVOKED",AUTH_DELEGATION_ANCESTOR_REVOKED:"AUTH_DELEGATION_ANCESTOR_REVOKED",NETWORK_ERROR:"NETWORK_ERROR",NODE_NOT_RESPONDING:"NODE_NOT_RESPONDING",NODE_IDENTITY_MISMATCH:"NODE_IDENTITY_MISMATCH",PARTIAL_NODE_WRITE:"PARTIAL_NODE_WRITE",RESOURCE_NOT_ROUTED:"RESOURCE_NOT_ROUTED",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",NODE_BUSY:"NODE_BUSY",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",OUTCOME_UNKNOWN:"OUTCOME_UNKNOWN",KV_NOT_FOUND:"KV_NOT_FOUND",KV_WRITE_FAILED:"KV_WRITE_FAILED",KV_PRECONDITION_FAILED:"KV_PRECONDITION_FAILED",KV_CONFLICT:"KV_CONFLICT",KV_RESPONSE_TOO_LARGE:"KV_RESPONSE_TOO_LARGE",KV_SYNC_RESET_REQUIRED:"KV_SYNC_RESET_REQUIRED",KV_RETENTION_GRANT_REFUSED:"KV_RETENTION_GRANT_REFUSED",SQL_ERROR:"SQL_ERROR",SQL_PERMISSION_DENIED:"SQL_PERMISSION_DENIED",SQL_DATABASE_NOT_FOUND:"SQL_DATABASE_NOT_FOUND",SQL_RESPONSE_TOO_LARGE:"SQL_RESPONSE_TOO_LARGE",SQL_QUOTA_EXCEEDED:"SQL_QUOTA_EXCEEDED",SQL_INVALID_STATEMENT:"SQL_INVALID_STATEMENT",SQL_SCHEMA_ERROR:"SQL_SCHEMA_ERROR",SQL_READONLY_VIOLATION:"SQL_READONLY_VIOLATION",STORAGE_QUOTA_EXCEEDED:"STORAGE_QUOTA_EXCEEDED",STORAGE_LIMIT_REACHED:"STORAGE_LIMIT_REACHED",STORAGE_STATUS_UNAVAILABLE:"STORAGE_STATUS_UNAVAILABLE",DUCKDB_ERROR:"DUCKDB_ERROR",DUCKDB_PERMISSION_DENIED:"DUCKDB_PERMISSION_DENIED",DUCKDB_DATABASE_NOT_FOUND:"DUCKDB_DATABASE_NOT_FOUND",DUCKDB_RESPONSE_TOO_LARGE:"DUCKDB_RESPONSE_TOO_LARGE",DUCKDB_QUOTA_EXCEEDED:"DUCKDB_QUOTA_EXCEEDED",DUCKDB_INVALID_STATEMENT:"DUCKDB_INVALID_STATEMENT",DUCKDB_SCHEMA_ERROR:"DUCKDB_SCHEMA_ERROR",DUCKDB_READONLY_VIOLATION:"DUCKDB_READONLY_VIOLATION"};function Ut(e){return{ok:!0,data:e}}function Lt(e){return{ok:!1,error:e}}function $t(e,t,r,s){return{code:e,message:t,service:r,cause:s?.cause,meta:s?.meta}}var Kt="[REDACTED]",Vt=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),qt=new Set(["authenticated","ok","persisted","purgePending"]),Mt={source:["replica","network","none"],reason:["hit","absent","deleted","content_missing","coverage_incomplete","not_covered","pending_write","grant_missing","grant_expired","grant_revoked","grant_not_yet_valid","stale","replica_error","runtime_unsupported","replica_unavailable","unsupported_option","network_cursor","cursor_restart","aborted","REPLICA_BEHIND_OWN_WRITES","REPLICA_UNPROVEN_SINCE_START","NETWORK_REQUESTED","replica_gated","sign_out","account_switch","consent_expired","startup"],op:["get","list","put","delete","batchPut"],trigger:["start","interval","stale_read","manual","peer"],origin:["peer"],outcome:["found","not_found","error","committed","failed","ambiguous","ok","busy","aborted"],class:["offline","authority","storage","node","lifecycle"],state:["opened","grant_installed","grant_missing","runtime_unsupported","unavailable","revoked","recreated","purged","purge_failed","pending_store_error","pinned","pending_cleared","closed","idle","ready","gated"],action:["minted","renewed","renewal_refused","renewal_deferred","capped","expired","consent_deadline_reached","denied","deny_stale","deny_failed","database_deleted","marker_set","marker_cleared","unguarded","drained","erased","erase_failed","activation_blocked","activated","recovered"],gate:["not_established","stamp_stale","principal_mismatch","purge_pending","logout_pending","gate_unavailable"],kind:["value","missing_local","extra_local","keys","order"],coverage:["empty","bootstrapping","complete"],authority:["valid","expired","revoked","not-yet-valid"],code:["NETWORK_ERROR","TIMEOUT","ABORTED","REPLICA_BUSY","REPLICA_BEHIND_OWN_WRITES","REPLICA_UNPROVEN_SINCE_START","NETWORK_REQUESTED","INTEGRITY_ERROR","STORAGE_ERROR","REPLICA_CLOSED","RUNTIME_UNSUPPORTED","GRANT_EXPIRED","GRANT_REVOKED","GRANT_NOT_YET_VALID","GRANT_MISSING","GRANT_INVALID","SOURCE_CHANGED","PROTOCOL_ERROR","SCOPE_VIOLATION","NODE_ERROR","CONTENT_MISMATCH","STORAGE_FULL","REPLICA_GATED","RESET_REQUIRED","STORAGE_BUDGET","CONSENT_EXPIRED"],pendingState:["in_flight","committed","ambiguous"],strategy:["session","minted","installed"],verify:["match","diverged","error","aborted"]};function Ft(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function jt(e,t){try{return e[t]}catch{return Kt}}function Bt(e){if(null==e)return e;if("object"!=typeof e)return Kt;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return Kt;const t={};for(const r of Vt){const s=Ft(jt(e,r));void 0!==s&&(t[r]=s)}for(const r of qt){const s=jt(e,r);"boolean"==typeof s&&(t[r]=s)}for(const[r,s]of Object.entries(Mt)){const n=jt(e,r);"string"==typeof n&&s.includes(n)&&(t[r]=n)}void 0!==jt(e,"url")&&(t.url=Kt);const r=jt(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=Ft(jt(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return Kt}}var Ht="TinyCloud_debug";function Zt(){return globalThis}function Wt(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function Gt(e){return!0===e||"true"===e||"1"===e}function zt(){const e=globalThis.process;return e?.env?.[Ht]}function Jt(){if(Zt().window===globalThis)try{return globalThis.localStorage}catch{return}}function Qt(e){const t=Jt();if(t)try{e?t.setItem(Ht,"true"):t.removeItem(Ht)}catch{}}var Yt=new class{constructor(){this.enabled=Gt(Zt()[Ht])||Gt(function(){const e=Jt();if(e)try{return e.getItem(Ht)}catch{return}}())||Gt(zt()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||Gt(Zt()[Ht])||Gt(zt())}enable(e={}){this.enabled=!0,Zt()[Ht]=!0,!1!==e.persist&&Qt(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,Zt()[Ht]=!1,!1!==e.persist&&Qt(!1)}clear(){this.events=[]}getLogs(){return[...this.events]}log(e,t,r){if(this.isEnabled())return this.record({event:e,data:t,message:r,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}startTimer(e,t){if(!this.isEnabled())return{stop:()=>{}};const r=Wt();return this.log(`${e}.start`,t),{stop:t=>{const s=Wt();return this.record({event:`${e}.end`,data:t,durationMs:s-r,startedAt:r,endedAt:s,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}}}async timeAsync(e,t,r){if(!this.isEnabled())return t();const s=this.startTimer(e,r);try{const e=await t();return s.stop({ok:!0}),e}catch(e){throw s.stop({ok:!1,error:e}),e}}time(e,t,r){if(!this.isEnabled())return t();const s=this.startTimer(e,r);try{const e=t();return s.stop({ok:!0}),e}catch(e){throw s.stop({ok:!1,error:e}),e}}record(e){const t={...e,...void 0===e.data?{}:{data:Bt(e.data)},...void 0===e.message?{}:{message:"[REDACTED]"},sequence:++this.sequence};this.events.push(t),this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);try{globalThis.console?.debug?.("[TinyCloud]",t.event,t)}catch{}return t}};function Xt(e){return Yt.enable(e),Yt}function er(e){return Yt.disable(e),Yt}function tr(){return Yt.getLogs()}function rr(){Yt.clear()}!function(){const e=Zt();e.TinyCloudDebug=Yt,e.enableTinyCloudDebug=Xt,e.disableTinyCloudDebug=er,e.getTinyCloudDebugLogs=tr,e.clearTinyCloudDebugLogs=rr}();var sr=Fe({code:$e(),message:$e(),service:$e(),cause:qe().optional(),meta:Fe({}).passthrough().optional()});function nr(e,t=sr){return je("ok",[Fe({ok:He(!0),data:e}),Fe({ok:He(!1),error:t})])}nr(qe(),sr);var ir,ar=Fe({etag:$e().optional(),contentType:$e().optional(),lastModified:$e().optional(),contentLength:Ke().optional()});function or(e){try{return JSON.parse(e)}catch{return{}}}function cr(e,t,r,s,n){return n.message?dr(n.message):/<!doctype html/i.test(i=s)||/<html[\s>]/i.test(i)?524===r||/524\s*[:-]/i.test(s)||/a timeout occurred/i.test(s)?`${e} ${t} failed: upstream request timed out. Please retry.`:`${e} ${t} failed: upstream service returned an HTML error page (${r}).`:`${e} ${t} failed: ${r} - ${dr(s)}`;var i}function ur(e,t,r){const s={status:e,statusText:t},n=dr(r);return n&&(s.responseSnippet=n.slice(0,300)),s}function dr(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}ir=qe(),Fe({data:ir,headers:ar}),nr(Fe({keys:Me($e()),truncated:Ve().optional(),nextCursor:$e().optional()})),Fe({service:$e(),action:$e(),span:$e().optional(),key:$e().optional(),timestamp:Ke()}),Fe({service:$e(),action:$e(),span:$e().optional(),ok:Ve(),duration:Ke(),durationMs:Ke().optional(),status:Ke().optional()}),Fe({service:$e(),span:$e().optional(),error:sr}),Fe({service:$e(),attempt:Ke().int().positive(),maxAttempts:Ke().int().positive(),error:sr}),Fe({span:$e(),ok:Ve(),durationMs:Ke(),service:$e().optional(),action:$e().optional(),status:Ke().optional(),error:sr.optional()}),Fe({maxAttempts:Ke().int().positive(),backoff:Ze(["none","linear","exponential"]),baseDelayMs:Ke().nonnegative(),maxDelayMs:Ke().nonnegative(),retryableErrors:Me($e()),maxTotalMs:Ke().positive().optional()}),Fe({delegationHeader:Fe({Authorization:$e()}),delegationCid:$e(),spaceId:$e(),verificationMethod:$e(),jwk:Fe({}).passthrough()});var lr="urn:tinycloud:encryption:",hr=/^[a-z0-9][a-z0-9-]*$/,pr=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,yr=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function fr(e){if("string"!=typeof e||0===e.length)throw new yr("networkId must be a non-empty string");if(!e.startsWith(lr))throw new yr(`networkId must start with ${lr} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new yr(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const s=t.slice(0,r),n=t.slice(r+1);if(!s.startsWith("did:"))throw new yr(`networkId ownerDid must be a DID (got ${JSON.stringify(s)})`);const i=s.split(":");if(i.length<3||i.some(e=>0===e.length))throw new yr(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(s)})`);if(!hr.test(n))throw new yr(`networkId name ${JSON.stringify(n)} must match ${hr.source}`);return{networkId:e,ownerDid:s,name:n}}function mr(e){const t=e.lastIndexOf(":"),r=e.slice(t+1),s=r.indexOf("/"),n=-1===s?r:r.slice(0,s),i=fr(-1===s?e:`${e.slice(0,t+1)}${n}`);if(-1===s)return i;const a=r.slice(s+1),o=a.split("/"),c=a.endsWith("/");if(0===a.length||/[\u0000-\u001f\u007f\\]/.test(a)||o.some((e,t)=>"."===e||".."===e||0===e.length&&!(c&&t===o.length-1)))throw new yr(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...i,keyPath:a}}function gr(e){const t=e.match(pr);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function vr(e,t){const r=gr(e),s=gr(t);return r&&s?r.chainId===s.chainId&&r.address===s.address:e===t}Error,Error,Error,Error;var _r={NODE_NOT_RESPONDING:!0,PARTIAL_NODE_WRITE:!0,NODE_IDENTITY_MISMATCH:!0,RESOURCE_NOT_ROUTED:!0,DECRYPTION_DEPENDENCY_UNAVAILABLE:!0,registry_unavailable:!0,node_not_found:!0,node_registry_entry_exists:!0};function kr(e){if("object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"string"==typeof e.code&&"string"==typeof e.message&&(t=e.code,Object.prototype.hasOwnProperty.call(_r,t))){const t="meta"in e?e.meta:void 0;let r="object"!=typeof t||null===t||Array.isArray(t)?void 0:t;return"NODE_NOT_RESPONDING"===e.code&&"hosts"in e&&Array.isArray(e.hosts)?r={...r,hosts:e.hosts}:"PARTIAL_NODE_WRITE"===e.code&&"succeeded"in e&&Array.isArray(e.succeeded)&&"failed"in e&&Array.isArray(e.failed)&&(r={...r,succeeded:e.succeeded,failed:e.failed}),{code:e.code,message:e.message,...e instanceof Error?{cause:e}:{},...r?{meta:r}:{}}}var t}function Er(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t=e;if(Object.keys(t).sort().some(e=>!["actions","path","service","space"].includes(e)))return;if("tinycloud.kv"!==t.service&&"tinycloud.encryption"!==t.service)return;if("string"!=typeof t.path||0===t.path.length||t.path.includes("*"))return;if("tinycloud.kv"===t.service&&("string"!=typeof t.space||0===t.space.length||!t.path.startsWith("vault/")||t.path.endsWith("/")))return;if("tinycloud.encryption"===t.service&&(void 0!==t.space||!t.path.startsWith("urn:tinycloud:encryption:")||t.path.endsWith(":")))return;if(!Array.isArray(t.actions)||1!==t.actions.length||"string"!=typeof t.actions[0]||t.actions[0].includes("*"))return;const r="tinycloud.kv"===t.service?"tinycloud.kv/get":"tinycloud.encryption/decrypt";if(t.actions[0]!==r)return;const s="string"==typeof t.space?t.space:void 0;return{service:t.service,...void 0===s?{}:{space:s},path:t.path,actions:[t.actions[0]]}}function br(e){return{code:Ct.AUTH_REQUIRED,message:"Authentication required. Please sign in first.",service:e}}function wr(e,t,r,s){const n=s.trim(),[,i,a]=/^([a-z_]+)(?::\s*([a-z_]+):)?/.exec(n)??[];let o;if(503!==r.status||"sql_busy"!==i&&"unavailable_retryable"!==i&&"read_audit_busy"!==i)if(503===r.status&&"request_timeout"===i)o=Ct.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==i)return;o=Ct.OUTCOME_UNKNOWN}else o=Ct.NODE_BUSY;const c=o!==Ct.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return $t(o,t,e,{meta:{...ur(r.status,r.statusText,s),retryable:c,..."sql_busy"===i&&a?{stage:a}:{},...c&&u&&/^\d{1,9}$/.test(u)?{retryAfterMs:1e3*Number(u)}:{}}})}var Tr=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function Nr(e){return e instanceof Tr||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function Or(e,t,r){return void 0===t?{code:Ct.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:Ct.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function Rr(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var Ar=new Set(it.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),Ir=new Set(it.map(({service:e})=>e.slice(10)));function Sr(e,t,r){if("string"!=typeof e||0===e.length||e.length>1024)return!1;if("encryption"===t&&e.startsWith("urn:tinycloud:encryption:")){if(!/^[A-Za-z0-9_][A-Za-z0-9_.:/-]*$/.test(e)||e.includes("//")||e.split("/").some(e=>"."===e||".."===e))return!1;try{return fr(e),!0}catch{return!1}}const s=function(e,t){if(0===e.length||e.length>1024||!Ir.has(t)||/[\s\p{C}*#]/u.test(e)||e.includes("://"))return;const r=e.split("/");if(!/^tinycloud:[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(r[0]))return;const s=r.findIndex((e,t)=>t>0&&Ir.has(e));if(s<1||r[s]!==t)return;if(r.slice(1,s).some(e=>0===e.length||"."===e||".."===e))return;const n=r.slice(s+1);return n.some(e=>"."===e||".."===e)||"kv"!==t&&(0===n.length||""===n[n.length-1])?void 0:{space:r.slice(0,s).join("/"),path:n.join("/")}}(e,t);return void 0!==s&&(!s.path.endsWith("/")||"kv"===t&&"tinycloud.kv/list"===r)&&(""!==s.path||"kv"===t&&"tinycloud.kv/list"===r)}function xr(e){const t=Cr(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let s=e;for(let e=0;e<Dr&&"object"==typeof s&&null!==s&&!r.has(s);e+=1){r.add(s);const e=s,t=Pr(e),n=e.meta;if((401===t||403===t||void 0===t&&e.code===Ct.AUTH_UNAUTHORIZED)&&"object"==typeof n&&null!==n&&!Array.isArray(n)){const t=n,{resource:r,requiredAction:s}=t;if("string"==typeof s&&Ar.has(s)){const n=s.slice(10,s.indexOf("/")),i=void 0===e.service?t.service:e.service;if(Sr(r,n,s)&&(void 0===i||i===n||i===`tinycloud.${n}`))return{resource:r,requiredAction:s}}}s=e.cause}}var Dr=8;function Pr(e){const t=e.meta,r=[e.status,e.statusCode,"object"==typeof t&&null!==t?t.status:void 0];for(const e of r)if("number"==typeof e&&Number.isInteger(e)&&e>=400&&e<=599)return e}function Cr(e){const t=new Set;let r=!1,s=e;for(let e=0;e<Dr&&"object"==typeof s&&null!==s&&!t.has(s);e+=1){t.add(s);const e=s,n=Pr(e);if(401===n)return"unauthenticated";if(403===n)return"forbidden";if(void 0!==n)return"other";e.code===Ct.AUTH_UNAUTHORIZED&&(r=!0),s=e.cause}return r?"forbidden":void 0}function Ur(e){const t=e.match(/Used:\s*(\d+)\s*bytes,\s*Limit:\s*(\d+)\s*bytes/i);if(t)return{usedBytes:parseInt(t[1],10),limitBytes:parseInt(t[2],10)}}var Lr={storage_quota_exceeded:!0,storage_limit_reached:!0};function $r(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function Kr(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return $r(t)&&$r(r)?{usedBytes:t,limitBytes:r}:void 0}function Vr(e){let t;try{t=JSON.parse(e)}catch{return Ur(e)}if("object"!=typeof t||null===t)return;const r=t,s="string"==typeof r.message?r.message:"",n=Kr(r.space)??Ur(s),i="string"==typeof r.error&&!0===Lr[r.error];if(!n&&!i)return;const a={...n},o=Kr(r.account);if(o){const e=r.account.plan;a.account="string"==typeof e&&""!==e?{...o,plan:e}:o}return a}function qr(e,t,r,s){const n={...r,...Vr(s)};return 402===t?function(e,t,r){return{code:Ct.STORAGE_QUOTA_EXCEEDED,message:"TinyCloud storage is full, so this change was not saved. Reading still works. Free up space or upgrade your plan to save again.",service:e,meta:r}}(e,0,n):function(e,t,r){return{code:Ct.STORAGE_LIMIT_REACHED,message:"This change is larger than the TinyCloud storage you have left, so it was not saved. Reading still works. Free up space or upgrade your plan to save it.",service:e,meta:r}}(e,0,n)}function Mr(e,t,r=Ct.NETWORK_ERROR){const s=kr(t);return s?{...s,service:e}:t instanceof Error?Nr(t)?Or(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:Ct.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?Or(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var Fr=class{constructor(){this.abortController=new AbortController,this._config={}}get config(){return this._config}initialize(e){this.context=e}onSessionChange(e){}onSignOut(){this.abortController.abort(),this.abortController=new AbortController}get abortSignal(){return this.combineSignals()}get isAuthenticated(){return this.context?.isAuthenticated??!1}get session(){if(!this.context?.session)throw new Error("Not authenticated");return this.context.session}requireAuth(){return this.isAuthenticated}emit(e,t){this.context?.emit(e,t)}emitRequest(e,t){const r=this.getServiceName();this.emit("service.request",{service:r,action:e,span:this.spanName(e),key:t,timestamp:Date.now()})}emitResponse(e,t,r,s){const n=this.getServiceName(),i=Date.now()-r,a=this.spanName(e);this.emit("service.response",{service:n,action:e,span:a,ok:t,duration:i,durationMs:i,status:s}),this.emit("telemetry.span",{span:a,service:n,action:e,ok:t,durationMs:i,status:s})}emitError(e,t){const r=t?this.spanName(t):void 0;this.emit("service.error",{service:this.getServiceName(),...r?{span:r}:{},error:e})}getServiceName(){return this.constructor.serviceName}spanName(e){return`sdk.${this.getServiceName()}.${e}`}combineSignals(...e){const t=new AbortController,r=[this.abortController.signal,this.context?.abortSignal,...e.filter(Boolean)].filter(Boolean);for(const e of r){if(e.aborted)return t.abort(e.reason),t.signal;e.addEventListener("abort",()=>t.abort(e.reason),{once:!0})}return t.signal}invokeWithRetry(e,t,{headers:r,...s}={}){const n=()=>{const e=t();return{method:"POST",...s,headers:Array.isArray(e)?[...e,...Object.entries(r??{})]:{...e,...r}}};return this.context.invokeWithRetry?this.context.invokeWithRetry(e,n):this.context.fetch(e,n())}createRequestSignal(e,t){const r=new AbortController,s=[];let n;const i=()=>{void 0!==n&&(clearTimeout(n),n=void 0);for(const e of s.splice(0))e()},a=e=>{i(),r.abort(e)},o={signal:r.signal,dispose:i},c=[this.abortController.signal,this.context?.abortSignal,this.context?.operationAbortSignal,e].filter(e=>void 0!==e);for(const e of c){if(e.aborted)return a(e.reason),o;const t=()=>a(e.reason);e.addEventListener("abort",t,{once:!0}),s.push(()=>e.removeEventListener("abort",t))}const u=t??this._config.timeout;return"number"==typeof u&&u>0&&u<=2147483647&&(n=setTimeout(()=>a(new Tr(u)),u)),o}async withTelemetry(e,t,r){const s=Date.now();this.emitRequest(e,t);try{const t=await r();return t.ok?this.emitResponse(e,!0,s):(this.emitResponse(e,!1,s),this.emitError(t.error,e)),t}catch(t){const r=Mr(this.getServiceName(),t);return this.emitResponse(e,!1,s),this.emitError(r,e),Lt(r)}}},jr=class e{constructor(e,t){this._kv=e,this._prefix=t.endsWith("/")?t.slice(0,-1):t}get prefix(){return this._prefix}getFullKey(e){const t=e.startsWith("/")?e:`/${e}`;return`${this._prefix}${t}`}async get(e,t){const r=this.getFullKey(e);return this._kv.get(r,{...t,prefix:""})}async batchGet(e,t){const r=await this._kv.batchGet(e.map(e=>this.getFullKey(e)),{...t,prefix:""});return r.ok?Ut({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async put(e,t,r){const s=this.getFullKey(e);return this._kv.put(s,t,{...r,prefix:""})}async batchPut(e,t){return this._kv.batchPut(e.map(e=>({...e,key:this.getFullKey(e.key)})),{...t,prefix:""})}async list(e){const t=e?.removePrefix??!0;return this._kv.list({...e,prefix:this._prefix,removePrefix:t})}async changes(e){if(""===this._prefix.replace(/\/+$/,""))return Lt($t(Ct.INVALID_INPUT,"KV changes needs a non-empty prefix; this view has none","kv"));const t=`${this._prefix}/`,r=await this._kv.changes({...e,prefix:t});return r.ok?Ut({...r.data,changes:r.data.changes.map(e=>({...e,key:e.key.startsWith(t)?e.key.slice(t.length):e.key}))}):r}async delete(e,t){const r=this.getFullKey(e);return this._kv.delete(r,{...t,prefix:""})}async head(e,t){const r=this.getFullKey(e);return this._kv.head(r,{...t,prefix:""})}async batchHead(e,t){const r=await this._kv.batchHead(e.map(e=>this.getFullKey(e)),{...t,prefix:""});return r.ok?Ut({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async createSignedReadUrl(e,t){const r=this.getFullKey(e);return this._kv.createSignedReadUrl(r,{...t,prefix:""})}withPrefix(t){const r=t.startsWith("/")?t:`/${t}`,s=`${this._prefix}${r}`;return new e(this._kv,s)}},Br="tinycloud.kv/get",Hr="tinycloud.kv/put",Zr="tinycloud.kv/list",Wr="tinycloud.kv/del",Gr="tinycloud.kv/metadata",zr="tinycloud.kv/sync";function Jr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Qr=new TextEncoder,Yr=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/;function Xr(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function es(e,t,r,s){if(413!==r)return;const n=s.split(":",1)[0].trim();let i;return i=n===`${e}_request_too_large`||n!==`${e}_response_too_large`&&["batch","executeStatement","import"].includes(t),i?`${e.toUpperCase()}_REQUEST_TOO_LARGE`:void 0}(class extends Fr{constructor(e={}){super(),this.readThrough=null,this.readThroughReady=null,this._config=e}setReadThroughReady(e){const t=e.then(()=>{},()=>{});this.readThroughReady=t,t.then(()=>{this.readThroughReady===t&&(this.readThroughReady=null)})}get config(){return this._config}setReadThrough(e){this.readThrough=e}handleQuotaErrorResponse(e,t,r){if((402===e.status||413===e.status)&&(413!==e.status||Vr(t)))return Lt(qr("kv",e.status,{status:e.status,statusText:e.statusText,key:r},t))}async classifyNotFound(e,t){const r=await e.text();return/space not found/i.test(r)?Lt($t(Ct.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):Lt($t(Ct.KV_NOT_FOUND,`Key not found: ${t}`,"kv"))}getFullPath(e,t){const r=t??this._config.prefix??"";return r?""===e?r:`${r}/${e}`:e}get host(){return this.context.hosts[0]}async invokeOperation(e,t,r,s,n){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"kv",e,t),{headers:n,body:r,signal:s})}serializePutValue(e,t){if(e instanceof Blob)return t&&e.type!==t?new Blob([e],{type:t}):e;if(e instanceof ArrayBuffer)return new Blob([e],{type:t??"application/octet-stream"});if(ArrayBuffer.isView(e)){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return new Blob([r],{type:t??"application/octet-stream"})}return"string"==typeof e?t?new Blob([e],{type:t}):e:JSON.stringify(e)}serializeBatchPutValue(e){const t=e.contentType;if(e.value instanceof Blob)return t&&e.value.type!==t?new Blob([e.value],{type:t}):e.value;if(e.value instanceof ArrayBuffer)return new Blob([e.value],{type:t??"application/octet-stream"});if(ArrayBuffer.isView(e.value)){const r=e.value,s=new Uint8Array(r.byteLength);return s.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),new Blob([s],{type:t??"application/octet-stream"})}if("string"==typeof e.value)return new Blob([e.value],{type:t??"text/plain;charset=UTF-8"});const r=JSON.stringify(e.value);if(void 0===r)throw new Error(`Cannot JSON serialize KV batch value for key "${e.key}"`);return new Blob([r],{type:t??"application/json"})}normalizeBatchPutResponse(e){if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.written)&&t.written.every(e=>"string"==typeof e)&&"number"==typeof t.count?{written:t.written,count:t.count}:void 0}createResponseHeaders(e){return{etag:e.get("etag")??void 0,contentType:e.get("content-type")??void 0,lastModified:e.get("last-modified")??void 0,contentLength:e.get("content-length")?parseInt(e.get("content-length"),10):void 0,get:t=>e.get(t)}}createBatchResponseHeaders(e){const t=new Map(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t]));return this.createResponseHeaders({get:e=>t.get(e.toLowerCase())??null})}parseBatchValue(e,t,r=!1,s=!1){const n=globalThis.atob(e),i=Uint8Array.from(n,e=>e.charCodeAt(0));if(s)return i;const a=(new TextDecoder).decode(i);if(r)return a;const o=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase())?.[1];return o?.includes("application/json")?JSON.parse(a):a}normalizeBatchReadResponse(e,t,r){if(!e||"object"!=typeof e)return;const s=e.results;if(!Array.isArray(s)||s.length!==t.length)return;for(const e of s){if(!e||"object"!=typeof e||"boolean"!=typeof e.ok)return;if(e.ok&&(!e.headers||"object"!=typeof e.headers||Object.values(e.headers).some(e=>"string"!=typeof e)||r&&"string"!=typeof e.dataBase64))return;if(!(e.ok||e.error&&"string"==typeof e.error.code&&"string"==typeof e.error.message))return}if(s.every(e=>"string"==typeof e.key)){const e=new Map(s.map(e=>[e.key,e]));if(e.size!==s.length)return;const r=[];for(const s of t){const t=e.get(s);if(!t)return;r.push(t)}return r}if(s.some(e=>void 0!==e.key))return;const n=t.map((e,t)=>t).sort((e,r)=>function(e,t){const r=Qr.encode(e),s=Qr.encode(t),n=Math.min(r.length,s.length);for(let e=0;e<n;e++)if(r[e]!==s[e])return r[e]-s[e];return r.length-s.length}(t[e],t[r])),i=new Array(s.length);for(let e=0;e<n.length;e++)i[n[e]]=s[e];return i}async batchRead(e,t,r){if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return Lt(br("kv"));if(0===e.length)return Ut({results:[],count:0});if(e.length>100)return Lt($t(Ct.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const s=e[0];return Ut({results:[{key:s,result:t===Br?await this.get(s,r):await this.head(s,r)}],count:1})}if(!this.context.invokeAny)return Lt($t(Ct.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const s=t===Br?r:void 0;if(void 0!==s?.maxResponseBytes&&(!Number.isSafeInteger(s.maxResponseBytes)||s.maxResponseBytes<=0))return Lt($t(Ct.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const n=e.map(e=>this.getFullPath(e,r?.prefix));if(new Set(n).size!==n.length)return Lt($t(Ct.INVALID_INPUT,"KV batch read received duplicate keys after prefix resolution","kv"));const i=this.createRequestSignal(r?.signal,r?.timeout);try{const r={};void 0!==s?.maxResponseBytes&&(r["x-tinycloud-max-response-bytes"]=String(s.maxResponseBytes));const a=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.session;return this.context.invokeAny(e,n.map(r=>({spaceId:e.spaceId,service:"kv",path:r,action:t})))},{headers:r,signal:i.signal});if(!a.ok){const r=401===a.status||403===a.status?await this.readAuthorizationText(a):await a.text();return 401===a.status||403===a.status?this.authorizationFailure(`Failed to batch read ${e.length} key(s)`,a,r,n,t):413===a.status?Lt($t(Ct.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:a.status,statusText:a.statusText}})):Lt($t(Ct.NETWORK_ERROR,`Failed to batch read ${e.length} key(s): ${a.status} - ${r}`,"kv",{meta:{status:a.status,statusText:a.statusText}}))}const o=this.normalizeBatchReadResponse(await a.json(),n,t===Br);if(!o)return Lt($t(Ct.NETWORK_ERROR,"KV batch read response did not match the requested keys","kv"));const c=o.map((r,n)=>{if(!r.ok)return{key:e[n],result:Lt($t(r.error.code,r.error.message,"kv"))};const i=r.headers,a=t===Gr?void 0:this.parseBatchValue(r.dataBase64,i,s?.raw,s?.binary);return{key:e[n],result:Ut({data:a,headers:this.createBatchResponseHeaders(i)})}});return Ut({results:c,count:c.length})}catch(e){return Lt(Mr("kv",e))}finally{i.dispose()}}async parseResponse(e,t=!1,r=!1){if(!e.ok)return;if(r)return new Uint8Array(await e.arrayBuffer());if(t)return await e.text();const s=e.headers.get("content-type");if(s?.includes("application/json"))return await e.json();if(s?.startsWith("text/"))return await e.text();const n=await e.text();if(n)try{return JSON.parse(n)}catch{return n}}async createSignedReadUrlError(e,t,r){let s=e.statusText;try{const t=await e.text();t&&(s=t)}catch{}return 401===e.status||403===e.status?this.authorizationFailure(`Failed to create signed read URL for key ${JSON.stringify(t)}`,e,s,[r],Br):Lt($t(400===e.status?Ct.INVALID_INPUT:Ct.NETWORK_ERROR,`Failed to create signed read URL for key ${JSON.stringify(t)}: ${e.status} - ${s}`,"kv",{meta:{status:e.status,statusText:e.statusText}}))}async readAuthorizationText(e){try{return await e.text()}catch{return""}}authorizationFailure(e,t,r,s,n,i={}){const{resource:a,action:o}=Rr(r),c=s.find(e=>a===e||a===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&o===n?xr({service:"kv",code:Ct.AUTH_UNAUTHORIZED,meta:{status:t.status,resource:`${this.context.session.spaceId}/kv/${c}`,requiredAction:o}}):void 0,d=r.trim().length>0?r:t.statusText||"authorization failed";return Lt((l=`${e}: ${t.status} - ${d}`,h={status:t.status,...i,...u},$t(Ct.AUTH_UNAUTHORIZED,l,"kv",{meta:h})));var l,h}normalizeSignedReadUrlResponse(e){if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.url&&"string"==typeof t.ticketId&&"string"==typeof t.expiresAt?{url:new URL(t.url,this.host).toString(),relativeUrl:t.url,ticketId:t.ticketId,expiresAt:t.expiresAt}:void 0}async get(e,t){return this.withTelemetry("get",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return Lt(br("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return Lt($t(Ct.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const r=this.getFullPath(e,t?.prefix),s=this.createRequestSignal(t?.signal,t?.timeout);try{const n=()=>this.getFromNetwork(e,r,t,s.signal);if("network"===t?.source){const e=this.readThrough;if(null===e)return await n();let t="error";const s=Date.now();try{const e=await n();return t=e.ok?"found":e.error.code===Ct.KV_NOT_FOUND?"not_found":"error",e}finally{try{e.observeNetworkRequested({op:"get",space:this.context.session.spaceId,path:r,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:Date.now()-s})}catch{}}}return null===this.readThrough?await n():await this.readThrough.get({space:this.context.session.spaceId,key:e,path:r,options:t,signal:s.signal,network:n})}catch(e){return Lt(Mr("kv",e))}finally{s.dispose()}})}async getFromNetwork(e,t,r,s){const n=await this.invokeOperation(t,Br,void 0,s,void 0===r?.maxResponseBytes?void 0:{"x-tinycloud-max-response-bytes":String(r.maxResponseBytes)});if(!n.ok){if(401===n.status||403===n.status){const r=await this.readAuthorizationText(n),s=function(e){try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return;const r=t,s=r.error,n="object"==typeof s&&null!==s?s:void 0;return Er(r.permissionHint)??Er(n?.permissionHint)}catch{return}}(r),i="tinycloud.kv"===s?.service&&s.space===this.context.session.spaceId&&s.path===t?xr({service:"kv",code:Ct.AUTH_UNAUTHORIZED,meta:{status:n.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:Br}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,n,r,[t],Br,i?{permissionHint:s,...i}:{})}if(404===n.status)return this.classifyNotFound(n,e);const r=await n.text();if(413===n.status)return Lt($t(Ct.KV_RESPONSE_TOO_LARGE,`KV value at key ${JSON.stringify(e)} exceeds the requested response limit`,"kv",{meta:{status:n.status,statusText:n.statusText}}));const s=`Failed to get key ${JSON.stringify(e)}: ${n.status} - ${r}`,i=wr("kv",s,n,r);return Lt(i||$t(Ct.NETWORK_ERROR,s,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return Ut({data:await this.parseResponse(n,r?.raw,r?.binary),headers:this.createResponseHeaders(n.headers),...n.retry&&{retry:n.retry}})}async batchGet(e,t){return this.withTelemetry("batchGet",String(e.length),()=>this.batchRead(e,Br,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return Lt(br("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return Lt($t(Ct.INVALID_INPUT,"KV put cannot combine ifMatch and ifNoneMatch","kv"));const s=this.getFullPath(e,r?.prefix),n=this.serializePutValue(t,r?.contentType),i=this.createRequestSignal(r?.signal,r?.timeout);try{const t=()=>this.putToNetwork(e,s,n,r,i.signal);return null===this.readThrough?await t():await this.readThrough.write({op:"put",space:this.context.session.spaceId,entries:[{path:s,body:n}],signal:i.signal,conditional:void 0!==r?.ifMatch||void 0!==r?.ifNoneMatch,network:t})}catch(e){return Lt(Mr("kv",e))}finally{i.dispose()}})}async putToNetwork(e,t,r,s,n){const i=await this.invokeOperation(t,Hr,r,n,{...void 0===s?.ifMatch?{}:{"if-match":s.ifMatch},...void 0===s?.ifNoneMatch?{}:{"if-none-match":s.ifNoneMatch}});if(401===i.status||403===i.status)return this.authorizationFailure(`Failed to put key ${JSON.stringify(e)}`,i,await this.readAuthorizationText(i),[t],Hr);if(!i.ok){const t=await i.text();if(412===i.status)return Lt($t(Ct.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:i.status,statusText:i.statusText}}));const r=`Failed to put key ${JSON.stringify(e)}: ${i.status} - ${t}`,s=wr("kv",r,i,t);if(s)return Lt(s);return this.handleQuotaErrorResponse(i,t,e)||Lt($t(Ct.KV_WRITE_FAILED,r,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return Ut({data:void 0,headers:this.createResponseHeaders(i.headers),...i.retry&&{retry:i.retry}})}async batchPut(e,t){return this.withTelemetry("batchPut",String(e.length),async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return Lt(br("kv"));if(0===e.length)return Ut({written:[],count:0});if(!this.context.invokeAny)return Lt($t(Ct.INVALID_INPUT,"KV batchPut requires SDK runtime support for multi-resource invocations","kv"));const r=this.context.session,s=e.map(e=>this.getFullPath(e.key,t?.prefix)),n=new Set;for(const e of s){if(n.has(e))return Lt($t(Ct.INVALID_INPUT,`KV batchPut received duplicate key after prefix resolution: ${e}`,"kv"));n.add(e)}const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=()=>this.batchPutToNetwork(e,s,i.signal);if(null===this.readThrough)return await t();const n=e.map((e,t)=>({path:s[t],body:this.serializeBatchPutValue(e)}));return await this.readThrough.write({op:"batchPut",space:r.spaceId,entries:n,signal:i.signal,network:()=>this.batchPutToNetwork(e,s,i.signal,n)})}catch(e){const t=Mr("kv",e);return Lt({...t,meta:{...t.meta,requestMayHaveDispatched:!1}})}finally{i.dispose()}})}async batchPutToNetwork(e,t,r,s){const n=this.context.session;let i=!1;try{const a=new FormData;for(let r=0;r<e.length;r++)a.append(Xr(t[r]),s?.[r]?.body??this.serializeBatchPutValue(e[r]));const o=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.invokeAny(n,t.map(e=>({spaceId:n.spaceId,service:"kv",path:e,action:Hr})));return i=!0,e},{body:a,signal:r});if(!o.ok){let r;try{r=await o.text()}catch(t){const r=t instanceof Error?t:new Error(String(t));return Lt($t(Ct.KV_WRITE_FAILED,`Failed to batch put ${e.length} key(s): ${o.status} - <response body could not be read: ${r.message}>`,"kv",{cause:r,meta:{status:o.status,statusText:o.statusText}}))}if(401===o.status||403===o.status)return this.authorizationFailure(`Failed to batch put ${e.length} key(s)`,o,r,t,Hr);return this.handleQuotaErrorResponse(o,r,"batch")||Lt($t(Ct.KV_WRITE_FAILED,`Failed to batch put ${e.length} key(s): ${o.status} - ${r}`,"kv",{meta:{status:o.status,statusText:o.statusText}}))}let c;try{c=await o.json()}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=Nr(t);return Lt($t(r?Ct.TIMEOUT:Ct.NETWORK_ERROR,r?`KV batchPut response body did not arrive in time: ${t.message}`:`KV batchPut response was not valid JSON: ${t.message}`,"kv",{cause:t,meta:{...r?{timeoutMs:t.timeoutMs}:{},requestMayHaveDispatched:!0,responseReceived:!0,status:o.status,outcome:"batch-unconfirmed"}}))}const u=this.normalizeBatchPutResponse(c);if(!u)return Lt($t(Ct.NETWORK_ERROR,"KV batchPut response did not include matching written keys and count","kv",{meta:{requestMayHaveDispatched:!0,responseReceived:!0,status:o.status,outcome:"batch-unconfirmed"}}));const d=new Set(t),l=new Set(u.written);return u.count===t.length&&u.written.length===t.length&&l.size===t.length&&u.written.every(e=>d.has(e))?Ut(u):Lt($t(Ct.NETWORK_ERROR,`KV batchPut response did not confirm all ${t.length} requested key(s) were written`,"kv",{meta:{requestMayHaveDispatched:!0,responseReceived:!0,status:o.status,outcome:"batch-unconfirmed"}}))}catch(e){const t=Mr("kv",e);return Lt({...t,meta:{...t.meta,requestMayHaveDispatched:i}})}}async list(e){return this.withTelemetry("list",e?.prefix,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return Lt(br("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return Lt($t(Ct.INVALID_INPUT,"KV list limit must be an integer from 1 through 1000","kv"));let t=e?.prefix??this._config.prefix??"";e?.path&&(t=t?`${t}/${e.path}`:e.path);const r=this.createRequestSignal(e?.signal,e?.timeout);try{const s=()=>this.listFromNetwork(t,e,r.signal);let n;if("network"===e?.source){const e=this.readThrough;if(null===e)n=await s();else{let r="error";const i=Date.now();try{n=await s(),r=n.ok?"found":"error"}finally{try{e.observeNetworkRequested({op:"list",space:this.context.session.spaceId,path:t,reason:"NETWORK_REQUESTED",outcome:r,latencyMs:Date.now()-i})}catch{}}}}else n=null===this.readThrough?await s():await this.readThrough.list({space:this.context.session.spaceId,listPath:t,options:e,signal:r.signal,network:s});return n.ok?this.finishList(n.data,t,e?.removePrefix):n}catch(e){return Lt(Mr("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const s=await this.invokeOperation(e,Zr,void 0,r,void 0===t?.limit&&void 0===t?.cursor?void 0:{...void 0===t?.limit?{}:{"x-tinycloud-limit":String(t.limit)},...void 0===t?.cursor?{}:{"x-tinycloud-cursor":t.cursor}});if(!s.ok){if(401===s.status||403===s.status)return this.authorizationFailure("Failed to list keys",s,await this.readAuthorizationText(s),[e],Zr);const t=await s.text(),r=`Failed to list keys: ${s.status} - ${t}`,n=wr("kv",r,s,t);return Lt(n||$t(Ct.NETWORK_ERROR,r,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return Ut({keys:await this.parseResponse(s,t?.raw)??[],...null===s.headers.get("x-tinycloud-truncated")?{}:{truncated:"true"===s.headers.get("x-tinycloud-truncated")},...null===s.headers.get("x-tinycloud-next-cursor")?{}:{nextCursor:s.headers.get("x-tinycloud-next-cursor")??void 0}})}finishList(e,t,r){let s=e.keys;if(r&&t){const e=t.endsWith("/")?t:`${t}/`;s=s.map(t=>t.startsWith(e)?t.slice(e.length):t)}return Ut({keys:s,...void 0===e.truncated?{}:{truncated:e.truncated},...void 0===e.nextCursor?{}:{nextCursor:e.nextCursor}})}async changes(e){return this.withTelemetry("changes",e?.prefix,async()=>{if(!this.requireAuth())return Lt(br("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return Lt($t(Ct.INVALID_INPUT,"KV changes prefix must be a non-empty string","kv"));if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return Lt($t(Ct.INVALID_INPUT,"KV changes limit must be an integer from 1 through 1000","kv"));const t="/"===e.prefix?"":e.prefix,r={};void 0!==e.limit&&(r["x-tinycloud-limit"]=String(e.limit)),void 0!==e.cursor&&(r["x-tinycloud-cursor"]=e.cursor),void 0!==e.retentionGrant&&(r["x-tinycloud-retention-grant"]=e.retentionGrant);const s=this.createRequestSignal(e.signal,e.timeout);try{const n=await this.invokeOperation(t,zr,void 0,s.signal,r);if(!n.ok)return await this.changesFailure(n,e.prefix,s.signal);const i=await n.text();let a;try{a=JSON.parse(i)}catch{a=void 0}const o=this.normalizeChangesResponse(a,e.prefix);return o?Ut(o):Lt($t(Ct.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:n.status,statusText:n.statusText}}))}catch(e){return Lt(Mr("kv",e))}finally{s.dispose()}})}async changesFailure(e,t,r){if(404===e.status)return this.classifyNotFound(e,t);let s;try{s=await e.text()}catch(e){if(r.aborted)throw e;s=""}const n={status:e.status,statusText:e.statusText};let i,a;try{const e=JSON.parse(s),t=Jr(e)?e.error:void 0;Jr(t)&&("string"==typeof t.code&&(a=t.code),"string"==typeof t.reason&&(i=t.reason))}catch{}const o=`Failed to read KV changes for ${JSON.stringify(t)}`;if(410===e.status)return Lt($t(Ct.KV_SYNC_RESET_REQUIRED,`${o}: the node requires a reset (${i??"reason not given"}); discard sync state and restart without a cursor`,"kv",{meta:{...n,reason:i}}));if(403===e.status&&"RETENTION_GRANT_REFUSED"===a)return Lt($t(Ct.KV_RETENTION_GRANT_REFUSED,`${o}: the retention grant was refused (${i??"reason not given"})`,"kv",{meta:{...n,reason:i}}));if(401===e.status){const e=function(e){const t=Yr.exec(e.trim());if(null!==t)return void 0!==t[1]?Ct.AUTH_DELEGATION_REVOKED:Ct.AUTH_DELEGATION_ANCESTOR_REVOKED}(s);if(void 0!==e)return Lt($t(e,`${o}: 401 - ${s}`,"kv",{meta:n}))}return 401===e.status||403===e.status?this.authorizationFailure(o,e,s,[t],zr):Lt($t(400===e.status?Ct.INVALID_INPUT:Ct.NETWORK_ERROR,`${o}: ${e.status} - ${s}`,"kv",{meta:n}))}normalizeChangesResponse(e,t){if(!Jr(e))return;const{changes:r,more:s,cursor:n,source:i,authority:a}=e;if(!Array.isArray(r)||"boolean"!=typeof s||"string"!=typeof n||!Jr(i)||"string"!=typeof i.nodeDid||"string"!=typeof i.space||"string"!=typeof i.prefix||!Jr(a))return;const{notBefore:o,expiresAt:c,retainUntil:u}=a;if(null!==o&&"string"!=typeof o||null!==c&&"string"!=typeof c||null!==u&&"string"!=typeof u)return;const d=[];for(const e of r){if(!Jr(e)||"string"!=typeof e.key)return;if(!0===e.deleted){d.push({key:e.key,deleted:!0});continue}const{metadata:t}=e;if(!1!==e.deleted||"string"!=typeof e.etag||!Jr(t)||!Object.values(t).every(e=>"string"==typeof e))return;d.push({key:e.key,deleted:!1,etag:e.etag,metadata:t})}return{changes:d,more:s,cursor:n,source:{nodeDid:i.nodeDid,space:i.space,prefix:"/"===t&&""===i.prefix?"/":i.prefix},authority:{notBefore:o,expiresAt:c,retainUntil:u}}}async delete(e,t){return this.withTelemetry("delete",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return Lt(br("kv"));const r=this.getFullPath(e,t?.prefix),s=this.createRequestSignal(t?.signal,t?.timeout);try{const n=()=>this.deleteFromNetwork(e,r,t,s.signal);return null===this.readThrough?await n():await this.readThrough.write({op:"delete",space:this.context.session.spaceId,entries:[{path:r}],signal:s.signal,conditional:void 0!==t?.ifMatch,network:n})}catch(e){return Lt(Mr("kv",e))}finally{s.dispose()}})}async deleteFromNetwork(e,t,r,s){const n=await this.invokeOperation(t,Wr,void 0,s,void 0===r?.ifMatch?void 0:{"if-match":r.ifMatch});if(!n.ok){if(401===n.status||403===n.status)return this.authorizationFailure(`Failed to delete key ${JSON.stringify(e)}`,n,await this.readAuthorizationText(n),[t],Wr);if(404===n.status)return this.classifyNotFound(n,e);const r=await n.text();if(412===n.status)return Lt($t(Ct.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:n.status,statusText:n.statusText}}));const s=`Failed to delete key ${JSON.stringify(e)}: ${n.status} - ${r}`,i=wr("kv",s,n,r);return Lt(i||$t(Ct.NETWORK_ERROR,s,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return Ut({data:void 0,headers:this.createResponseHeaders(n.headers),...n.retry&&{retry:n.retry}})}async head(e,t){return this.withTelemetry("head",e,async()=>{if(!this.requireAuth())return Lt(br("kv"));const r=this.getFullPath(e,t?.prefix),s=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,Gr,void 0,s.signal);if(!t.ok){if(401===t.status||403===t.status)return this.authorizationFailure(`Failed to get metadata for key ${JSON.stringify(e)}`,t,await this.readAuthorizationText(t),[r],Gr);if(404===t.status)return await this.classifyNotFound(t,e);const s=await t.text(),n=`Failed to get metadata for key ${JSON.stringify(e)}: ${t.status} - ${s}`,i=wr("kv",n,t,s);return Lt(i||$t(Ct.NETWORK_ERROR,n,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return Ut({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return Lt(Mr("kv",e))}finally{s.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,Gr,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return Lt(br("kv"));const r=this.getFullPath(e,t?.prefix),s=this.context.session,n={space:s.spaceId,path:r,ttl_seconds:t?.expiresInSeconds??Math.ceil(300)};void 0!==t?.contentHash&&(n.content_hash=t.contentHash),void 0!==t?.etag&&(n.etag=t.etag);const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeWithRetry(`${this.host}/signed/kv`,()=>this.context.invoke(s,"kv",r,Br),{headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:i.signal});if(!t.ok)return await this.createSignedReadUrlError(t,e,r);const a=this.normalizeSignedReadUrlResponse(await t.json());return a?Ut(a):Lt($t(Ct.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return Lt(Mr("kv",e))}finally{i.dispose()}})}withPrefix(e){return new jr(this,e)}}).serviceName="kv";var ts=class{constructor(e,t){this.service=e,this.dbName=t}apply(e){return this.service.applyMigrationsOnDb(this.dbName,e)}},rs=class{constructor(e,t){this.service=e,this.name=t,this.migrations=new ts(e,t)}async query(e,t,r){return this.service.queryOnDb(this.name,e,t,r)}async execute(e,t,r){return this.service.executeOnDb(this.name,e,t,r)}async batch(e,t){return this.service.batchOnDb(this.name,e,t)}async executeStatement(e,t,r){return this.service.executeStatementOnDb(this.name,e,t,r)}async export(e){return this.service.exportDb(this.name,e)}},ss={READ:et.READ,WRITE:et.WRITE,SCHEMA:et.SCHEMA,ADMIN:et.ADMIN,SELECT:et.SELECT,EXECUTE:et.EXECUTE,EXPORT:et.EXPORT,ALL:et.ALL},ns=new Set(["alter","create","drop"]),is="__tinycloud_sql_migrations",as=`CREATE TABLE IF NOT EXISTS ${is} (\n key TEXT PRIMARY KEY,\n namespace TEXT NOT NULL,\n id TEXT NOT NULL,\n applied_at TEXT NOT NULL,\n statement_count INTEGER NOT NULL\n)`,os="tinycloud.sql.migrations",cs="000_metadata";function us(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function ds(e){return/no such table/i.test(e)}function ls(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function hs(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends Fr{constructor(e={}){super(),this.migrationLocks=new Map,this._config=e}get config(){return this._config}get defaultDbName(){return this._config.defaultDatabase??"default"}get host(){return this.context.hosts[0]}db(e){return new rs(this,e??this.defaultDbName)}async query(e,t,r){return this.queryOnDb(this.defaultDbName,e,t,r)}async execute(e,t,r){return this.executeOnDb(this.defaultDbName,e,t,r)}async batch(e,t){return this.batchOnDb(this.defaultDbName,e,t)}async applyMigrationsOnDb(e,t){const r=function(e){if(!e||"object"!=typeof e)return"SQL migrations require options";if(!e.namespace||"string"!=typeof e.namespace)return"SQL migrations require a non-empty namespace";if(!Array.isArray(e.migrations))return"SQL migrations require an ordered migrations array";const t=new Set;for(const r of e.migrations){if(!r.id||"string"!=typeof r.id)return"SQL migrations require every migration to have a non-empty id";if(t.has(r.id))return`Duplicate SQL migration id: ${r.id}`;if(t.add(r.id),!Array.isArray(r.sql))return`SQL migration ${r.id} requires a sql array`;for(const e of r.sql)if("string"!=typeof e){if(!e||"string"!=typeof e.sql||""===e.sql.trim())return`SQL migration ${r.id} contains an invalid statement`}else if(""===e.trim())return`SQL migration ${r.id} contains an empty statement`}return null}(t);if(r)return Lt($t(Ct.INVALID_INPUT,r,"sql"));const s=`${e}\0${t.namespace}`,n=this.migrationLocks.get(s);if(n)return n;const i=this.applyMigrationsOnDbUnlocked(e,t);this.migrationLocks.set(s,i);try{return await i}finally{this.migrationLocks.delete(s)}}async queryOnDb(e,t,r,s){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return Lt(br("sql"));const n=this.createRequestSignal(s?.signal);try{const i={action:"query",sql:t,params:us(r??[])};void 0!==s?.maxRows&&(i.maxRows=s.maxRows),void 0!==s?.maxBytes&&(i.maxBytes=s.maxBytes);const a=this.actionForSql(t,ss.READ),o=await this.invokeSQL(e,a,i,n.signal);if(!o.ok){const t=await this.handleErrorResponse(o,"query",e,[a]);return this.redactFailure(t,s?.redactErrors,o.status)}return Ut(await o.json())}catch(e){return this.redactFailure(Lt(Mr("sql",e)),s?.redactErrors)}finally{n.dispose()}})}async executeOnDb(e,t,r,s){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return Lt(br("sql"));const n=this.createRequestSignal(s?.signal);try{const i={action:"execute",sql:t,params:us(r??[])};s?.schema&&(i.schema=s.schema);const a=[this.actionForSql(t,ss.WRITE),...(s?.schema??[]).map(e=>this.actionForSql(e,ss.SCHEMA))],o=this.dedupeActions(a),c=await this.invokeSQL(e,o,i,n.signal);if(!c.ok){const t=await this.handleErrorResponse(c,"execute",e,o);return this.redactFailure(t,s?.redactErrors,c.status)}return Ut(await c.json())}catch(e){return this.redactFailure(Lt(Mr("sql",e)),s?.redactErrors)}finally{n.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return Lt(br("sql"));const s=this.createRequestSignal(r?.signal);try{const n=this.actionsForSqlBatch(t),i=await this.invokeSQL(e,n,{action:"batch",statements:t},s.signal);if(!i.ok){const t=await this.handleErrorResponse(i,"batch",e,n);return this.redactFailure(t,r?.redactErrors,i.status)}return Ut(await i.json())}catch(e){return this.redactFailure(Lt(Mr("sql",e)),r?.redactErrors)}finally{s.dispose()}})}async executeStatementOnDb(e,t,r,s){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return Lt(br("sql"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeSQL(e,ss.WRITE,{action:"execute_statement",name:t,params:r??[]},n.signal);return s.ok?Ut(await s.json()):await this.handleErrorResponse(s,"executeStatement",e,[ss.WRITE])}catch(e){return Lt(Mr("sql",e))}finally{n.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return Lt(br("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,ss.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[ss.READ]);const s=t;return"function"==typeof s.blob?Ut(await s.blob()):Ut(await t.text())}catch(e){return Lt(Mr("sql",e))}finally{r.dispose()}})}async applyMigrationsOnDbUnlocked(e,t){return this.withTelemetry("migrations.apply",e,async()=>{const r=await this.queryOnDb(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${is}'`,[],{signal:t.signal});let s=r.ok?0===r.data.rows.length:r.error.code===Ct.SQL_DATABASE_NOT_FOUND||ds(r.error.message);if(!r.ok&&!s)return r;const n=new Set;if(!s){const r=await this.queryOnDb(e,`SELECT id FROM ${is} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(s=!r.ok&&(r.error.code===Ct.SQL_DATABASE_NOT_FOUND||ds(r.error.message)),!r.ok&&!s)return r;if(r.ok)for(const e of r.data.rows){const t=hs(e,0);"string"==typeof t&&n.add(t)}}const i=t.migrations.filter(e=>n.has(e.id)).map(e=>e.id),a=t.migrations.filter(e=>!n.has(e.id)),o=[];if(a.length>0&&s){const r=await this.ensureMigrationsTable(e,t.signal);if(!r.ok)return r}for(const r of a){const s=await this.applyOneMigration(e,t.namespace,r,t.signal);if(!s.ok)return s;o.push(r.id)}return Ut({database:e,namespace:t.namespace,status:o.length>0?"applied":"already_current",applied:o,skipped:i})})}async applyOneMigration(e,t,r,s){const n=[...r.sql.map(e=>"string"==typeof e?{sql:e}:e),{sql:`INSERT OR REPLACE INTO ${is} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[ls(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],i=await this.batchOnDb(e,n,{signal:s});return i.ok?Ut(void 0):i}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:as},{sql:`INSERT OR REPLACE INTO ${is} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[ls(os,cs),os,cs,(new Date).toISOString(),1]}],{signal:t});return r.ok?Ut(void 0):r}async invokeSQL(e,t,r,s){const n=Array.isArray(t)?t:[t];return this.invokeWithRetry(`${this.host}/invoke`,()=>{const t=this.context.session;return 1===n.length?this.context.invoke(t,"sql",e,n[0]):this.invokeSQLAny(t,e,n)},{headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:s})}actionForSql(e,t){const r=function(e){let t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(e.startsWith("--",t)){const r=e.indexOf("\n",t+2);if(-1===r)return;t=r+1;continue}if(e.startsWith("/*",t)){const r=e.indexOf("*/",t+2);if(-1===r)return;t=r+2;continue}break}const r=/^[A-Za-z_]+/.exec(e.slice(t));return r?.[0].toLowerCase()}(e);return"pragma"===r?ss.ADMIN:void 0!==r&&ns.has(r)?ss.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,ss.WRITE)))}dedupeActions(e){return[...new Set(e)]}invokeSQLAny(e,t,r){if(!this.context.invokeAny)throw new Error(`SQL operation requires multiple permissions (${r.join(", ")}) but this SDK runtime does not support multi-resource invocations`);return this.context.invokeAny(e,r.map(r=>({spaceId:e.spaceId,service:"sql",path:t,action:r})))}redactFailure(e,t,r){if(!t||e.ok)return e;const s=e.error.code,n="string"==typeof s&&Object.prototype.hasOwnProperty.call(Ct,s)?s:Ct.SQL_ERROR,i="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return Lt($t(n,"SQL operation failed","sql",void 0===i?void 0:{meta:{status:i}}))}async handleErrorResponse(e,t,r,s){const n=await e.text(),i=ur(e.status,e.statusText,n);if(402===e.status)return Lt(qr("sql",402,i,n));if(413===e.status&&Vr(n))return Lt(qr("sql",413,i,n));const a=wr("sql",`SQL ${t} failed: ${e.status} - ${n}`,e,n);if(a)return Lt(a);const o=or(n),c=es("sql",t,e.status,n)??this.mapHttpStatusToErrorCode(e.status,o.error),u=cr("SQL",t,e.status,n,o);if(401===e.status){const{action:e}=Rr(n);e&&s.includes(e)&&(i.requiredAction=e,i.resource=`${this.context.session.spaceId}/sql/${r}`)}return Lt($t(c,u,"sql",{meta:i}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return Ct.SQL_ERROR;case 401:return Ct.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?Ct.SQL_READONLY_VIOLATION:Ct.SQL_PERMISSION_DENIED;case 404:return Ct.SQL_DATABASE_NOT_FOUND;case 413:return Ct.SQL_RESPONSE_TOO_LARGE;case 429:return Ct.SQL_QUOTA_EXCEEDED;default:return Ct.NETWORK_ERROR}}}).serviceName="sql";var ps=class{constructor(e,t){this.service=e,this.name=t}async query(e,t,r){return this.service.queryOnDb(this.name,e,t,r)}async queryArrow(e,t,r){return this.service.queryArrowOnDb(this.name,e,t,r)}async execute(e,t,r){return this.service.executeOnDb(this.name,e,t,r)}async batch(e,t){return this.service.batchOnDb(this.name,e,t)}async executeStatement(e,t,r){return this.service.executeStatementOnDb(this.name,e,t,r)}async describe(e){return this.service.describeDb(this.name,e)}async export(e){return this.service.exportOnDb(this.name,e)}async import(e,t){return this.service.importOnDb(this.name,e,t)}},ys={READ:tt.READ,WRITE:tt.WRITE,ADMIN:tt.ADMIN,DESCRIBE:tt.DESCRIBE,EXPORT:tt.EXPORT,IMPORT:tt.IMPORT,EXECUTE:tt.EXECUTE,ALL:tt.ALL};(class extends Fr{constructor(e={}){super(),this._config=e}get config(){return this._config}get defaultDbName(){return this._config.defaultDatabase??"default"}get host(){return this.context.hosts[0]}db(e){return new ps(this,e??this.defaultDbName)}async query(e,t,r){return this.queryOnDb(this.defaultDbName,e,t,r)}async queryArrow(e,t,r){return this.queryArrowOnDb(this.defaultDbName,e,t,r)}async execute(e,t,r){return this.executeOnDb(this.defaultDbName,e,t,r)}async batch(e,t){return this.batchOnDb(this.defaultDbName,e,t)}async queryOnDb(e,t,r,s){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeDuckDb(e,ys.READ,{action:"query",sql:t,params:r??[]},n.signal);return s.ok?Ut(await s.json()):await this.handleErrorResponse(s,"query")}catch(e){return Lt(Mr("duckdb",e))}finally{n.dispose()}})}async queryArrowOnDb(e,t,r,s){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeDuckDb(e,ys.READ,{action:"query",sql:t,params:r??[]},n.signal,{Accept:"application/vnd.apache.arrow.stream"});return s.ok?Ut(await s.arrayBuffer()):await this.handleErrorResponse(s,"queryArrow")}catch(e){return Lt(Mr("duckdb",e))}finally{n.dispose()}})}async executeOnDb(e,t,r,s){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const n=this.createRequestSignal(s?.signal);try{const i={action:"execute",sql:t,params:r??[]};s?.schema&&(i.schema=s.schema);const a=await this.invokeDuckDb(e,ys.WRITE,i,n.signal);return a.ok?Ut(await a.json()):await this.handleErrorResponse(a,"execute")}catch(e){return Lt(Mr("duckdb",e))}finally{n.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const s=this.createRequestSignal(r?.signal);try{const n={action:"batch",statements:t};void 0!==r?.transactional&&(n.transactional=r.transactional);const i=await this.invokeDuckDb(e,ys.WRITE,n,s.signal);return i.ok?Ut(await i.json()):await this.handleErrorResponse(i,"batch")}catch(e){return Lt(Mr("duckdb",e))}finally{s.dispose()}})}async executeStatementOnDb(e,t,r,s){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeDuckDb(e,ys.WRITE,{action:"executeStatement",name:t,params:r??[]},n.signal);return s.ok?Ut(await s.json()):await this.handleErrorResponse(s,"executeStatement")}catch(e){return Lt(Mr("duckdb",e))}finally{n.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,ys.READ,{action:"describe"},r.signal);return t.ok?Ut(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return Lt(Mr("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,ys.EXPORT,{action:"export"},r.signal);return t.ok?Ut(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return Lt(Mr("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return Lt(br("duckdb"));const s=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,ys.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:s.signal});return r.ok?Ut(void 0):await this.handleErrorResponse(r,"import")}catch(e){return Lt(Mr("duckdb",e))}finally{s.dispose()}})}async invokeDuckDb(e,t,r,s,n){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,t),{headers:{"Content-Type":"application/json",...n},body:JSON.stringify(r),signal:s})}async handleErrorResponse(e,t){const r=await e.text(),s=ur(e.status,e.statusText,r);if(402===e.status)return Lt(qr("duckdb",402,s,r));if(413===e.status&&Vr(r))return Lt(qr("duckdb",413,s,r));const n=wr("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(n)return Lt(n);const i=or(r),a=es("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,i.error),o=cr("DuckDB",t,e.status,r,i);if(401===e.status){const{resource:e,action:t}=Rr(r);t&&(s.requiredAction=t),e&&(s.resource=e)}return Lt($t(a,o,"duckdb",{meta:s}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return Ct.DUCKDB_ERROR;case 401:return Ct.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?Ct.DUCKDB_READONLY_VIOLATION:Ct.DUCKDB_PERMISSION_DENIED;case 404:return Ct.DUCKDB_DATABASE_NOT_FOUND;case 413:return Ct.DUCKDB_RESPONSE_TOO_LARGE;case 429:return Ct.DUCKDB_QUOTA_EXCEEDED;default:return Ct.NETWORK_ERROR}}}).serviceName="duckdb";var fs=class{constructor(){this.values=[],this.waiters=[],this.closed=!1}[Symbol.asyncIterator](){return this}push(e){if(this.closed)return;const t=this.waiters.shift();t?t.resolve({value:e,done:!1}):this.values.push(e)}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const e=this.waiters.shift();e?.resolve({value:void 0,done:!0})}}fail(e){if(!this.closed)for(this.closed=!0,this.failure=e;this.waiters.length>0;){const t=this.waiters.shift();t?.reject(e)}}next(){if(this.values.length>0){const e=this.values.shift();return Promise.resolve({value:e,done:!1})}return void 0!==this.failure?Promise.reject(this.failure):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function ms(e,t){const r=Ds(t);return r?`${e}/${r}`:e}function gs(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends Fr{constructor(e={}){super(),this._subscribers=new Set,this._supervising=!1,this._sessionGeneration=0,this._streamGeneration=0,this._config=e}get config(){return this._config}get host(){return this._config.host??this.context.hosts[0]}async*subscribe(e,t={}){if(!this.requireAuth())throw new Error("Authentication required for hooks subscription");if(0===e.length)throw new Error("At least one hook subscription is required");const r=e.map(Is),s={requested:r,signatures:r.map(Ss),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new fs},n=()=>{this._subscribers.delete(s),s.queue.close(),this.wake()},{signal:i}=t;if(!i?.aborted){i?.addEventListener("abort",n,{once:!0}),this._subscribers.add(s),this.wake(),this._readyStream&&this.notifyReady(s,this._readyStream);try{for await(const e of s.queue)yield e}finally{i?.removeEventListener("abort",n),n()}}}async register(e){if(!this.requireAuth())return Lt(br("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return Lt($t(Ct.INVALID_INPUT,"Webhook secret is required","hooks",{meta:{field:"secret"}}));try{const t=await this.invokeWithRetry(`${this.host}/hooks/webhooks`,()=>this.createHookHeaders("tinycloud.hooks/register",ms(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:Ds(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return Lt(await Ps("hooks","failed to register webhook",t));const r=Ls(await t.json());return r?Ut(r):Lt(Mr("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return Lt(Mr("hooks",e))}}async list(e={}){if(!this.requireAuth())return Lt(br("hooks"));try{const t=new URLSearchParams;if(e.space&&t.set("space",e.space),e.service&&t.set("service",e.service),e.pathPrefix){const r=Ds(e.pathPrefix);r&&t.set("prefix",r)}const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks${t.size>0?`?${t.toString()}`:""}`,()=>this.createHookHeaders("tinycloud.hooks/list",e.service?ms(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return Lt(await Ps("hooks","failed to list webhooks",r));const s=function(e){if(Array.isArray(e))return e.map(e=>Ls(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=$s(t.webhooks)??$s(t.subscriptions)??$s(t.hooks)??$s(t.data);if(r)return r;const s=Ks(t);return s?[s]:null}(await r.json());return s?Ut(s):Lt(Mr("hooks",new Error("Webhook list response did not include records")))}catch(e){return Lt(Mr("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return Lt(br("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?ms(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?Ut(void 0):Lt(await Ps("hooks","failed to unregister webhook",r))}catch(e){return Lt(Mr("hooks",e))}}wake(){const e=this._phase;e&&e.key!==this.plan()?.key&&e.interrupt.abort(),this._supervising||0===this._subscribers.size||(this._supervising=!0,this.supervise().catch(()=>this.collapse()))}async supervise(){let e=0;for(;;){const t=this.plan();if(!t)return void(this._supervising=!1);const r={openedAt:0,delivered:!1},s=await this.phase(t.key,e=>this.attempt(t,e,r));(r.delivered||r.openedAt>0&&performance.now()-r.openedAt>=5e3)&&(e=0),s&&this.plan()?.key===t.key&&("stopped"!==s.kind?"refused"===s.kind&&s.terminal?(this.release(s.error),this.report(s.error)):("ended"!==s.kind&&this.report(s.error),e+=1,await this.phase(t.key,t=>this.pause(e,t))):this.release())}}async phase(e,t){const r=new AbortController;this._phase={key:e,interrupt:r};try{this.plan()?.key!==e&&r.abort();const s=await t(r.signal);return r.signal.aborted?void 0:s}finally{this._phase=void 0,r.abort()}}async attempt(e,t,r){let s,n="mint";const i=++this._streamGeneration,a=()=>!t.aborted&&!s?.signal.aborted&&this.plan()?.key===e.key;try{const o=this.context,c=o.abortSignal;if(this._lastContextSignal=c,!o.isAuthenticated||c?.aborted)return{kind:"stopped"};s=this.createRequestSignal(t,0);const u=this.host,d=await _s(s.signal,()=>{return o.fetch(`${u}/hooks/tickets`,{method:"POST",headers:{...(t=this.createInvokeHeaders(e.subscriptions),Array.isArray(t)?Object.fromEntries(t):{...t}),"content-type":"application/json"},body:JSON.stringify({subscriptions:e.subscriptions,ttlSeconds:e.ttlSeconds}),signal:s.signal});var t});if(!a())return{kind:"stopped"};if(!d.ok){const e=d.status,t=await _s(s.signal,()=>Ps("hooks","failed to mint hook ticket",d));return a()?{kind:"refused",terminal:gs(e),error:t}:{kind:"stopped"}}const l=await _s(s.signal,()=>d.json());if(!a())return{kind:"stopped"};const h=null!==l&&"object"==typeof l&&"ticket"in l?l.ticket:void 0;if("string"!=typeof h||0===h.length)throw new Error("Hook ticket response did not include a ticket");if(n="open",!a())return{kind:"stopped"};const p=await _s(s.signal,()=>o.fetch(`${u}/hooks/events?ticket=${encodeURIComponent(h)}`,{method:"GET",headers:{accept:"text/event-stream"},signal:s.signal}));if(!a())return{kind:"stopped"};if(!p.ok)return{kind:"refused",terminal:!1,error:Es(p.status)};r.openedAt=performance.now();const y=async function*(e,t){if(!e)throw new Error("Hook stream response does not expose a readable body");const r=new TextDecoder;let s="";for await(const n of async function*(e,t){const r=e;if("function"==typeof r?.[Symbol.asyncIterator]){const e=r[Symbol.asyncIterator](),s=()=>{try{const t=e.return?.();t&&Promise.resolve(t).then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",s,{once:!0});try{for(;!t?.aborted;){const t=await e.next();if(t.done)break;yield t.value}}finally{t?.removeEventListener("abort",s),s()}return}const s=e;if("function"!=typeof s.getReader)throw new Error("Unsupported hook stream body type");const n=s.getReader(),i=()=>{try{const e=n.cancel?.();e&&e.then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",i,{once:!0});try{for(;!t?.aborted;){const{done:e,value:t}=await n.read();if(e)break;t&&(yield t)}}finally{t?.removeEventListener("abort",i),i(),n.releaseLock?.()}}(e,t)){s+=r.decode(n,{stream:!0}).replace(/\r\n/g,"\n");let e=s.indexOf("\n\n");for(;e>=0;){const t=s.slice(0,e);s=s.slice(e+2);const r=Cs(t);r&&(yield r),e=s.indexOf("\n\n")}}s+=r.decode();const n=Cs(s.trim());n&&(yield n)}(p.body,s.signal)[Symbol.asyncIterator]();try{for(;;){const t=await _s(s.signal,()=>y.next());if(!a())return{kind:"stopped"};if(t.done)break;const n=t.value;if(!n.data)continue;if("ready"===n.event){const t=JSON.parse(n.data);if(null!==t&&"object"==typeof t&&"type"in t&&"ready"===t.type){this._readyStream={key:e.key,generation:i};for(const e of this._subscribers)this.notifyReady(e,this._readyStream)}continue}const o=Us(n);if(!a())return{kind:"stopped"};this.dispatch(o),r.delivered=!0}}finally{const e=y.return?.();e&&Promise.resolve(e).then(()=>{},()=>{})}return a()?{kind:"ended"}:{kind:"stopped"}}catch(e){return s?.signal.aborted||e===vs?{kind:"stopped"}:{kind:"failed",error:ws(n,e)}}finally{this._readyStream?.generation===i&&(this._readyStream=void 0)}}async pause(e,t){try{this._lastContextSignal=this.context.abortSignal}catch{}const r=this._lastContextSignal,s=[],n=[];try{const r=this._config.streamRetry,n=r?.delay?.(e)??function(e){const t=Math.min(250*2**Math.max(0,e-1),3e4);return t/2+Math.random()*(t/2)}(e);s.push((r?.wait??Rs)(n,e,t))}catch{s.push(Promise.resolve())}n.push(As(t)),r&&n.push(As(r));try{await Promise.race([...s,...n.map(({promise:e})=>e)])}catch{}finally{for(const e of n)e.dispose()}await new Promise(e=>setTimeout(e,0))}plan(){if(0===this._subscribers.size)return;const e=new Map;let t;for(const r of this._subscribers)r.requested.forEach((t,s)=>e.set(r.signatures[s],t)),"number"==typeof r.ttlSeconds&&(t=Math.min(r.ttlSeconds,t??1/0));const r=[...e.keys()].sort();return{key:JSON.stringify([this._sessionGeneration,r,t??null]),subscriptions:r.map(t=>e.get(t)),ttlSeconds:t}}notifyReady(e,t){if(this._subscribers.has(e)&&e.readyGeneration!==t.generation&&this.plan()?.key===t.key&&!this._phase?.interrupt.signal.aborted){e.readyGeneration=t.generation;try{e.onReady?.()}catch{this.report($t(Ct.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)xs(e,t.requested)&&t.queue.push(e)}release(e){const t=[...this._subscribers];this._subscribers.clear();for(const{queue:r}of t)e?r.fail(e):r.close()}report(e){e.meta&&"object"==typeof e.meta&&Object.freeze(e.meta),Object.freeze(e);try{this.emitError(e,"stream")}catch{}}collapse(){this._supervising=!1,this._phase?.interrupt.abort(),this._phase=void 0;const e=$t(Ct.NETWORK_ERROR,"hook stream supervisor stopped unexpectedly","hooks");this.report(e),this.release(e)}onSessionChange(e){super.onSessionChange(e),this._sessionGeneration+=1,this.wake()}onSignOut(){super.onSignOut(),this.release(),this.wake()}createHookHeaders(e,t){return this.context.invoke(this.session,"hooks",t,e)}createInvokeHeaders(e){const t=e.map(e=>({spaceId:e.space,service:"hooks",path:e.pathPrefix?`${e.service}/${e.pathPrefix}`:e.service,action:"tinycloud.hooks/subscribe"}));if(this.context.invokeAny)return this.context.invokeAny(this.session,t);if(1===t.length){const e=t[0];return this.context.invoke(this.session,e.service,e.path,e.action)}throw new Error("This SDK runtime does not support multi-scope hook invocations")}}).serviceName="hooks";var vs=Symbol("hooks attempt superseded");async function _s(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(ks,()=>{}),vs;const r="function"==typeof t?t():t;return new Promise((t,s)=>{let n=!1;const i=()=>e.removeEventListener("abort",a),a=()=>{n||(n=!0,i(),s(vs))};e.addEventListener("abort",a,{once:!0}),r.then(e=>{n?ks(e):(n=!0,i(),t(e))},e=>{n||(n=!0,i(),s(e))})})}function ks(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function Es(e){const t="number"==typeof e?e:void 0;return $t(Ct.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var bs=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function ws(e,t){const r=Os(t,"name"),s="string"==typeof r&&bs.has(r)?r:"Error",n=Ns(Os(t,"code"))??Ns(Os(Os(t,"cause"),"code"));return $t(Ct.NETWORK_ERROR,`hook stream ${e} failed: ${s}${n?` (${n})`:""}`,"hooks",{meta:{phase:e,errorName:s,...n?{errorCode:n}:{}}})}var Ts=new Set(["ECONNREFUSED","ECONNRESET","ECONNABORTED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EADDRNOTAVAIL","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CLOSED","UND_ERR_ABORTED","UND_ERR_RESPONSE_STATUS_CODE","ERR_TLS_CERT_ALTNAME_INVALID","CERT_HAS_EXPIRED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","ERR_SSL_WRONG_VERSION_NUMBER"]);function Ns(e){return"string"==typeof e&&Ts.has(e)?e:void 0}function Os(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var Rs=(e,t,r)=>((e,t,r=!1)=>new Promise(s=>{const n=()=>{clearTimeout(i),t.removeEventListener("abort",n),s()},i=setTimeout(n,e);r&&i.unref?.(),t.aborted?n():t.addEventListener("abort",n)}))(e,r,!0);function As(e){let t;const r=new Promise(e=>{t=e}),s=()=>t();return e.aborted?t():e.addEventListener("abort",s,{once:!0}),{promise:r,dispose:()=>e.removeEventListener("abort",s)}}function Is(e){return{...e,pathPrefix:"kv"===e.service?Ds(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function Ss(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function xs(e,t){return t.some(t=>function(e,t){if(e.space!==t.space)return!1;if(e.service!==t.service)return!1;if("sql"===e.service||"duckdb"===e.service){const r=t.pathPrefix,s=e.databasePath??e.path;if(r&&"/"!==r&&(!s||(r.endsWith("/")?!s.startsWith(r):s!==r)))return!1}else if(t.pathPrefix){const r=t.pathPrefix.endsWith("/")?t.pathPrefix:`${t.pathPrefix}/`;if(e.path&&e.path!==t.pathPrefix&&!e.path.startsWith(r))return!1}const r=t.abilities??[];return!(r.length>0&&!r.includes(e.ability))}(e,t))}function Ds(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function Ps(e,t,r){let s=r.statusText;try{const e=await r.text();e&&(s=e)}catch{}return $t(408===r.status||504===r.status?Ct.TIMEOUT:Ct.NETWORK_ERROR,`${t}: ${r.status} ${s}`,e,{meta:{status:r.status,statusText:r.statusText}})}function Cs(e){if(!e)return null;let t,r="message";const s=[];for(const n of e.split("\n")){if(!n||n.startsWith(":"))continue;const[e,...i]=n.split(":"),a=i.join(":").replace(/^ /,"");switch(e){case"event":r=a;break;case"id":t=a;break;case"data":s.push(a)}}return 0===s.length?null:{event:r,id:t,data:s.join("\n")}}function Us(e){const t=JSON.parse(e.data);return{type:"write",id:t.id??e.id??"",space:t.space??"",service:t.service??"",ability:t.ability??"",path:t.path,databasePath:"string"==typeof t.databasePath?t.databasePath:void 0,actor:t.actor??"",epoch:t.epoch??"",eventIndex:t.eventIndex??0,timestamp:t.timestamp??""}}function Ls(e){if(!e||"object"!=typeof e)return null;const t=e;return Ks(t)??Ls(t.webhook)??Ls(t.hook)??Ls(t.subscription)??Ls(t.data)??null}function $s(e){return Array.isArray(e)?e.map(e=>Ls(e)).filter(e=>null!==e):null}function Ks(e){const t=Vs(e,"id"),r=Vs(e,"space")??Vs(e,"spaceId"),s=Vs(e,"service"),n=Vs(e,"callbackUrl")??Vs(e,"callback_url");return t&&r&&s&&n?{id:t,space:r,service:s,pathPrefix:qs(e,"pathPrefix")??qs(e,"path_prefix"),abilities:Fs(e,"abilities")??js(e,"abilitiesJson")??js(e,"abilities_json"),callbackUrl:n,active:Ms(e,"active")??!0,createdAt:Vs(e,"createdAt")??Vs(e,"created_at")??(new Date).toISOString(),subscriberDid:qs(e,"subscriberDid")??qs(e,"subscriber_did")}:null}function Vs(e,t){const r=e[t];return"string"==typeof r?r:void 0}function qs(e,t){return Vs(e,t)}function Ms(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function Fs(e,t){const r=e[t];if(!Array.isArray(r))return;const s=r.filter(e=>"string"==typeof e);return s.length===r.length?s:void 0}function js(e,t){const r=e[t];if("string"==typeof r)try{const e=JSON.parse(r);if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e);return t.length===e.length?t:void 0}catch{return}}function Bs(e){return void 0===e?"":Hs(e)}function Hs(e){if(null===e)return"null";switch(typeof e){case"boolean":case"number":case"string":return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(Hs).join(",")}]`;const t=Object.keys(e).sort(),r=[];for(const s of t){const t=e[s];void 0!==t&&r.push(`${JSON.stringify(s)}:${Hs(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var Zs="0123456789abcdef";function Ws(e){let t="";for(let r=0;r<e.length;r++){const s=e[r];t+=Zs[s>>4&15]+Zs[15&s]}return t}function Gs(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<e.length;s+=3){const n=e[s],i=s+1<e.length?e[s+1]:0,a=s+2<e.length?e[s+2]:0;r+=t[n>>2&63],r+=t[63&(n<<4|i>>4)],r+=s+1<e.length?t[63&(i<<2|a>>6)]:"=",r+=s+2<e.length?t[63&a]:"="}return r}function zs(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),r=t.length;if(r%4!=0)throw new Error("invalid base64 input");const s=r/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),n=new Uint8Array(s),i={};for(let e=0;e<64;e++)i["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let a=0;for(let e=0;e<r;e+=4){const r=i[t[e]]??0,o=i[t[e+1]]??0,c="="===t[e+2]?0:i[t[e+2]]??0,u=r<<2|o>>4,d=(15&o)<<4|c>>2,l=(3&c)<<6|("="===t[e+3]?0:i[t[e+3]]??0);a<s&&(n[a++]=u),a<s&&(n[a++]=d),a<s&&(n[a++]=l)}return n}function Js(e){return(new TextEncoder).encode(e)}function Qs(e,t){return Ws(e(Js(Bs(t))))}var Ys={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},Xs="x-vault-version",en="x-vault-cipher",tn="x-vault-key-id",rn="x-vault-content-type",sn="x-vault-kdf",nn="x-vault-key-rotation",an="x-vault-grant-version",on="x-vault-grantor",cn="signatures",un="__wrap_key__";function dn(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function ln(){return new Promise((e,t)=>{const r=indexedDB.open("tinycloud-vault-cache",1);r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(cn)||e.createObjectStore(cn)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function hn(e,t){return new Promise((r,s)=>{const n=e.transaction(cn,"readonly").objectStore(cn).get(t);n.onsuccess=()=>r(n.result),n.onerror=()=>s(n.error)})}function pn(e,t,r){return new Promise((s,n)=>{const i=e.transaction(cn,"readwrite").objectStore(cn).put(r,t);i.onsuccess=()=>s(),i.onerror=()=>n(i.error)})}function yn(e,t){return new Promise((r,s)=>{const n=e.transaction(cn,"readwrite").objectStore(cn).delete(t);n.onsuccess=()=>r(),n.onerror=()=>s(n.error)})}async function fn(e){const t=await hn(e,un);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await pn(e,un,r),r}function mn(e){return`sig:${e}`}async function gn(e){if(!dn())return null;try{const t=await ln(),r=await hn(t,mn(e));if(!r)return null;const s=await fn(t);return await async function(e,t){const r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.iv},e,t.ciphertext);return new Uint8Array(r)}(s,r)}catch{return null}}async function vn(e,t){if(dn())try{const r=await ln(),s=await fn(r),n=await async function(e,t){const r=crypto.getRandomValues(new Uint8Array(12));return{iv:r,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t))}}(s,t);await pn(r,mn(e),n)}catch{}}async function _n(e){if(dn())try{const t=await ln();if(e)await yn(t,mn(e));else{const e=await function(e){return new Promise((t,r)=>{const s=e.transaction(cn,"readonly").objectStore(cn).getAllKeys();s.onsuccess=()=>t(s.result.filter(e=>"string"==typeof e)),s.onerror=()=>r(s.error)})}(t);for(const r of e)r.startsWith("sig:")&&await yn(t,r)}}catch{}}function kn(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function En(e){return(new TextEncoder).encode(e)}function bn(e){return(new TextDecoder).decode(e)}function wn(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function Tn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Nn(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function On(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function Rn(e){return"number"==typeof e.meta?.status}function An(e){switch(e.code){case"DECRYPTION_FAILED":return e.message??"Decryption failed";case"KEY_NOT_FOUND":return e.message??`Key not found: ${e.key}`;case"INTEGRITY_ERROR":return e.message??"Integrity check failed";case"GRANT_NOT_FOUND":return e.message??`Grant not found: ${e.grantor} / ${e.key}`;case"VAULT_LOCKED":return e.message??"Vault is locked";case"PUBLIC_KEY_NOT_FOUND":return e.message??`Public key not found for ${e.did}`;case"STORAGE_ERROR":return e.message??e.cause.message;case"ALREADY_EXISTS":return e.message??`A value already exists at ${e.key}`;case"AUTH_UNAUTHORIZED":case"PERMISSION_DENIED":case"AAD_MISMATCH":case"ETAG_MISMATCH":case"INVALID_ETAG":case"OUTCOME_UNKNOWN":case"NODE_BUSY":case"STORAGE_QUOTA_EXCEEDED":case"STORAGE_LIMIT_REACHED":return e.message;default:return e.message??e.code}}function In(e){return{ok:!1,error:{...e,service:"vault",message:An(e)}}}function Sn(e){return Object.assign(new Error(e.message),{name:"ServiceError",code:e.code,service:e.service,...void 0!==e.meta?{meta:e.meta}:{},...void 0!==e.cause?{cause:e.cause}:{}})}function xn(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function Dn(e,t,r){const s=e;if("object"!=typeof s||null===s||Array.isArray(s)||!["networkId","alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"].every(e=>"string"==typeof s[e]&&""!==s[e])||!Number.isInteger(s.keyVersion)||void 0!==s.aad&&"string"!=typeof s.aad)return"corrupt";let n="";try{"string"==typeof s.aad&&(n=bn(zs(s.aad)))}catch{}const i=`:${r}`;return n.endsWith(i)&&xn(n.slice(0,-i.length))===xn(`tinycloud.vault:${t}`)?"ok":"mismatch"}var Pn=[500,502,503,504,520,522,524];function Cn(e,t){const r=kr(t);if(r)return In(r);if(t.code===Ct.STORAGE_QUOTA_EXCEEDED||t.code===Ct.STORAGE_LIMIT_REACHED)return In({code:t.code,message:t.message,meta:t.meta});const s=`${e}: ${t.message}`;return t.code===Ct.AUTH_UNAUTHORIZED?In({code:"unauthenticated"===Cr(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:s,...void 0!==t.meta?{meta:t.meta}:{},cause:Sn(t)}):In({code:"STORAGE_ERROR",cause:new Error(s,{cause:Sn(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}(class extends Fr{constructor(e){super(),this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1,this.unlockInFlight=null,this.vaultConfig=e,this._config=e}get config(){return this._config}get isUnlocked(){return this.usesNetworkEncryption||this._isUnlocked}get publicKey(){if(this.usesNetworkEncryption)throw new Error("Network-encrypted vaults do not expose a local public key");if(!this.encryptionIdentity)throw new Error("Vault is locked");return this.encryptionIdentity.publicKey}get crypto(){return this.vaultConfig.crypto}get tc(){return this.vaultConfig.tc}get networkEncryption(){return this.vaultConfig.encryption}get usesNetworkEncryption(){return void 0!==this.networkEncryption}get host(){return this.tc.hosts[0]}async decryptCapabilityProof(){const e=this.networkEncryption?.decryptCapabilityProof;return"function"==typeof e?await e():e??{proofs:[]}}serializeValue(e,t){let r;return r=e instanceof Uint8Array?e:t?.serialize?t.serialize(e):En("string"==typeof e?e:JSON.stringify(e)),{plaintext:r,contentType:t?.contentType??(e instanceof Uint8Array?"application/octet-stream":"application/json")}}deserializeValue(e,t,r){return r?.raw?e:r?.deserialize?r.deserialize(e):"application/json"===t?JSON.parse(bn(e)):e}async unlock(e){if(this.usesNetworkEncryption)return this._isUnlocked=!0,{ok:!0,data:void 0};const t=function(e){return"object"==typeof e&&null!==e&&"function"==typeof e.signMessage}(e)?e:void 0;if(this._isUnlocked&&this.masterKey&&(this.encryptionIdentity||!t))return{ok:!0,data:void 0};if(this.unlockInFlight)return this.unlockInFlight;this.unlockInFlight=this.withTelemetry("unlock",void 0,async()=>{const e=this.vaultConfig.spaceId,r=Ys,s=`vault-master:${e}`,n=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let n=await gn(s);if(!n){if(!t)return In({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});n=En(await t.signMessage(r.masterMessage(e))),await vn(s,n)}this.masterKey=this.crypto.deriveKey(n,this.crypto.sha256(En(e)),En("vault-master"))}const i=this.tc.makePublicSpaceId(this.tc.address,this.tc.chainId);let a=null;try{const e=await this.tc.readPublicSpace(this.host,i,".well-known/vault-pubkey");e.ok&&e.data&&(a=e.data)}catch{}if(a)this.encryptionIdentity={publicKey:Nn(a),privateKey:new Uint8Array(0)};else{let e=await gn(n);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,Ut(void 0);e=En(await t.signMessage(r.identityMessage)),await vn(n,e)}const s=this.crypto.deriveKey(e,En("tinycloud-x25519"),En("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(s);try{const e=Tn(this.encryptionIdentity.publicKey);await this.tc.ensurePublicSpace(),await this.tc.publicKV.put(".well-known/vault-pubkey",e),await this.tc.publicKV.put(".well-known/vault-version","1"),await this.tc.publicKV.put(".well-known/vault-space",this.vaultConfig.spaceId)}catch{}}return this._isUnlocked=!0,Ut(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,In({code:"STORAGE_ERROR",cause:kn(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await _n(`vault-master:${e}`):await _n()}lock(){this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1}onSignOut(){this.lock(),super.onSignOut()}async putNetworkEncrypted(e,t,r){const s=this.networkEncryption;if(!s)return In({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return In({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return In({code:"INVALID_ETAG",key:e,message:r.ifMatch.startsWith("W/")?'ifMatch is a weak etag (W/"..."): the node only issues strong etags, so the etag was weakened in transit (a proxy or CDN rewrote it). Read it from a connection that preserves strong ETags':"ifMatch must be the strong, quoted ETag returned by a network read (VaultEntry.etag), passed exactly as returned"})}try{const{plaintext:n,contentType:i}=this.serializeValue(t,r),a={[Xs]:"2",[en]:"tinycloud-network-envelope",[rn]:i,...r?.metadata??{}},o=En(`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`),c=await s.service.encryptToNetwork(s.networkId,n,{aad:o,metadata:a});if(!c.ok){const e=kr(c.error);return In(e||{code:"STORAGE_ERROR",cause:new Error(c.error.message)})}const u=`vault/${e}`,d=JSON.stringify(c.data),l=void 0!==r?.ifMatch?{ifMatch:r.ifMatch}:void 0!==r?.ifNoneMatch?{ifNoneMatch:r.ifNoneMatch}:void 0,h=void 0!==l?await this.tc.kv.put(u,d,l):await this.tc.kv.put(u,d);if(!h.ok){if(void 0!==r?.ifNoneMatch&&h.error.code===Ct.KV_PRECONDITION_FAILED)return In({code:"ALREADY_EXISTS",key:e,...void 0!==h.error.meta?{meta:h.error.meta}:{},cause:Sn(h.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,s=t.code===Ct.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===Ct.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===Ct.OUTCOME_UNKNOWN||t.code===Ct.KV_WRITE_FAILED&&"number"==typeof r&&Pn.includes(r)||(t.code===Ct.NETWORK_ERROR||t.code===Ct.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===Ct.NODE_BUSY||t.code===Ct.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==s)return In({code:s,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:Sn(t)})}(e,h.error);if(void 0!==t)return t}return Cn("Failed to store encrypted value",h.error)}return{ok:!0,data:void 0}}catch(e){const t=kr(e);return In(t||{code:"STORAGE_ERROR",cause:kn(e)})}}async getNetworkEncrypted(e,t){const r=this.networkEncryption;if(!r)return In({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!s.ok){const t=kr(s.error);return In(t||{code:"KEY_NOT_FOUND",key:e})}const n=On(s.data),i="string"==typeof n?JSON.parse(n):n;if(!0===t?.expectAad){const t=Dn(i,this.vaultConfig.spaceId,e);if("corrupt"===t)return In({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===t)return In({code:"AAD_MISMATCH",key:e,message:`Envelope at ${e} is not bound to this space and key`})}const a=await this.decryptCapabilityProof(),o=await r.service.decryptEnvelope(i,a);if(!o.ok){const e=kr(o.error);return In(e||{code:"DECRYPTION_FAILED",message:o.error.message})}const c=i.metadata??{},u=c[rn]??"application/json",d=c[tn]??i.encryptedSymmetricKeyHash.slice(0,16),l=this.deserializeValue(o.data,u,t),h="network"===t?.source?s.data.headers?.etag:void 0;return{ok:!0,data:{value:l,metadata:c,keyId:d,...void 0===h?{}:{etag:h}}}}catch(e){const t=kr(e);return In(t||{code:"STORAGE_ERROR",cause:kn(e)})}}async readNetworkEncrypted(e,t){const r=this.networkEncryption;if(!r||!this.requireAuth())return{status:"read_failed"};let s,n,i;try{s=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"})}catch(e){if(kr(e))throw e;return{status:"node_unreachable"}}if(!s.ok){if(kr(s.error))throw s.error;const e=Er(s.error.meta?.permissionHint);return"AUTH_UNAUTHORIZED"===s.error.code&&void 0!==e?{status:"permission_required",hint:e}:"NOT_FOUND"!==s.error.code&&"KV_NOT_FOUND"!==s.error.code||Rn(s.error)?"NODE_NOT_RESPONDING"===s.error.code||"NETWORK_ERROR"===s.error.code||"TIMEOUT"===s.error.code||"ABORTED"===s.error.code?Rn(s.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=On(s.data);n="string"==typeof e?JSON.parse(e):e}catch{return{status:"corrupt_envelope"}}if(!0===t?.expectAad){const t=Dn(n,this.vaultConfig.spaceId,e);if("ok"!==t)return{status:"corrupt"===t?"corrupt_envelope":"aad_mismatch"}}try{const e=await this.decryptCapabilityProof();i=await r.service.decryptEnvelope(n,e)}catch(e){if(kr(e))throw e;return{status:"decrypt_failed"}}if(!i.ok){if(kr(i.error))throw i.error;const e=Er(i.error.permissionHint);return"DECRYPT_DENIED"===i.error.code&&void 0!==e?{status:"permission_required",hint:e}:"INVALID_ENVELOPE"===i.error.code?{status:"corrupt_envelope"}:"NODE_NOT_RESPONDING"===i.error.code||"TRANSPORT_ERROR"===i.error.code?{status:"node_unreachable"}:{status:"decrypt_failed"}}try{const e=n.metadata??{},r=e[rn]??"application/json",a=e[tn]??n.encryptedSymmetricKeyHash.slice(0,16),o=this.deserializeValue(i.data,r,t),c=s.data.headers?.etag;return{status:"ok",entry:{value:o,metadata:e,keyId:a,...void 0===c?{}:{etag:c}}}}catch{return{status:"invalid_payload"}}}async headNetworkEncrypted(e){if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return In({code:"KEY_NOT_FOUND",key:e});const r=On(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(this.usesNetworkEncryption)return this.putNetworkEncrypted(e,t,r);if(void 0!==r?.ifNoneMatch)return In({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return In({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{let s;s=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):En("string"==typeof t?t:JSON.stringify(t));const n=r?.contentType??(t instanceof Uint8Array?"application/octet-stream":"application/json"),i=this.crypto.randomBytes(32),a=wn(this.crypto.sha256(i)).slice(0,16),o=this.crypto.encrypt(i,s),c=this.crypto.encrypt(this.masterKey,i),u={[Xs]:"1",[en]:"aes-256-gcm",[tn]:a,[rn]:n,[sn]:"hkdf-sha256",[nn]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},d=JSON.stringify({keyId:a,contentType:n,...u}),l=JSON.stringify({key:Tn(c),metadata:d}),h=await this.tc.kv.put(`keys/${e}`,l);if(!h.ok)return Cn("Failed to store key blob",h.error);const p=JSON.stringify({data:Tn(o),metadata:u}),y=await this.tc.kv.put(`vault/${e}`,p);return y.ok?Ut(void 0):Cn("Failed to store encrypted value",y.error)}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return In({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.tc.kv.get(`keys/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!r.ok)return In({code:"KEY_NOT_FOUND",key:e});const s=Nn(JSON.parse(r.data.data).key),n=this.crypto.decrypt(this.masterKey,s),i=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!i.ok)return In({code:"KEY_NOT_FOUND",key:e});const a=JSON.parse(i.data.data),o=Nn(a.data),c=this.crypto.decrypt(n,o),u=a.metadata??{},d=u[rn]??"application/json",l=u[tn]??"";let h;return h=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===d?JSON.parse(bn(c)):c,Ut({value:h,metadata:u,keyId:l})}catch(e){return e instanceof Error&&e.message.includes("decryption")?In({code:"DECRYPTION_FAILED",message:e.message}):In({code:"STORAGE_ERROR",cause:kn(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=kr(t.error);return In(r||{code:"KEY_NOT_FOUND",key:e})}return Ut(void 0)}const[t,r]=await Promise.all([this.tc.kv.delete(`keys/${e}`),this.tc.kv.delete(`vault/${e}`)]);if(!t.ok&&!r.ok){const s=kr(t.error)??kr(r.error);return In(s||{code:"KEY_NOT_FOUND",key:e})}return Ut(void 0)}catch(e){const t=kr(e);return In(t||{code:"STORAGE_ERROR",cause:kn(e)})}})}async list(e){const t=await this.listPage(e);return t.ok?{ok:!0,data:t.data.keys}:t}async listPage(e){return this.withTelemetry("list",e?.prefix,async()=>{if(!this.isUnlocked)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=e?.prefix?`vault/${e.prefix}`:"vault/",r=await this.tc.kv.list({prefix:t,removePrefix:!0,...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.source?{}:{source:e.source},...void 0===e?.cursor?{}:{cursor:e.cursor}});if(!r.ok){const e=kr(r.error);return In(e||{code:"STORAGE_ERROR",cause:new Error(`Failed to list vault keys: ${r.error.message}`)})}let s=r.data.keys;if(e?.removePrefix&&e.prefix){const t=e.prefix.endsWith("/")?e.prefix:`${e.prefix}/`;s=s.map(e=>e.startsWith(t)?e.slice(t.length):e)}return Ut({keys:s,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=kr(e);return In(t||{code:"STORAGE_ERROR",cause:kn(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return In({code:"KEY_NOT_FOUND",key:e});return Ut(JSON.parse(t.data.data).metadata??{})}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}})}async putMany(e){return Promise.all(e.map(e=>this.put(e.key,e.value,e.options)))}async getMany(e,t){return Promise.all(e.map(e=>this.get(e,t)))}async reencrypt(e,t,r){return this.withTelemetry("reencrypt",e,async()=>{if(this.usesNetworkEncryption)return In({code:"STORAGE_ERROR",cause:new Error("Vault key grants are deprecated for network-encrypted vaults; grant tinycloud.encryption/decrypt on the network plus KV access to vault data.")});if(!this._isUnlocked||!this.masterKey)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await this.resolvePublicKey(t);if(!s.ok)return s;const n=s.data,i=await this.tc.kv.get(`keys/${e}`,{raw:!0});if(!i.ok)return In({code:"KEY_NOT_FOUND",key:e});const a=Nn(JSON.parse(i.data.data).key),o=this.crypto.decrypt(this.masterKey,a),c=this.crypto.randomBytes(32),u=this.crypto.x25519FromSeed(c),d=this.crypto.x25519Dh(u.privateKey,n),l=this.crypto.deriveKey(d,En("tinycloud-x25519"),En("vault-grant")),h=this.crypto.encrypt(l,o),p=function(...e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}(u.publicKey,h),y=JSON.stringify({grant:Tn(p),spaceId:this.vaultConfig.spaceId,metadata:{[an]:"1",[on]:this.tc.did,...r?.metadata??{}}}),f=await this.tc.kv.put(`grants/${t}/${e}`,y);return f.ok?Ut(void 0):Cn("Failed to store grant",f.error)}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}})}async grant(e,t,r){return this.reencrypt(e,t,r)}async getShared(e,t,r){return this.withTelemetry("getShared",t,async()=>{if(!0===r?.expectAad)return In({code:"STORAGE_ERROR",cause:new Error("expectAad is not supported by getShared: the AAD binds the grantor's space, which this vault does not know")});if(this.usesNetworkEncryption){const e=r?.kv;if(!e)return In({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const s=this.networkEncryption;if(!s)return In({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=await e.get(`vault/${t}`,{raw:!0});if(!n.ok)return In({code:"KEY_NOT_FOUND",key:t});const i=On(n.data),a="string"==typeof i?JSON.parse(i):i,o=await this.decryptCapabilityProof(),c=await s.service.decryptEnvelope(a,o);if(!c.ok)return In({code:"DECRYPTION_FAILED",message:c.error.message});const u=a.metadata??{},d=u[rn]??"application/json",l=u[tn]??a.encryptedSymmetricKeyHash.slice(0,16);return{ok:!0,data:{value:this.deserializeValue(c.data,d,r),metadata:u,keyId:l}}}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=this.tc.did,n=r?.kv;if(!n)return In({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv. Use useDelegation() to get delegated access, then pass { kv: access.kv }.")});const i=await n.get(`grants/${s}/${t}`,{raw:!0});if(!i.ok)return In({code:"GRANT_NOT_FOUND",grantor:e,key:t});const a=Nn(("string"==typeof i.data?.data?JSON.parse(i.data.data):i.data?.data).grant),o=a.slice(0,32),c=a.slice(32),u=this.crypto.x25519Dh(this.encryptionIdentity.privateKey,o),d=this.crypto.deriveKey(u,En("tinycloud-x25519"),En("vault-grant")),l=this.crypto.decrypt(d,c),h=await n.get(`vault/${t}`,{raw:!0});if(!h.ok)return In({code:"KEY_NOT_FOUND",key:t});const p="string"==typeof h.data?.data?JSON.parse(h.data.data):h.data?.data,y=Nn(p.data),f=this.crypto.decrypt(l,y),m=p.metadata??{},g=m[rn]??"application/json",v=m[tn]??"";let _;return _=r?.raw?f:r?.deserialize?r.deserialize(f):"application/json"===g?JSON.parse(bn(f)):f,Ut({value:_,metadata:m,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?In({code:"DECRYPTION_FAILED",message:e.message}):In({code:"STORAGE_ERROR",cause:kn(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return In({code:"PUBLIC_KEY_NOT_FOUND",did:e});const r=this.tc.makePublicSpaceId(t.address,t.chainId),s=await this.tc.readPublicSpace(this.host,r,".well-known/vault-pubkey");return s.ok?{ok:!0,data:Nn(s.data)}:In({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return In({code:"PUBLIC_KEY_NOT_FOUND",did:e})}}async listGrants(e){return this.withTelemetry("listGrants",e,async()=>{if(this.usesNetworkEncryption)return{ok:!0,data:[]};if(!this._isUnlocked)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return In({code:"STORAGE_ERROR",cause:new Error(`Failed to list grants: ${t.error.message}`)});const r=[];for(const s of t.data.keys)if(s.endsWith(`/${e}`)){const t=s.slice(0,s.length-e.length-1);t&&r.push(t)}return Ut(r)}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return In({code:"STORAGE_ERROR",cause:new Error("Vault key grants are deprecated for network-encrypted vaults; revoke KV and tinycloud.encryption/decrypt grants instead.")});if(!this._isUnlocked||!this.masterKey)return In({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return In({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.listGrants(e);if(!r.ok)return r;const s=r.data.filter(e=>e!==t),n=(await this.tc.kv.delete(`grants/${t}/${e}`),await this.get(e));if(!n.ok)return n;const i=n.data,a=this.crypto.randomBytes(32),o=wn(this.crypto.sha256(a)).slice(0,16);let c;c=i.value instanceof Uint8Array?i.value:En(JSON.stringify(i.value));const u=this.crypto.encrypt(a,c),d=this.crypto.encrypt(this.masterKey,a),l={...i.metadata,[tn]:o},h=JSON.stringify({key:Tn(d),metadata:JSON.stringify({keyId:o,...l})}),p=await this.tc.kv.put(`keys/${e}`,h);if(!p.ok)return Cn("Failed to store rotated key blob",p.error);const y=JSON.stringify({data:Tn(u),metadata:l}),f=await this.tc.kv.put(`vault/${e}`,y);if(!f.ok)return Cn("Failed to store re-encrypted value",f.error);for(const t of s)(await this.reencrypt(e,t)).ok;return Ut(void 0)}catch(e){return In({code:"STORAGE_ERROR",cause:kn(e)})}})}parseDID(e){const t=e.split(":");if(5!==t.length||"did"!==t[0]||"pkh"!==t[1]||"eip155"!==t[2])return null;const r=parseInt(t[3],10),s=t[4];return isNaN(r)||!s?null:{address:s,chainId:r}}}).serviceName="vault",Object.freeze(["default","global","scoped"]);var Un="tinycloud.encryption.decrypt/v1",Ln="tinycloud.encryption.decrypt-result/v1";function $n(e){switch(e.code){case"NETWORK_NOT_FOUND":return e.message??`Network not found: ${e.networkId??e.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return e.message??`Network not active (state=${e.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return e.message;case"RESPONSE_SIGNATURE_INVALID":return e.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return e.message??`Node response binding mismatch on field ${JSON.stringify(e.field)}`;case"TRANSPORT_ERROR":return e.message??e.cause.message;default:return e.message??e.code}}function Kn(e){return{...e,service:"encryption",message:$n(e)}}function Vn(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function qn(e,t,r,s){let n;try{n=fr(e.networkId)}catch(e){return{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(n.name!==s||!vr(n.ownerDid,r))return{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:`descriptor networkId ${JSON.stringify(e.networkId)} does not match expected ${JSON.stringify(t)}`})};const i=function(e){if("string"==typeof e.ownerDid&&e.ownerDid.length>0)return e.ownerDid;const t=e;return"string"==typeof t.principal&&t.principal.length>0?t.principal:void 0}(e);return void 0!==i&&vr(i,r)&&vr(i,n.ownerDid)?e.name!==s?{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:i}}:{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function Mn(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:Kn({code:"NETWORK_NOT_ACTIVE",state:e.state})}}function Fn(e){return{ok:!0,data:e}}function jn(e){return{ok:!1,error:e}}function Bn(e){return Kn("NODE_NOT_RESPONDING"===e.code||"TRANSPORT_ERROR"===e.code&&"AbortError"!==e.cause.name?{...e,code:"DECRYPTION_DEPENDENCY_UNAVAILABLE",message:"The decryption service isn't responding right now. Please try again."}:e)}(class extends Fr{constructor(e){super(),this._config=e}get config(){return this._config}get crypto(){return this._config.crypto}async discoverNetwork(e,t){this.assertActive();const r=await async function(e){let t,r,s;try{if(e.identifier.startsWith("urn:tinycloud:encryption:")){const n=fr(e.identifier);t=n.networkId,r=n.ownerDid,s=n.name}else{if(void 0===e.ownerDid)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"discoverNetwork requires `ownerDid` when identifier is a bare network name"})};t=`urn:tinycloud:encryption:${e.ownerDid}:${e.identifier}`;const n=fr(t);r=n.ownerDid,s=n.name}}catch(e){if(e instanceof yr)return{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:e.message})};throw e}if(void 0!==e.node)try{const n=await e.node.fetchByNetworkId(t);if(null!==n){const e=qn(n,t,r,s);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=kr(e);if(t)return{ok:!1,error:Kn(t)}}if(void 0!==e.wellKnown)try{const n=await e.wellKnown.fetchWellKnown(r,function(e){if(!hr.test(e))throw new yr(`network name ${JSON.stringify(e)} must match ${hr.source}`);return`.well-known/encryption/network/${e}`}(s));if(null!==n){const e=qn(n,t,r,s);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=kr(e);if(t)return{ok:!1,error:Kn(t)}}return{ok:!1,error:Kn({code:"NETWORK_NOT_FOUND",networkId:t,name:s})}}({identifier:e,...void 0!==t?{ownerDid:t}:{},...void 0!==this._config.node?{node:this._config.node}:{},...void 0!==this._config.wellKnown?{wellKnown:this._config.wellKnown}:{}});return this.assertActive(),r.ok?Fn(r.data.descriptor):r}async encryptToNetwork(e,t,r){try{this.assertActive();const s=await this.discoverNetwork(e);if(!s.ok)return s;const n=Mn(s.data);if(!n.ok)return n;const i=n.data,a=zs(i.publicEncryptionKey);return Fn(function(e,t){if(mr(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new yr("keyPath must name an exact encryption key");const r=t.alg??"x25519-aes256gcm/v1",s=t.keyVersion??1,n=e.randomBytes(32),i=e.authEncrypt(n,t.plaintext,t.aad),a=Gs(e.sealToNetworkKey(t.networkPublicKey,n)),o=Qs(e.sha256,a);return{envelope:{v:1,networkId:t.networkId,...void 0!==t.keyPath?{keyPath:t.keyPath}:{},alg:r,keyVersion:s,encryptedSymmetricKey:a,encryptedSymmetricKeyHash:o,ciphertext:Gs(i),...void 0!==t.aad?{aad:Gs(t.aad)}:{},...void 0!==t.metadata?{metadata:t.metadata}:{}},symmetricKey:n}}(this.crypto,{networkId:i.networkId,...void 0!==r?.keyPath?{keyPath:r.keyPath}:{},networkPublicKey:a,plaintext:t,...void 0!==r?.aad?{aad:r.aad}:{},alg:r?.alg??i.alg,keyVersion:r?.keyVersion??i.keyVersion,...void 0!==r?.metadata?{metadata:r.metadata}:{}}).envelope)}catch(e){const t=kr(e);return jn(Kn(t||{code:"TRANSPORT_ERROR",cause:Vn(e)}))}}async decryptEnvelope(e,t,r){try{this.assertActive();const n=function(e,t){if(null===t||"object"!=typeof t)return{ok:!1,error:Kn({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const r=t;if(1!==r.v)return{ok:!1,error:Kn({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${r.v})`})};try{if(void 0!==mr(r.networkId).keyPath)throw new Error("networkId must identify the network root");if(void 0!==r.keyPath){if("string"!=typeof r.keyPath)throw new Error("keyPath must be a string");if(mr(`${r.networkId}/${r.keyPath}`).keyPath!==r.keyPath||r.keyPath.endsWith("/"))throw new Error("keyPath must name an exact encryption key")}}catch(e){return{ok:!1,error:Kn({code:"INVALID_ENVELOPE",message:`envelope encryption resource is malformed: ${e instanceof Error?e.message:String(e)}`})}}for(const e of["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"])if("string"!=typeof r[e]||0===r[e].length)return{ok:!1,error:Kn({code:"INVALID_ENVELOPE",message:`envelope.${e} must be a non-empty string`})};return"number"==typeof r.keyVersion&&Number.isInteger(r.keyVersion)?Qs(e.sha256,r.encryptedSymmetricKey)!==r.encryptedSymmetricKeyHash?{ok:!1,error:Kn({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})}:{ok:!0,data:r}:{ok:!1,error:Kn({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})}}(this.crypto,e);if(!n.ok)return n;if(void 0!==r?.aad&&n.data.aad!==Gs(r.aad))return jn(Kn({code:"INVALID_INPUT",message:"decryptEnvelope aad does not match the envelope"}));let i;if(void 0!==r?.descriptor)i=r.descriptor;else{const t=await this.discoverNetwork(e.networkId);if(!t.ok)return jn(Bn(t.error));i=t.data}const a=Mn(i);if(!a.ok)return a;const o=this._config.resolveTargetNode?await this._config.resolveTargetNode(e.networkId):r?.targetNode??i.members[0]?.nodeId;if(void 0===o)return jn(Kn({code:"INVALID_INPUT",message:"no target node available from descriptor"}));if(this._config.resolveTargetNode&&(void 0!==r?.targetNode&&r.targetNode!==o||!i.members.some(e=>e.nodeId===o)))return jn(Kn({code:"INVALID_INPUT",message:"Encryption destination does not match the registry"}));const c=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:this.crypto}),u=Gs(c.publicKey),d=Qs(this.crypto.sha256,u),l={type:Un,targetNode:o,networkId:e.networkId,...void 0!==e.keyPath?{keyPath:e.keyPath}:{},alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:u,receiverPublicKeyHash:d},h={canonicalBody:Bs((s={crypto:this.crypto,body:l,receiverPublicKey:c.publicKey}).body),bodyHash:Qs(s.crypto.sha256,s.body),receiverPublicKeyHash:Qs(s.crypto.sha256,s.body.receiverPublicKey)},p=function(e){const t=void 0!==e.canonicalBody?Ws(e.crypto.sha256(Js(e.canonicalBody))):Qs(e.crypto.sha256,e.body),r=Qs(e.crypto.sha256,e.body.receiverPublicKey);return{type:Un,targetNode:e.body.targetNode,networkId:e.body.networkId,...void 0!==e.body.keyPath?{keyPath:e.body.keyPath}:{},bodyHash:t,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:r,alg:e.body.alg,keyVersion:e.body.keyVersion}}({crypto:this.crypto,body:l,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:c.publicKey,canonicalBody:h.canonicalBody}),y=await async function(e,t,r){const s=function(e,t){if(t.body.type!==Un)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:`body.type must be ${Un}`})};if(t.facts.type!==Un)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:`facts.type must be ${Un}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.targetNode must equal targetNode — the UCAN audience binds the request to a single node"})};if(t.body.targetNode!==t.targetNode)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==mr(t.networkId).keyPath)throw new yr("networkId must identify the network root")}catch(e){return{ok:!1,error:Kn({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if(mr(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new yr("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:Kn({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=Bs(t.body);return Qs(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:Kn({code:"INVALID_INPUT",message:"facts.bodyHash does not match the canonical body hash"})}:{ok:!0,data:t,canonicalBody:r}}(e,r);if(!s.ok)return s;try{const e=await t.signDecryptInvocation(s.data);return e.authorization&&e.invocationCid?e.canonicalBody!==s.canonicalBody?{ok:!1,error:Kn({code:"INVALID_INPUT",message:"decrypt-invocation signer returned a canonicalBody that does not match the SDK's canonicalization — signer must use the SDK-provided body"})}:{ok:!0,data:e}:{ok:!1,error:Kn({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:Kn({code:"TRANSPORT_ERROR",cause:e instanceof Error?e:new Error(String(e)),message:`failed to sign decrypt invocation: ${e instanceof Error?e.message:String(e)}`})}}}(this.crypto,this._config.signer,{targetNode:o,networkId:e.networkId,body:l,facts:p,proof:t});if(this.assertActive(),!y.ok)return"TRANSPORT_ERROR"!==y.error.code?y:jn(Kn({code:"INVALID_INPUT",message:"Unable to build decrypt request"}));let f;try{f=await this._config.transport.postDecrypt({targetNode:o,networkId:e.networkId,authorization:y.data.authorization,canonicalBody:y.data.canonicalBody,signal:this.abortSignal}),this.assertActive()}catch(t){const r=kr(t);return r?jn(Bn(r)):t instanceof Pt.DecryptTransportResponseError?jn(Kn(404===t.status?{code:"NETWORK_NOT_FOUND",networkId:e.networkId,message:t.notFoundMessage}:401===t.status||403===t.status?{code:"DECRYPT_DENIED",message:"Node denied decrypt request",...void 0===t.permissionHint?{}:{permissionHint:t.permissionHint}}:{code:"INVALID_RESPONSE",message:"Node decrypt request failed"})):jn(Bn({code:"TRANSPORT_ERROR",cause:Vn(t)}))}const m=function(e){const{crypto:t,request:r,facts:s,invocationCid:n,requestBodyHash:i,response:a}=e;if(a.type!==Ln)return{ok:!1,error:Kn({code:"INVALID_RESPONSE",message:`response.type must be ${Ln}`})};if(a.targetNode!==r.targetNode)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(a.networkId!==r.networkId)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(a.nodeId!==r.targetNode)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(a.alg!==r.alg)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(a.keyVersion!==r.keyVersion)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(a.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(a.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(a.invocationCid!==n)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const o=Ws(t.sha256(Js(`${n}${i}`)));if(a.requestHash!==o)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(s.encryptedSymmetricKeyHash!==a.encryptedSymmetricKeyHash||s.receiverPublicKeyHash!==a.receiverPublicKeyHash||s.networkId!==a.networkId||s.targetNode!==a.targetNode||s.alg!==a.alg||s.keyVersion!==a.keyVersion)return{ok:!1,error:Kn({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return Bs(r)}(a)),u=zs(a.nodeSignature);return t.verifyNodeSignature(a.nodeId,c,u)?{ok:!0,data:a}:{ok:!1,error:Kn({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:this.crypto,request:l,facts:p,invocationCid:y.data.invocationCid,requestBodyHash:p.bodyHash,response:f});if(!m.ok)return m;const g=function(e,t,r){const s=zs(r.wrappedKey);return e.openWithReceiverKey(t,s)}(this.crypto,c.privateKey,m.data),v=function(e,t,r){const s=zs(t.ciphertext),n=void 0!==t.aad?zs(t.aad):void 0;return e.authDecrypt(r,s,n)}(this.crypto,e,g);return Fn(v)}catch(e){const t=kr(e);return jn(t?Bn(t):Kn({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var s}assertActive(){this._config.assertActive?.()}}).serviceName="encryption";var Hn=Fe({kty:$e(),crv:$e().optional(),x:$e().optional(),y:$e().optional(),d:$e().optional(),e:$e().optional(),n:$e().optional(),kid:$e().optional(),alg:$e().optional(),use:$e().optional(),key_ops:Me($e()).optional()}),Zn=Ze(["main","session","ingested"]),Wn=Fe({id:$e(),did:$e(),type:Zn,jwk:Hn.optional(),priority:Ke()}),Gn=(Fe({code:$e(),message:$e(),service:He("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Ue(t=>t instanceof e,t))(Error).optional(),meta:Be($e(),qe()).optional()}),"NOT_INITIALIZED"),zn="NETWORK_ERROR",Jn="INVALID_INPUT",Qn="INVALID_TOKEN",Yn=Fe({cid:$e(),delegateDID:$e(),spaceId:$e(),path:$e(),actions:Me($e()),caveats:Me(Be($e(),qe())).optional(),expiry:We(),isRevoked:Ve(),delegatorDID:$e().optional(),createdAt:We().optional(),parentCid:$e().optional(),allowSubDelegation:Ve().optional(),authHeader:$e().optional()}),Xn=(Fe({cid:$e().min(1),status:Ze(["active","revoked","expired","unavailable","not_found"]),exists:Ve(),active:Ve(),revoked:Ve(),expired:Ve()}).strict().superRefine((e,t)=>{("active"===e.status?e.exists&&e.active&&!e.revoked&&!e.expired:"revoked"===e.status?e.exists&&!e.active&&e.revoked&&!e.expired:"expired"===e.status?e.exists&&!e.active&&!e.revoked&&e.expired:"unavailable"===e.status?e.exists&&!e.active&&!e.revoked&&!e.expired:!(e.exists||e.active||e.revoked||e.expired))||t.addIssue({code:o.custom,message:"delegation status flags do not match status"})}),Fe({revoked:He(!0),cid:$e().min(1)}).strict()),ei=Fe({resource:$e().min(1),actions:Me($e()),caveats:Me(Be($e(),qe()))}).strict(),ti=$e().datetime({offset:!0}).transform(e=>new Date(e)),ri=Fe({cid:$e().min(1),direction:Ze(["granted","received"]),delegatorDid:$e().min(1),delegateDid:$e().min(1),resources:Me(ei),parents:Me($e()),issuedAt:ti.nullable(),notBefore:ti.nullable(),expiresAt:ti.nullable(),status:Ze(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:ti.nullable().optional(),revokedBy:$e().optional(),revokedAncestorCid:$e().optional()}).strict(),si=Fe({schemaVersion:He(2),items:Me(ri),nextCursor:$e().optional()}).strict(),ni=(Fe({direction:Ze(["granted","received","all","issued"]).optional(),status:Ze(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:$e().trim().min(1).optional(),limit:Ke().int().min(1).max(100).optional(),cursor:$e().min(1).optional()}).strict(),Fe({resource:$e(),action:$e(),keys:Me(Wn),delegation:Yn,expiresAt:We().optional()}),Fe({cid:$e(),spaceId:$e(),delegator:$e(),delegatee:$e(),keyId:$e().optional(),path:$e(),actions:Me($e()),expiry:We().optional(),notBefore:We().optional(),isRevoked:Ve(),createdAt:We(),parentCid:$e().optional()}),Fe({delegateDID:$e(),path:$e(),actions:Me($e()),expiry:We().optional(),disableSubDelegation:Ve().optional(),statement:$e().optional()}),Me(Yn),Fe({root:Yn,chain:Me(Yn),leaf:Yn}),Ze(["granted","received","all"])),ii=(Fe({direction:ni.optional(),path:$e().optional(),actions:Me($e()).optional(),includeRevoked:Ve().optional(),delegator:$e().optional(),delegatee:$e().optional(),validAt:We().optional(),limit:Ke().optional(),cursor:$e().optional()}),Ze(["owned","delegated"])),ai=(Fe({id:$e(),name:$e().optional(),owner:$e(),type:ii,permissions:Me($e()).optional(),expiresAt:We().optional()}),Ze(["base64","compact","ipfs"]));Fe({token:$e(),url:$e(),delegation:Yn,schema:ai,expiresAt:We().optional(),description:$e().optional()}),function(e){Fe({data:e,delegation:Yn,spaceId:$e(),path:$e()})}(qe()),Fe({persist:Ve().optional(),validateChain:Ve().optional(),keyName:$e().optional(),createSessionKey:Ve().optional(),priority:Ke().optional()}),Fe({path:$e(),actions:Me($e()).optional(),expiry:We().optional(),schema:ai.optional(),description:$e().optional(),baseUrl:$e().optional(),allowSubDelegation:Ve().optional()}),Fe({hosts:Me($e()),accountSpaceId:$e().min(1).optional(),session:qe().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:qe().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:qe().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:Ue().optional(),sessionInvocationSigner:Ue().optional(),resourceTransport:Ue().optional(),fetch:qe().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Fe({createSessionKey:qe().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:qe().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:qe().refine(e=>"function"==typeof e,{message:"Expected a function"})}),Fe({siwe:$e(),signature:$e(),version:Ke(),cid:$e().optional()});var oi=Fe({service:$e(),space:$e(),path:$e(),actions:Me($e()),caveats:Me(Be($e(),qe())).optional()}),ci=(Fe({session:qe().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:$e(),spaceId:$e(),abilities:Be($e(),Be($e(),Me($e()))),expirationSecs:Ke(),notBeforeSecs:Ke().optional(),disableSubDelegation:Ve().optional()}),Fe({delegation:$e(),cid:$e(),delegateDID:$e(),expiry:We(),resources:Me(oi)}),"tinycloud.delegation/revoke"),ui="tinycloud.delegation/list";function di(e,t,r,s){return{code:e,message:t,service:"delegation",cause:r,meta:s}}var li="delegation-issued-query-v1";async function hi(e,t,r){const s=await async function(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}(e),n={...r,status:e.status};return 401===e.status||403===e.status?di("PERMISSION_DENIED",""===s?"The node refused the request":s,void 0,n):400===e.status&&s.includes("invalid delegation query cursor")?di("INVALID_CURSOR","The node rejected the page cursor; list again from the start",void 0,n):503===e.status?di("CHAIN_TOO_DEEP","This delegation chain is too long for the node to check right now; try again later",void 0,{...n,retryable:!0}):di(zn,`${t}: ${e.status} - ${s}`,void 0,n)}var pi=class extends Error{};function yi(){return{ok:!1,error:di("UNSUPPORTED_OPERATION","This node doesn't support listing issued delegations yet",void 0,{feature:li})}}async function fi(e,t){const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:di(Gn,"Listing issued delegations needs a session key signer")};try{const s=async(e,s,n)=>e(`${s}/delegation/query`,{method:"POST",headers:{Authorization:await r.sign({[`${r.did()}/delegation`]:{[ui]:[{}]}},n),"content-type":"application/json"},body:JSON.stringify(t),redirect:"error"});let n;if(e.resourceTransport)n=await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>{const t=e.nodeInfo.features;if(!Array.isArray(t)||!t.includes(li))throw new pi;return s(e.fetch,e.url,e.nodeDid)},{nodeLocal:!0});else{const t=await async function(e){if(e.state.issuedQuerySupported)return{ok:!0,data:!0};const t=await e.fetchFn(`${e.host}/info`,{redirect:"error"});if(!t.ok)return{ok:!1,error:di(zn,`Couldn't read the node's info: ${t.status}`,void 0,{status:t.status})};const r=await t.json();return e.state.issuedQuerySupported=Array.isArray(r.features)&&r.features.includes(li),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!t.ok)return t;if(!t.data)return yi();n=await s(e.fetchFn,e.host)}if(!n.ok)return{ok:!1,error:await hi(n,"Failed to query issued delegations",{})};const i=si.safeParse(await n.json());return i.success?{ok:!0,data:i.data}:{ok:!1,error:di(Qn,"Node returned an invalid delegation query response")}}catch(e){return kr(e)?{ok:!1,error:{...Mr("delegation",e),service:"delegation"}}:e instanceof pi?yi():{ok:!1,error:di(zn,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function mi(e,t){const{pageSize:r=100,maxItems:s,untilCid:n,...i}=t;if(void 0!==s&&(!Number.isInteger(s)||s<1))return{ok:!1,error:di(Jn,"maxItems must be a positive integer")};const a=[],o=new Set;let c;do{const t=Math.min(r,void 0===s?r:s-a.length),n=await e({...i,direction:"issued",limit:t,...void 0===c?{}:{cursor:c}});if(!n.ok)return n;if(a.push(...n.data.items),c=n.data.nextCursor,void 0!==c){if(o.has(c))return{ok:!1,error:di(Qn,"The node returned the same page cursor twice while listing issued delegations")};o.add(c)}}while(void 0!==c&&(void 0===s||a.length<s)&&(void 0===n||!a.some(e=>e.cid===n)));return{ok:!0,data:void 0===s?a:a.slice(0,s)}}async function gi(e,t){if(!t)return{ok:!1,error:di(Jn,"cid is required")};const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:di(Gn,"Revoking an issued delegation needs a session key signer")};try{const s=async(e,s,n)=>e(`${s}/revoke`,{method:"POST",headers:{Authorization:await r.sign({[`urn:cid:${t}`]:{[ci]:[{}]}},n)},redirect:"error"}),n=e.resourceTransport?await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>s(e.fetch,e.url,e.nodeDid),{nodeLocal:!0}):await s(e.fetchFn,e.host);if(!n.ok)return 404===n.status?{ok:!1,error:di("NOT_FOUND",`Delegation not found: ${t}`)}:{ok:!1,error:await hi(n,"Failed to revoke delegation",{cid:t})};const i=Xn.safeParse(await n.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:di("REVOCATION_FAILED","Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return kr(e)?{ok:!1,error:{...Mr("delegation",e),service:"delegation"}}:{ok:!1,error:di(zn,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}export{mi as queryAllIssued,fi as queryIssued,gi as revokeIssued};
|