@tinycloud/web-sdk 3.8.0-beta.2 → 3.8.0-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/adapters/BrowserSessionStorage.d.ts +17 -0
- package/dist/credentials.cjs +1 -1
- package/dist/credentials.mjs +1 -1
- package/dist/delegations-issued-entry.d.ts +3 -0
- package/dist/delegations-issued.cjs +1 -0
- package/dist/delegations-issued.mjs +1 -0
- package/dist/encryption-keys-entry.d.ts +3 -0
- package/dist/encryption-keys.cjs +2 -0
- package/dist/encryption-keys.cjs.LICENSE.txt +1 -0
- package/dist/encryption-keys.mjs +2 -0
- package/dist/encryption-keys.mjs.LICENSE.txt +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/modules/Storage/tinycloud/types.schema.d.ts +2 -2
- package/dist/modules/runtimeGrantPersistence.d.ts +41 -0
- package/dist/modules/tcw.d.ts +28 -1
- package/dist/panel-data.cjs +1 -1
- package/dist/panel-data.mjs +1 -1
- package/dist/panel.cjs +1 -1
- package/dist/panel.mjs +1 -1
- package/dist/replica.cjs +1 -1
- package/dist/replica.mjs +1 -1
- package/dist/ui/api.d.ts +8 -0
- package/dist/ui/client.d.ts +14 -2
- package/dist/ui/config.d.ts +9 -0
- package/dist/ui/data/authority.d.ts +26 -0
- package/dist/ui/data.d.ts +10 -1
- package/dist/ui/host.d.ts +2 -0
- package/dist/ui/panel-styles.d.ts +1 -1
- package/dist/ui/pending.d.ts +1 -1
- package/dist/ui/sections/delegations.strings.d.ts +5 -0
- package/dist/ui/slots.d.ts +13 -1
- package/dist/ui/styles.d.ts +1 -1
- package/package.json +6 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{"use strict";var e,t,a={d:(e,t)=>{for(var s in t)a.o(t,s)&&!a.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},s={};a.r(s),a.d(s,{queryAllIssued:()=>ct,queryIssued:()=>dt,revokeIssued:()=>ut}),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 n=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return n.undefined;case"string":return n.string;case"number":return Number.isNaN(e)?n.nan:n.number;case"boolean":return n.boolean;case"function":return n.function;case"bigint":return n.bigint;case"symbol":return n.symbol;case"object":return Array.isArray(e)?n.array:null===e?n.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?n.promise:"undefined"!=typeof Map&&e instanceof Map?n.map:"undefined"!=typeof Set&&e instanceof Set?n.set:"undefined"!=typeof Date&&e instanceof Date?n.date:n.object;default:return n.unknown}},r=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 o 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 o))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()}}o.create=e=>new o(e);const d=(t,a)=>{let s;switch(t.code){case r.invalid_type:s=t.received===n.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case r.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case r.unrecognized_keys:s=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case r.invalid_union:s="Invalid input";break;case r.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case r.invalid_enum_value:s=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case r.invalid_arguments:s="Invalid function arguments";break;case r.invalid_return_type:s="Invalid function return type";break;case r.invalid_date:s="Invalid date";break;case r.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 r.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 r.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 r.custom:s="Invalid input";break;case r.invalid_intersection_types:s="Intersection results could not be merged";break;case r.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case r.not_finite:s="Number must be finite";break;default:s=a.defaultError,e.assertNever(t)}return{message:s}};let c=d;var u;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(u||(u={}));function l(e,t){const a=c,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===d?void 0:d].filter(e=>!!e)});e.common.issues.push(s)}class h{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 p;"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 h.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 p;if("aborted"===n.status)return p;"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 p=Object.freeze({status:"aborted"}),m=e=>({status:"dirty",value:e}),f=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,g=e=>"dirty"===e.status,y=e=>"valid"===e.status,v=e=>"undefined"!=typeof Promise&&e instanceof Promise;class k{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 x=(e,t)=>{if(y(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 o(e.common.issues);return this._error=t,this._error}}};function b(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 w{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:i(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:i(e)},s=this._parseSync({data:e,path:a.path,parent:a});return x(a,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return y(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=>y(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:i(e)},s=this._parse({data:e,path:a.path,parent:a}),n=await(v(s)?s:Promise.resolve(s));return x(a,n)}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 n=e(t),i=()=>s.addIssue({code:r.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!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 be({schema:this,typeName:Ze.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 we.create(this,this._def)}nullable(){return Te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this)}promise(){return xe.create(this,this._def)}or(e){return ce.create([this,e],this._def)}and(e){return le.create(this,e,this._def)}transform(e){return new be({...b(this._def),schema:this,typeName:Ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Oe({...b(this._def),innerType:this,defaultValue:t,typeName:Ze.ZodDefault})}brand(){return new Ne({typeName:Ze.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ie({...b(this._def),innerType:this,catchValue:t,typeName:Ze.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return Se.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const T=/^c[^\s-]{8,}$/i,O=/^[0-9a-z]+$/,I=/^[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,N=/^[a-z0-9_-]{21}$/i,E=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,S=/^[-+]?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)?)??$/,R=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let C;const Z=/^(?:(?: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])$/,D=/^(([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]))$/,P=/^(([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}=))?$/,L=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,F="((\\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])))",V=new RegExp(`^${F}$`);function U(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 M(e){return new RegExp(`^${U(e)}$`)}function z(e){let t=`${F}T${U(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 K(e,t){return!("v4"!==t&&t||!Z.test(e))||!("v6"!==t&&t||!D.test(e))}function B(e,t){if(!E.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 W(e,t){return!("v4"!==t&&t||!j.test(e))||!("v6"!==t&&t||!P.test(e))}class q extends w{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==n.string){const e=this._getOrReturnCtx(t);return l(e,{code:r.invalid_type,expected:n.string,received:e.parsedType}),p}const a=new h;let s;for(const n of this._def.checks)if("min"===n.kind)t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if("max"===n.kind)t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.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?l(s,{code:r.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&l(s,{code:r.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),a.dirty())}else if("email"===n.kind)R.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"email",code:r.invalid_string,message:n.message}),a.dirty());else if("emoji"===n.kind)C||(C=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),C.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"emoji",code:r.invalid_string,message:n.message}),a.dirty());else if("uuid"===n.kind)A.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"uuid",code:r.invalid_string,message:n.message}),a.dirty());else if("nanoid"===n.kind)N.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"nanoid",code:r.invalid_string,message:n.message}),a.dirty());else if("cuid"===n.kind)T.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"cuid",code:r.invalid_string,message:n.message}),a.dirty());else if("cuid2"===n.kind)O.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"cuid2",code:r.invalid_string,message:n.message}),a.dirty());else if("ulid"===n.kind)I.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"ulid",code:r.invalid_string,message:n.message}),a.dirty());else if("url"===n.kind)try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),l(s,{validation:"url",code:r.invalid_string,message:n.message}),a.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"regex",code:r.invalid_string,message:n.message}),a.dirty())):"trim"===n.kind?t.data=t.data.trim():"includes"===n.kind?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),a.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),l(s,{code:r.invalid_string,validation:{startsWith:n.value},message:n.message}),a.dirty()):"endsWith"===n.kind?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:{endsWith:n.value},message:n.message}),a.dirty()):"datetime"===n.kind?z(n).test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:"datetime",message:n.message}),a.dirty()):"date"===n.kind?V.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:"date",message:n.message}),a.dirty()):"time"===n.kind?M(n).test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:"time",message:n.message}),a.dirty()):"duration"===n.kind?S.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"duration",code:r.invalid_string,message:n.message}),a.dirty()):"ip"===n.kind?K(t.data,n.version)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"ip",code:r.invalid_string,message:n.message}),a.dirty()):"jwt"===n.kind?B(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"jwt",code:r.invalid_string,message:n.message}),a.dirty()):"cidr"===n.kind?W(t.data,n.version)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"cidr",code:r.invalid_string,message:n.message}),a.dirty()):"base64"===n.kind?$.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"base64",code:r.invalid_string,message:n.message}),a.dirty()):"base64url"===n.kind?L.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"base64url",code:r.invalid_string,message:n.message}),a.dirty()):e.assertNever(n);return{status:a.value,value:t.data}}_regex(e,t,a){return this.refinement(t=>e.test(t),{validation:t,code:r.invalid_string,...u.errToObj(a)})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...u.errToObj(e)})}url(e){return this._addCheck({kind:"url",...u.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...u.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...u.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...u.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...u.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...u.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...u.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...u.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...u.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...u.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...u.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...u.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,...u.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,...u.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...u.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...u.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...u.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...u.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...u.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...u.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...u.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...u.errToObj(t)})}nonempty(e){return this.min(1,u.errToObj(e))}trim(){return new q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q({...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 H(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}q.create=e=>new q({checks:[],typeName:Ze.ZodString,coerce:e?.coerce??!1,...b(e)});class J extends w{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)!==n.number){const e=this._getOrReturnCtx(t);return l(e,{code:r.invalid_type,expected:n.number,received:e.parsedType}),p}let a;const s=new h;for(const n of this._def.checks)"int"===n.kind?e.isInteger(t.data)||(a=this._getOrReturnCtx(t,a),l(a,{code:r.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.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)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):"multipleOf"===n.kind?0!==H(t.data,n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(a=this._getOrReturnCtx(t,a),l(a,{code:r.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,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,a,s){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:u.toString(s)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:u.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:u.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:u.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:u.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)}}J.create=e=>new J({checks:[],typeName:Ze.ZodNumber,coerce:e?.coerce||!1,...b(e)});class Q extends w{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)!==n.bigint)return this._getInvalidInput(t);let a;const s=new h;for(const n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.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)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.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 l(t,{code:r.invalid_type,expected:n.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,a,s){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:u.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:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.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:Ze.ZodBigInt,coerce:e?.coerce??!1,...b(e)});class G extends w{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==n.boolean){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.boolean,received:t.parsedType}),p}return f(e.data)}}G.create=e=>new G({typeName:Ze.ZodBoolean,coerce:e?.coerce||!1,...b(e)});class X extends w{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==n.date){const e=this._getOrReturnCtx(t);return l(e,{code:r.invalid_type,expected:n.date,received:e.parsedType}),p}if(Number.isNaN(t.data.getTime()))return l(this._getOrReturnCtx(t),{code:r.invalid_date}),p;const a=new h;let s;for(const n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),a.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),a.dirty()):e.assertNever(n);return{status:a.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:u.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:u.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:Ze.ZodDate,...b(e)});class Y extends w{_parse(e){if(this._getType(e)!==n.symbol){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.symbol,received:t.parsedType}),p}return f(e.data)}}Y.create=e=>new Y({typeName:Ze.ZodSymbol,...b(e)});class ee extends w{_parse(e){if(this._getType(e)!==n.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.undefined,received:t.parsedType}),p}return f(e.data)}}ee.create=e=>new ee({typeName:Ze.ZodUndefined,...b(e)});class te extends w{_parse(e){if(this._getType(e)!==n.null){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.null,received:t.parsedType}),p}return f(e.data)}}te.create=e=>new te({typeName:Ze.ZodNull,...b(e)});class ae extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return f(e.data)}}ae.create=e=>new ae({typeName:Ze.ZodAny,...b(e)});class se extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return f(e.data)}}se.create=e=>new se({typeName:Ze.ZodUnknown,...b(e)});class ne extends w{_parse(e){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.never,received:t.parsedType}),p}}ne.create=e=>new ne({typeName:Ze.ZodNever,...b(e)});class ie extends w{_parse(e){if(this._getType(e)!==n.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.void,received:t.parsedType}),p}return f(e.data)}}ie.create=e=>new ie({typeName:Ze.ZodVoid,...b(e)});class re extends w{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),s=this._def;if(t.parsedType!==n.array)return l(t,{code:r.invalid_type,expected:n.array,received:t.parsedType}),p;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(l(t,{code:e?r.too_big:r.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}),a.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(l(t,{code:r.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),a.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(l(t,{code:r.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map((e,a)=>s.type._parseAsync(new k(t,e,t.path,a)))).then(e=>h.mergeArray(a,e));const i=[...t.data].map((e,a)=>s.type._parseSync(new k(t,e,t.path,a)));return h.mergeArray(a,i)}get element(){return this._def.type}min(e,t){return new re({...this._def,minLength:{value:e,message:u.toString(t)}})}max(e,t){return new re({...this._def,maxLength:{value:e,message:u.toString(t)}})}length(e,t){return new re({...this._def,exactLength:{value:e,message:u.toString(t)}})}nonempty(e){return this.min(1,e)}}function oe(e){if(e instanceof de){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=we.create(oe(s))}return new de({...e._def,shape:()=>t})}return e instanceof re?new re({...e._def,type:oe(e.element)}):e instanceof we?we.create(oe(e.unwrap())):e instanceof Te?Te.create(oe(e.unwrap())):e instanceof he?he.create(e.items.map(e=>oe(e))):e}re.create=(e,t)=>new re({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ze.ZodArray,...b(t)});class de extends w{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)!==n.object){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.object,received:t.parsedType}),p}const{status:t,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ne&&"strip"===this._def.unknownKeys))for(const e in a.data)i.includes(e)||o.push(e);const d=[];for(const e of i){const t=s[e],n=a.data[e];d.push({key:{status:"valid",value:e},value:t._parse(new k(a,n,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof ne){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)d.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)o.length>0&&(l(a,{code:r.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 s=a.data[t];d.push({key:{status:"valid",value:t},value:e._parse(new k(a,s,a.path,t)),alwaysSet:t in a.data})}}return a.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=>h.mergeObjectSync(t,e)):h.mergeObjectSync(t,d)}get shape(){return this._def.shape()}strict(e){return u.errToObj,new de({...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:u.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ze.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...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 de({...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 de({...this._def,shape:()=>a})}deepPartial(){return oe(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 de({...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 we;)e=e._def.innerType;a[s]=e}return new de({...this._def,shape:()=>a})}keyof(){return ye(e.objectKeys(this.shape))}}de.create=(e,t)=>new de({shape:()=>e,unknownKeys:"strip",catchall:ne.create(),typeName:Ze.ZodObject,...b(t)}),de.strictCreate=(e,t)=>new de({shape:()=>e,unknownKeys:"strict",catchall:ne.create(),typeName:Ze.ZodObject,...b(t)}),de.lazycreate=(e,t)=>new de({shape:e,unknownKeys:"strip",catchall:ne.create(),typeName:Ze.ZodObject,...b(t)});class ce extends w{_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 o(e.ctx.common.issues));return l(t,{code:r.invalid_union,unionErrors:a}),p});{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 n=s.map(e=>new o(e));return l(t,{code:r.invalid_union,unionErrors:n}),p}}get options(){return this._def.options}}function ue(t,a){const s=i(t),r=i(a);if(t===a)return{valid:!0,data:t};if(s===n.object&&r===n.object){const s=e.objectKeys(a),n=e.objectKeys(t).filter(e=>-1!==s.indexOf(e)),i={...t,...a};for(const e of n){const s=ue(t[e],a[e]);if(!s.valid)return{valid:!1};i[e]=s.data}return{valid:!0,data:i}}if(s===n.array&&r===n.array){if(t.length!==a.length)return{valid:!1};const e=[];for(let s=0;s<t.length;s++){const n=ue(t[s],a[s]);if(!n.valid)return{valid:!1};e.push(n.data)}return{valid:!0,data:e}}return s===n.date&&r===n.date&&+t===+a?{valid:!0,data:t}:{valid:!1}}ce.create=(e,t)=>new ce({options:e,typeName:Ze.ZodUnion,...b(t)});class le extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=(e,s)=>{if(_(e)||_(s))return p;const n=ue(e.value,s.value);return n.valid?((g(e)||g(s))&&t.dirty(),{status:t.value,value:n.data}):(l(a,{code:r.invalid_intersection_types}),p)};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}))}}le.create=(e,t,a)=>new le({left:e,right:t,typeName:Ze.ZodIntersection,...b(a)});class he extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.array)return l(a,{code:r.invalid_type,expected:n.array,received:a.parsedType}),p;if(a.data.length<this._def.items.length)return l(a,{code:r.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&a.data.length>this._def.items.length&&(l(a,{code:r.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...a.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new k(a,e,a.path,t)):null}).filter(e=>!!e);return a.common.async?Promise.all(s).then(e=>h.mergeArray(t,e)):h.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new he({...this._def,rest:e})}}he.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new he({items:e,typeName:Ze.ZodTuple,rest:null,...b(t)})};class pe extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.object)return l(a,{code:r.invalid_type,expected:n.object,received:a.parsedType}),p;const s=[],i=this._def.keyType,o=this._def.valueType;for(const e in a.data)s.push({key:i._parse(new k(a,e,a.path,e)),value:o._parse(new k(a,a.data[e],a.path,e)),alwaysSet:e in a.data});return a.common.async?h.mergeObjectAsync(t,s):h.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,a){return new pe(t instanceof w?{keyType:e,valueType:t,typeName:Ze.ZodRecord,...b(a)}:{keyType:q.create(),valueType:e,typeName:Ze.ZodRecord,...b(t)})}}class me extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.map)return l(a,{code:r.invalid_type,expected:n.map,received:a.parsedType}),p;const s=this._def.keyType,i=this._def.valueType,o=[...a.data.entries()].map(([e,t],n)=>({key:s._parse(new k(a,e,a.path,[n,"key"])),value:i._parse(new k(a,t,a.path,[n,"value"]))}));if(a.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 p;"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 p;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}me.create=(e,t,a)=>new me({valueType:t,keyType:e,typeName:Ze.ZodMap,...b(a)});class fe extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.set)return l(a,{code:r.invalid_type,expected:n.set,received:a.parsedType}),p;const s=this._def;null!==s.minSize&&a.data.size<s.minSize.value&&(l(a,{code:r.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&a.data.size>s.maxSize.value&&(l(a,{code:r.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const a=new Set;for(const s of e){if("aborted"===s.status)return p;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const d=[...a.data.values()].map((e,t)=>i._parse(new k(a,e,a.path,t)));return a.common.async?Promise.all(d).then(e=>o(e)):o(d)}min(e,t){return new fe({...this._def,minSize:{value:e,message:u.toString(t)}})}max(e,t){return new fe({...this._def,maxSize:{value:e,message:u.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}fe.create=(e,t)=>new fe({valueType:e,minSize:null,maxSize:null,typeName:Ze.ZodSet,...b(t)});class _e extends w{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:Ze.ZodLazy,...b(t)});class ge extends w{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:r.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ye(e,t){return new ve({values:e,typeName:Ze.ZodEnum,...b(t)})}ge.create=(e,t)=>new ge({value:e,typeName:Ze.ZodLiteral,...b(t)});class ve extends w{_parse(t){if("string"!=typeof t.data){const a=this._getOrReturnCtx(t),s=this._def.values;return l(a,{expected:e.joinValues(s),received:a.parsedType,code:r.invalid_type}),p}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 l(e,{received:e.data,code:r.invalid_enum_value,options:a}),p}return f(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=ye;class ke extends w{_parse(t){const a=e.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==n.string&&s.parsedType!==n.number){const t=e.objectValues(a);return l(s,{expected:e.joinValues(t),received:s.parsedType,code:r.invalid_type}),p}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(a);return l(s,{received:s.data,code:r.invalid_enum_value,options:t}),p}return f(t.data)}get enum(){return this._def.values}}ke.create=(e,t)=>new ke({values:e,typeName:Ze.ZodNativeEnum,...b(t)});class xe extends w{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.promise&&!1===t.common.async)return l(t,{code:r.invalid_type,expected:n.promise,received:t.parsedType}),p;const a=t.parsedType===n.promise?t.data:Promise.resolve(t.data);return f(a.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(e,t)=>new xe({type:e,typeName:Ze.ZodPromise,...b(t)});class be extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ze.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=>{l(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 p;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===a.value?m(t.value):t});{if("aborted"===a.value)return p;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===a.value?m(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?p:("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?p:("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(!y(e))return p;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=>y(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:a.value,value:e})):p)}e.assertNever(n)}}be.create=(e,t,a)=>new be({schema:e,typeName:Ze.ZodEffects,effect:t,...b(a)}),be.createWithPreprocess=(e,t,a)=>new be({schema:t,effect:{type:"preprocess",transform:e},typeName:Ze.ZodEffects,...b(a)});class we extends w{_parse(e){return this._getType(e)===n.undefined?f(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(e,t)=>new we({innerType:e,typeName:Ze.ZodOptional,...b(t)});class Te extends w{_parse(e){return this._getType(e)===n.null?f(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:Ze.ZodNullable,...b(t)});class Oe extends w{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===n.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:Ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Ie extends w{_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 o(a.common.issues)},input:a.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new o(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Ze.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class Ae extends w{_parse(e){if(this._getType(e)!==n.nan){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Ae.create=e=>new Ae({typeName:Ze.ZodNaN,...b(e)}),Symbol("zod_brand");class Ne extends w{_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 Ee extends w{_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?p:"dirty"===e.status?(t.dirty(),m(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?p:"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 Ee({in:e,out:t,typeName:Ze.ZodPipeline})}}class Se extends w{_parse(e){const t=this._def.innerType._parse(e),a=e=>(y(e)&&(e.value=Object.freeze(e.value)),e);return v(t)?t.then(e=>a(e)):a(t)}unwrap(){return this._def.innerType}}function Re(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function Ce(e,t={},a){return e?ae.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Re(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Re(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}}):ae.create()}var Ze;Se.create=(e,t)=>new Se({innerType:e,typeName:Ze.ZodReadonly,...b(t)}),de.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"}(Ze||(Ze={}));const je=q.create,De=J.create,Pe=(Ae.create,Q.create,G.create),$e=(X.create,Y.create,ee.create,te.create,ae.create,se.create),Le=(ne.create,ie.create,re.create),Fe=de.create,Ve=(de.strictCreate,ce.create,le.create,he.create,pe.create),Ue=(me.create,fe.create,_e.create,ge.create),Me=ve.create,ze=(ke.create,xe.create,be.create,we.create,Te.create,be.createWithPreprocess,Ee.create,e=>X.create({...e,coerce:!0}));var Ke=Fe({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:Le(je()).optional()}),Be=Me(["main","session","ingested"]),We=Fe({id:je(),did:je(),type:Be,jwk:Ke.optional(),priority:De()}),qe=(Fe({code:je(),message:je(),service:Ue("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Ce(t=>t instanceof e,t))(Error).optional(),meta:Ve(je(),$e()).optional()}),{AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_EXPIRED:"AUTH_EXPIRED",NOT_INITIALIZED:"NOT_INITIALIZED",NOT_FOUND:"NOT_FOUND",REVOKED:"REVOKED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",CREATION_FAILED:"CREATION_FAILED",REVOCATION_FAILED:"REVOCATION_FAILED",INVALID_TOKEN:"INVALID_TOKEN",KV_SERVICE_UNAVAILABLE:"KV_SERVICE_UNAVAILABLE",DATA_FETCH_FAILED:"DATA_FETCH_FAILED",VALIDATION_ERROR:"VALIDATION_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",CHAIN_TOO_DEEP:"CHAIN_TOO_DEEP",INVALID_CURSOR:"INVALID_CURSOR"}),He=Fe({cid:je(),delegateDID:je(),spaceId:je(),path:je(),actions:Le(je()),caveats:Le(Ve(je(),$e())).optional(),expiry:ze(),isRevoked:Pe(),delegatorDID:je().optional(),createdAt:ze().optional(),parentCid:je().optional(),allowSubDelegation:Pe().optional(),authHeader:je().optional()}),Je=(Fe({cid:je().min(1),status:Me(["active","revoked","expired","unavailable","not_found"]),exists:Pe(),active:Pe(),revoked:Pe(),expired:Pe()}).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:r.custom,message:"delegation status flags do not match status"})}),Fe({revoked:Ue(!0),cid:je().min(1)}).strict()),Qe=Fe({resource:je().min(1),actions:Le(je()),caveats:Le(Ve(je(),$e()))}).strict(),Ge=je().datetime({offset:!0}).transform(e=>new Date(e)),Xe=Fe({cid:je().min(1),direction:Me(["granted","received"]),delegatorDid:je().min(1),delegateDid:je().min(1),resources:Le(Qe),parents:Le(je()),issuedAt:Ge.nullable(),notBefore:Ge.nullable(),expiresAt:Ge.nullable(),status:Me(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:Ge.nullable().optional(),revokedBy:je().optional(),revokedAncestorCid:je().optional()}).strict(),Ye=Fe({schemaVersion:Ue(2),items:Le(Xe),nextCursor:je().optional()}).strict(),et=(Fe({direction:Me(["granted","received","all","issued"]).optional(),status:Me(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:je().trim().min(1).optional(),limit:De().int().min(1).max(100).optional(),cursor:je().min(1).optional()}).strict(),Fe({resource:je(),action:je(),keys:Le(We),delegation:He,expiresAt:ze().optional()}),Fe({cid:je(),spaceId:je(),delegator:je(),delegatee:je(),keyId:je().optional(),path:je(),actions:Le(je()),expiry:ze().optional(),notBefore:ze().optional(),isRevoked:Pe(),createdAt:ze(),parentCid:je().optional()}),Fe({delegateDID:je(),path:je(),actions:Le(je()),expiry:ze().optional(),disableSubDelegation:Pe().optional(),statement:je().optional()}),Le(He),Fe({root:He,chain:Le(He),leaf:He}),Me(["granted","received","all"])),tt=(Fe({direction:et.optional(),path:je().optional(),actions:Le(je()).optional(),includeRevoked:Pe().optional(),delegator:je().optional(),delegatee:je().optional(),validAt:ze().optional(),limit:De().optional(),cursor:je().optional()}),Me(["owned","delegated"])),at=(Fe({id:je(),name:je().optional(),owner:je(),type:tt,permissions:Le(je()).optional(),expiresAt:ze().optional()}),Me(["base64","compact","ipfs"]));Fe({token:je(),url:je(),delegation:He,schema:at,expiresAt:ze().optional(),description:je().optional()}),Fe({data:$e(),delegation:He,spaceId:je(),path:je()}),Fe({persist:Pe().optional(),validateChain:Pe().optional(),keyName:je().optional(),createSessionKey:Pe().optional(),priority:De().optional()}),Fe({path:je(),actions:Le(je()).optional(),expiry:ze().optional(),schema:at.optional(),description:je().optional(),baseUrl:je().optional(),allowSubDelegation:Pe().optional()}),Fe({hosts:Le(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:Ce().optional(),sessionInvocationSigner:Ce().optional(),fetch:$e().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Fe({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"})}),Fe({siwe:je(),signature:je(),version:De(),cid:je().optional()});var st=Fe({service:je(),space:je(),path:je(),actions:Le(je()),caveats:Le(Ve(je(),$e())).optional()}),nt=(Fe({session:$e().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:je(),spaceId:je(),abilities:Ve(je(),Ve(je(),Le(je()))),expirationSecs:De(),notBeforeSecs:De().optional(),disableSubDelegation:Pe().optional()}),Fe({delegation:je(),cid:je(),delegateDID:je(),expiry:ze(),resources:Le(st)}),{REVOKE:"tinycloud.delegation/revoke",STATUS:"tinycloud.delegation/status",LIST:"tinycloud.delegation/list",GET:"tinycloud.delegation/get",CHECK:"tinycloud.delegation/check"});function it(e,t,a,s){return{code:e,message:t,service:"delegation",cause:a,meta:s}}var rt="delegation-issued-query-v1";async function ot(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?it(qe.PERMISSION_DENIED,""===s?"The node refused the request":s,void 0,n):400===e.status&&s.includes("invalid delegation query cursor")?it(qe.INVALID_CURSOR,"The node rejected the page cursor; list again from the start",void 0,n):503===e.status?it(qe.CHAIN_TOO_DEEP,"This delegation chain is too long for the node to check right now; try again later",void 0,{...n,retryable:!0}):it(qe.NETWORK_ERROR,`${t}: ${e.status} - ${s}`,void 0,n)}async function dt(e,t){const a=e.sessionInvocationSigner;if(!a)return{ok:!1,error:it(qe.NOT_INITIALIZED,"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:it(qe.NETWORK_ERROR,`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(rt),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!s.ok)return s;if(!s.data)return{ok:!1,error:it(qe.UNSUPPORTED_OPERATION,"This node doesn't support listing issued delegations yet",void 0,{feature:rt})};const n=await a.sign({[`${a.did()}/delegation`]:{[nt.LIST]:[{}]}}),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 ot(i,"Failed to query issued delegations",{})};const r=Ye.safeParse(await i.json());return r.success?{ok:!0,data:r.data}:{ok:!1,error:it(qe.INVALID_TOKEN,"Node returned an invalid delegation query response")}}catch(e){return{ok:!1,error:it(qe.NETWORK_ERROR,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function ct(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:it(qe.INVALID_INPUT,"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:it(qe.INVALID_TOKEN,"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 ut(e,t){if(!t)return{ok:!1,error:it(qe.INVALID_INPUT,"cid is required")};const a=e.sessionInvocationSigner;if(!a)return{ok:!1,error:it(qe.NOT_INITIALIZED,"Revoking an issued delegation needs a session key signer")};try{const s=await a.sign({[`urn:cid:${t}`]:{[nt.REVOKE]:[{}]}}),n=await e.fetchFn(`${e.host}/revoke`,{method:"POST",headers:{Authorization:s}});if(!n.ok)return 404===n.status?{ok:!1,error:it(qe.NOT_FOUND,`Delegation not found: ${t}`)}:{ok:!1,error:await ot(n,"Failed to revoke delegation",{cid:t})};const i=Je.safeParse(await n.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:it(qe.REVOCATION_FAILED,"Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return{ok:!1,error:it(qe.NETWORK_ERROR,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}module.exports=s})();
|
|
@@ -0,0 +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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! For license information please see encryption-keys.cjs.LICENSE.txt */
|
|
2
|
+
(()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createNamedKeyClient:()=>Kt});class n extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const i="2.45.1";let r=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,s=`viem@${i}`;class o extends Error{constructor(e,t={}){const n=t.cause instanceof o?t.cause.details:t.cause?.message?t.cause.message:t.details,c=t.cause instanceof o&&t.cause.docsPath||t.docsPath,a=r?.({...t,docsPath:c});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...n?[`Details: ${n}`]:[],...s?[`Version: ${s}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=c,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=i}walk(e){return c(this,e)}}function c(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?c(e.cause,t):t?null:e}class a extends o{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function d(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}class u extends o{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function l(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const i=e.replace("0x","");if(i.length>2*n)throw new u({size:Math.ceil(i.length/2),targetSize:n,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new u({size:e.length,targetSize:n,type:"bytes"});const i=new Uint8Array(n);for(let r=0;r<n;r++){const s="right"===t;i[s?r:n-r-1]=e[s?r:e.length-r-1]}return i}(e,{dir:t,size:n})}class y extends o{constructor({max:e,min:t,signed:n,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class p extends o{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function h(e){return d(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function f(e,{size:t}){if(h(e)>t)throw new p({givenSize:h(e),maxSize:t})}function w(e,t={}){const{signed:n,size:i}=t,r=BigInt(e);let s;i?s=n?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&r>s||r<o){const t="bigint"==typeof e?"n":"";throw new y({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:i,value:`${e}${t}`})}const c=`0x${(n&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?l(c,{size:i}):c}const k=new TextEncoder;const v={zero:48,nine:57,A:65,F:70,a:97,f:102};function g(e){return e>=v.zero&&e<=v.nine?e-v.zero:e>=v.A&&e<=v.F?e-(v.A-10):e>=v.a&&e<=v.f?e-(v.a-10):void 0}function m(e,t={}){let n=e;t.size&&(f(n,{size:t.size}),n=l(n,{dir:"right",size:t.size}));let i=n.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,s=new Uint8Array(r);for(let e=0,t=0;e<r;e++){const n=g(i.charCodeAt(t++)),r=g(i.charCodeAt(t++));if(void 0===n||void 0===r)throw new o(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);s[e]=16*n+r}return s}function b(e,t={}){const n=k.encode(e);return"number"==typeof t.size?(f(n,{size:t.size}),l(n,{dir:"right",size:t.size})):n}const I=BigInt(2**32-1),E=BigInt(32);function N(e,t=!1){return t?{h:Number(e&I),l:Number(e>>E&I)}:{h:0|Number(e>>E&I),l:0|Number(e&I)}}function S(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function $(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function _(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function A(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function O(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const P=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=O(e[t]);return e};function x(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),$(e),e}class T{}const D=BigInt(0),K=BigInt(1),z=BigInt(2),R=BigInt(7),L=BigInt(256),C=BigInt(113),M=[],V=[],U=[];for(let e=0,t=K,n=1,i=0;e<24;e++){[n,i]=[i,(2*n+3*i)%5],M.push(2*(5*i+n)),V.push((e+1)*(e+2)/2%64);let r=D;for(let e=0;e<7;e++)t=(t<<K^(t>>R)*C)%L,t&z&&(r^=K<<(K<<BigInt(e))-K);U.push(r)}const H=function(e,t=!1){const n=e.length;let i=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=N(e[s],t);[i[s],r[s]]=[n,o]}return[i,r]}(U,!0),B=H[0],j=H[1],q=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),F=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class G extends T{constructor(e,t,n,i=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=r,S(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}clone(){return this._cloneInto()}keccak(){P(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,s=n[r],o=n[r+1],c=q(s,o,1)^n[i],a=F(s,o,1)^n[i+1];for(let n=0;n<50;n+=10)e[t+n]^=c,e[t+n+1]^=a}let t=e[2],r=e[3];for(let n=0;n<24;n++){const i=V[n],s=q(t,r,i),o=F(t,r,i),c=M[n];t=e[c],r=e[c+1],e[c]=s,e[c+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)n[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~n[(i+2)%10]&n[(i+4)%10]}e[0]^=B[i],e[1]^=j[i]}A(n)}(this.state32,this.rounds),P(this.state32),this.posOut=0,this.pos=0}update(e){_(this),$(e=x(e));const{blockLen:t,state:n}=this,i=e.length;for(let r=0;r<i;){const s=Math.min(t-this.pos,i-r);for(let t=0;t<s;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,128&t&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){_(this,!1),$(e),this.finish();const t=this.state,{blockLen:n}=this;for(let i=0,r=e.length;i<r;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return S(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){$(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,A(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:i,rounds:r,enableXOF:s}=this;return e||(e=new G(t,n,i,s,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}}const Y=(e,t,n)=>function(e){const t=t=>e().update(x(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new G(t,e,n)),W=(()=>Y(1,136,32))(),J=new n(8192);function X(e,t){if(J.has(`${e}.${t}`))return J.get(`${e}.${t}`);const n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),i=function(e){const t=W(d(e,{strict:!1})?function(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){return m(w(e,t))}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(f(n,{size:t.size}),l(n,{size:t.size})):n}(e,t):d(e)?m(e,t):b(e,t)}(e):e);return t}(b(n)),r=(t?n.substring(`${t}0x`.length):n).split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&i[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());const s=`0x${r.join("")}`;return J.set(`${e}.${t}`,s),s}const Z=/^0x[a-fA-F0-9]{40}$/,Q=new n(8192);function ee(e,t){const{strict:n=!0}=t??{},i=`${e}.${n}`;if(Q.has(i))return Q.get(i);const r=!(!Z.test(e)||e.toLowerCase()!==e&&n&&X(e)!==e);return Q.set(i,r),r}var te=[{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 ne(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function ie(e){return e.slice(10,e.indexOf("/"))}function re(e){return e.slice(e.indexOf("/")+1)}function se(e){const t={};for(const n of te)ie(n.urn)===e&&(t[ne(re(n.urn))]=n.urn);return t}var oe=se("kv"),ce={...se("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},ae=(se("duckdb"),se("capabilities")),de=(se("hooks"),se("encryption")),ue=se("space"),le="applications",ye="account",pe="applications/",he="secrets",fe="default",we="public",ke="agents",ve="tinycloud.encryption",ge=de.NETWORK_CREATE,me=[fe,le,ye,he,we,ke],be={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:fe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:fe,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:fe,path:"",actions:["read","write"]}]},Ie={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:le,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:le,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:le,path:"",actions:["read","write"]}]},Ee={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ye,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ye,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ye,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ye,path:"account",actions:["read","write","schema"]}]},Ne={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:he,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:he,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:he,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:he,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:he,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:he,path:"",actions:["read"],skipPrefix:!0}]},Se={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:we,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:we,path:"",actions:["get","list","metadata"]}]},$e={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ke,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ke,path:"",actions:["get","put","del","list","metadata"]}]},_e={[fe]:be,[le]:Ie,[ye]:Ee,[he]:Ne,[we]:Se,[ke]:$e};function Ae(e,t=1){return function(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`Invalid EIP-155 chain ID: ${e}`)}(t),`did:pkh:eip155:${t}:${function(e){if(!ee(e,{strict:!1}))throw new Error(`Invalid EVM address: ${e}`);return function(e){if(!ee(e,{strict:!1}))throw new a({address:e});return X(e,void 0)}(e)}(e)}`}function Oe(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Pe(e,t,n){return!0===n||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function xe(e,t,n){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const n=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,i="read"===n||"get"===n?oe.GET:"write"===n||"put"===n?oe.PUT:"delete"===n||"del"===n?oe.DEL:"list"===n?oe.LIST:"metadata"===n?oe.METADATA:void 0;if(void 0===i)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const r=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${r}`,actions:[i],skipPrefix:!0}})}(e).flatMap(e=>xe(e,t,n));const i=!0===e.skipPrefix||e.service===ve;return[{service:e.service,space:e.service===ve?"encryption":e.space??n,path:Pe(t,e.path,i),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 Te(e){const t=new Set(e.filter(e=>e.service!==ve).map(e=>e.space));return function(e){const t=new Map;for(const n of e){const e=`${n.service}\0${n.space}\0${n.path}`,i=t.get(e);if(i)for(const e of n.actions)i.actions.includes(e)||i.actions.push(e);else t.set(e,{...n,actions:[...n.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[ae.READ]}))])}function De(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const n=t.includeAccountRegistryPermissions??!0,i=e.map(Oe),r=i.flatMap(e=>{const t=e.prefix??e.app_id,n=e.space??le;return(e.permissions??[]).flatMap(e=>xe(e,t,n))});n&&r.push(...Ke.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of i){const t=s.get(e.app_id)??[];t.push(Oe(e)),s.set(e.app_id,t)}return{manifests:i,resources:Te(r),delegationTargets:[],registryRecords:n?[...s.entries()].map(([e,t])=>({key:`${pe}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:i.some(e=>e.includePublicSpace??!0)}}([_e[e]],{includeAccountRegistryPermissions:!1})}me.map(e=>({name:e,manifest:_e[e],persistedAsApplication:e===he}));var Ke=Object.freeze([{service:"tinycloud.kv",space:ye,path:pe,actions:[oe.GET,oe.PUT,oe.LIST]},{service:"tinycloud.kv",space:ye,path:"spaces/",actions:[oe.GET,oe.PUT,oe.LIST]},{service:"tinycloud.kv",space:ye,path:"system/bootstrap/complete",actions:[oe.GET,oe.PUT]},{service:"tinycloud.delegation",space:ye,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ye,path:"account",actions:[ce.READ,ce.WRITE,ce.SCHEMA]},{service:"tinycloud.capabilities",space:ye,path:"",actions:[ae.READ]}]),ze=De(fe),Re={...ze,resources:[...ze.resources,...Ke.map(e=>({...e,actions:[...e.actions]}))]},Le=Object.freeze(Object.fromEntries(me.map(e=>[e,e===fe?Re:De(e)]))),Ce=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ge]}]);function Me(e){return void 0===e?"":Ve(e)}function Ve(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(Ve).join(",")}]`;const t=Object.keys(e).sort(),n=[];for(const i of t){const t=e[i];void 0!==t&&n.push(`${JSON.stringify(i)}:${Ve(t)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}Object.freeze(me.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:Le[e].resources,...e===ye?{rawAbilities:Ce}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[ue.HOST]}]));var Ue="0123456789abcdef";function He(e){let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=Ue[i>>4&15]+Ue[15&i]}return t}function Be(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let i=0;i<e.length;i+=3){const r=e[i],s=i+1<e.length?e[i+1]:0,o=i+2<e.length?e[i+2]:0;n+=t[r>>2&63],n+=t[63&(r<<4|s>>4)],n+=i+1<e.length?t[63&(s<<2|o>>6)]:"=",n+=i+2<e.length?t[63&o]:"="}return n}function je(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),n=t.length;if(n%4!=0)throw new Error("invalid base64 input");const i=n/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),r=new Uint8Array(i),s={};for(let e=0;e<64;e++)s["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let o=0;for(let e=0;e<n;e+=4){const n=s[t[e]]??0,c=s[t[e+1]]??0,a="="===t[e+2]?0:s[t[e+2]]??0,d=n<<2|c>>4,u=(15&c)<<4|a>>2,l=(3&a)<<6|("="===t[e+3]?0:s[t[e+3]]??0);o<i&&(r[o++]=d),o<i&&(r[o++]=u),o<i&&(r[o++]=l)}return r}function qe(e){return(new TextEncoder).encode(e)}function Fe(e,t){return He(e(qe(Me(t))))}var Ge="urn:tinycloud:encryption:",Ye=/^[a-z0-9][a-z0-9-]*$/,We=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Je(e){if("string"!=typeof e||0===e.length)throw new We("networkId must be a non-empty string");if(!e.startsWith(Ge))throw new We(`networkId must start with ${Ge} (got ${JSON.stringify(e)})`);const t=e.slice(25),n=t.lastIndexOf(":");if(n<=0||n===t.length-1)throw new We(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const i=t.slice(0,n),r=t.slice(n+1);if(!i.startsWith("did:"))throw new We(`networkId ownerDid must be a DID (got ${JSON.stringify(i)})`);const s=i.split(":");if(s.length<3||s.some(e=>0===e.length))throw new We(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(i)})`);if(!Ye.test(r))throw new We(`networkId name ${JSON.stringify(r)} must match ${Ye.source}`);return{networkId:e,ownerDid:i,name:r}}var Xe=Ge,Ze="tinycloud.encryption.decrypt/v1",Qe="tinycloud.encryption.decrypt-result/v1",et="tinycloud.encryption/decrypt";function tt(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}}function nt(e){return{...e,service:"encryption",message:tt(e)}}var it="[a-z0-9][a-z0-9._-]{0,63}",rt=new RegExp(`^${it}(?:/${it}){0,7}$`),st=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ot=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,ct="did:pkh:eip155:",at="tinycloud.encryption/key.create",dt="tinycloud.encryption/key.block",ut="tinycloud.encryption/key.unblock",lt=(Object.freeze([et,at,dt,ut]),class extends Error{constructor(e,t){super(t),this.name="EncryptionResourceError",this.code=e}});function yt(e){if(!e.startsWith(ct))return e;const t=e.slice(15),n=t.indexOf(":"),i=-1===n?"":t.slice(0,n),r=-1===n?"":t.slice(n+1);if(!/^\d+$/.test(i)||!/^0x[a-fA-F0-9]{40}$/.test(r))throw new lt("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(e)})`);const s=BigInt(i);if(0n===s||s>18446744073709551615n)throw new lt("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(i)})`);const o=Ae(r,1).slice(17);return`${ct}${s}:${o}`}function pt(e){const t=yt(e);if(t!==e)throw new lt("non_canonical_owner",`owner DID is not canonical (expected ${t})`)}function ht(e,t){if(0===e.length)throw new lt("empty_path",`${t} must not be empty`);if((new TextEncoder).encode(e).length>255)throw new lt("path_too_long",`${t} exceeds 255 bytes`);if(!rt.test(e))throw new lt("bad_path",`${t} ${JSON.stringify(e)} must match ${rt.source}`);const n=e.split("/");if("apps"===n[0]&&n.length<("key path"===t?3:2))throw new lt("bad_path",`${t} ${JSON.stringify(e)} under apps/ needs ${"key path"===t?"apps/<id>/<name>":"apps/<id>/"}`)}function ft(e){if("string"!=typeof e||!e.startsWith(Xe))throw new lt("not_encryption_urn",`resource must start with ${Xe}`);const t=e.slice(25),n=ot.exec(t);if(null===n)throw new lt("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(e)})`);const i=n[1],r=n[2],s=n[3];if(void 0===s){const e=yt(i),t=`${Xe}${e}:${r}`;try{Je(t)}catch(e){if(e instanceof We)throw new lt("bad_network",e.message);throw e}return{kind:"network",ownerDid:e,network:r,networkId:t}}if(!st.test(r))throw new lt("bad_network",`network ${JSON.stringify(r)} must match ${st.source}`);pt(i);const o=`${Xe}${i}:${r}`;if(s.endsWith("/")){const e=s.slice(0,-1);return ht(e,"prefix"),{kind:"prefix",ownerDid:i,network:r,networkId:o,prefix:e}}return ht(s,"key path"),{kind:"key",ownerDid:i,network:r,networkId:o,path:s}}function wt(e){let t="";for(const n of e){const e=n.codePointAt(0);t+=e>=32&&e<=126?n:`\\u{${e.toString(16).toUpperCase().padStart(4,"0")}}`}return t}function kt(e){const t="string"==typeof e?e:String(e),n=Array.from(t);return wt(n.length>120?`${n.slice(0,120).join("")}...`:t)}var vt=class extends Error{constructor(e,t,n={}){super(wt(t),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=e,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},gt=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),mt=Object.assign(Object.create(null),{key_deleted:!0}),bt=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function It(e,t,n){const i=bt.exec(t.trim()),r=i?.[1]?.slice(0,64),s=i?.[2]?.trim(),o={status:e,...void 0===r?{}:{nodeCode:r},...void 0===s||0===s.length?{}:{detail:s}};if(void 0!==r){const e=gt[r];if(void 0!==e)return new vt(e,`${n}: ${r}`,o);if(!0===mt[r])return new vt("KEY_UNAVAILABLE",`${n}: key unavailable (${r})`,{...o,rawState:r})}return new vt("NODE_ERROR",`${n}: node responded ${e}`,o)}function Et(e){let t;try{t=ft(e)}catch(t){throw new vt("INVALID_KEY_TARGET",`not a valid encryption key resource: ${kt(t instanceof Error?t.message:t)}`,{cause:t,input:e})}if("key"!==t.kind)throw new vt("INVALID_KEY_TARGET",`a ${t.kind} resource cannot be an invocation target; an exact key is required`,{input:e});return t}function Nt(e){const t=Et(e.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path,action:e.action,bodyHash:Fe(e.crypto.sha256,e.body)}}function St(e){const t=Et(e.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path}}var $t={[et]:!0,[at]:!0,[dt]:!0,[ut]:!0};function _t(e){return new vt("INVALID_RESPONSE",`node returned an invalid ${e}`)}function At(e,t,n){const i="object"==typeof e&&null!==e?e:{};if("string"!=typeof i.alg||"number"!=typeof i.keyVersion||!Number.isInteger(i.keyVersion)||"string"!=typeof i.publicEncryptionKey||0===i.publicEncryptionKey.length)throw _t("key descriptor");if(i.networkId!==t||i.keyPath!==n)throw new vt("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:t,keyPath:n,alg:i.alg,keyVersion:i.keyVersion,publicEncryptionKey:i.publicEncryptionKey}}function Ot(e,t,n){const i=At(e,t,n),r=e;if("string"!=typeof r.state||"string"!=typeof r.kind)throw _t("key descriptor (state/kind missing)");return{...i,state:r.state,kind:r.kind,..."string"==typeof r.createdAt?{createdAt:r.createdAt}:{},..."string"==typeof r.updatedAt?{updatedAt:r.updatedAt}:{}}}function Pt(e){return e.startsWith("apps/")}var xt=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],Tt=class{constructor(e){this.config=e}networkFor(e){return e?.networkId??this.config.defaultNetworkId()}keyUrn(e,t){try{return function(e,t){const n=function(e){let t;try{t=Je(e)}catch(e){if(e instanceof We)throw new lt("bad_network",e.message);throw e}return pt(t.ownerDid),t.networkId}(e);ht(t,"key path");const i=`${n}/${t}`;return function(e,t){if(ft(e).networkId!==t)throw new lt("malformed",`built resource does not round-trip (got ${JSON.stringify(e)})`)}(i,n),i}(e,t)}catch(n){throw new vt("INVALID_KEY_TARGET",kt(n instanceof Error?n.message:n),{cause:n,input:`${e}/${t}`})}}requireNode(){if(void 0===this.nodeId){const e=this.readNodeInfo();this.nodeId=e,e.catch(()=>{this.nodeId===e&&(this.nodeId=void 0)})}return this.nodeId}refreshNodeInfo(){this.nodeId=void 0}async readNodeInfo(){const e=await this.config.fetch(`${this.config.host}/info`);if(!e.ok)throw It(e.status,await Dt(e),"failed to read node info");const t=await e.json();if(!function(e){const t=e?.features;return Array.isArray(t)&&t.includes("encryption-named-keys-v1")}(t))throw new vt("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof t.nodeId||0===t.nodeId.length)throw _t("/info response (nodeId missing)");return t.nodeId}keysUrl(e,t){return`${this.config.host}/encryption/networks/${e}/keys/${t}`}async getPublicKey(e,t){const n=this.networkFor(t);this.keyUrn(n,e),await this.requireNode();const i=await this.config.fetch(this.keysUrl(n,e),{method:"GET"});if(!i.ok)throw It(i.status,await Dt(i),"failed to read key");return At(await i.json(),n,e)}async describeKey(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);return null===i?null:Ot(i,n,e)}async describePublic(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);if(null===i)throw new vt("KEY_NOT_FOUND",`key ${kt(e)} does not exist`,{status:404});return At(i,n,e)}async describeBody(e,t){const n=this.networkFor(t),i=this.keyUrn(n,e),r=t?.ability??et;if(!0!==$t[r])throw new vt("INVALID_KEY_TARGET",`${kt(r)} cannot describe a key`,{input:r});const s=await this.requireNode(),o=await this.config.signInvocation({targetNode:s,resource:i,action:r,facts:St({targetNode:s,keyResource:i})}),c=await this.config.fetch(this.keysUrl(n,e),{method:"GET",headers:{Authorization:o.authorization}});if(404===c.status){const e=It(404,await Dt(c),"failed to describe key");if("KEY_NOT_FOUND"===e.code)return null;throw e}if(!c.ok)throw It(c.status,await Dt(c),"failed to describe key");return c.json()}async admin(e,t,n,i){const r=this.networkFor(i),s=this.keyUrn(r,n),o="keys"===e?{keyPath:n,deletable:Pt(n)}:{keyPath:n},c=await this.requireNode(),a=await this.config.signInvocation({targetNode:c,resource:s,action:t,facts:Nt({crypto:this.config.crypto,targetNode:c,keyResource:s,action:t,body:o})}),d=await this.config.fetch(`${this.config.host}/encryption/networks/${r}/${e}`,{method:"POST",headers:{Authorization:a.authorization,"Content-Type":"application/json"},body:Me(o)});if(!d.ok)throw It(d.status,await Dt(d),`failed to ${t}`);return Ot(function(e){const t="object"==typeof e&&null!==e?e:{};return"object"==typeof t.descriptor&&null!==t.descriptor?t.descriptor:e}(await d.json()),r,n)}createKey(e,t){return this.admin("keys",at,e,t)}blockKey(e,t){return this.admin("key-actions/block",dt,e,t)}unblockKey(e,t){return this.admin("key-actions/unblock",ut,e,t)}async ensureKey(e,t){const n=()=>this.describeKey(e,{...t,ability:at});let i=await n();if(null===i)try{i=await this.createKey(e,t)}catch(t){if(!(t instanceof vt)||"KEY_EXISTS"!==t.code)throw t;if(i=await n(),null===i)throw new vt("KEY_NOT_FOUND",`key ${kt(e)} reported as existing but could not be read back`)}return function(e,t){if("blocked"===e.state)throw new vt("KEY_BLOCKED",`key ${kt(e.keyPath)} is blocked`,{rawState:e.state});if("active"!==e.state)throw new vt("KEY_UNAVAILABLE",`key ${kt(e.keyPath)} is unavailable (state ${kt(e.state)})`,{rawState:e.state});if(e.kind!==t)throw new vt("KEY_KIND_MISMATCH",`key ${kt(e.keyPath)} exists with kind ${kt(e.kind)}, not ${t}`,{kind:e.kind});return e}(i,Pt(e)?"deletable":"deterministic")}async encrypt(e,t,n){const i=Pt(e)?await this.describePublic(e,n):await this.getPublicKey(e,n),{crypto:r}=this.config,s=r.randomBytes(32),o=r.authEncrypt(s,t,n?.aad),c=Be(r.sealToNetworkKey(je(i.publicEncryptionKey),s));return{v:2,networkId:i.networkId,keyPath:i.keyPath,alg:i.alg??"x25519-aes256gcm/v1",keyVersion:i.keyVersion,encryptedSymmetricKey:c,encryptedSymmetricKeyHash:Fe(r.sha256,c),ciphertext:Be(o),...void 0!==n?.aad?{aad:Be(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(e){const t="object"==typeof e&&null!==e?e:{};if(1===t.v&&void 0===t.keyPath)return this.decryptRoot(t);if(2===t.v&&"string"==typeof t.keyPath)return this.decryptKey(this.validateKeyEnvelope(t));throw new vt("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(e){const t=[];for(const n of e)try{t.push({ok:!0,data:await this.decrypt(n)})}catch(e){t.push({ok:!1,error:e instanceof vt?e:new vt("DECRYPT_FAILED","decrypt failed",{cause:e})})}return t}async decryptRoot(e){if(void 0===this.config.decryptRoot)throw new vt("DECRYPT_FAILED","no root-key decrypt path is configured");const t=await this.config.decryptRoot(e);if(!t.ok)throw new vt("DECRYPT_FAILED",kt(t.error.message),{cause:t.error});return t.data}validateKeyEnvelope(e){for(const t of xt)if("string"!=typeof e[t]||0===e[t].length)throw new vt("INVALID_ENVELOPE",`envelope.${t} must be a non-empty string`);if("number"!=typeof e.keyVersion||!Number.isInteger(e.keyVersion))throw new vt("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof e.networkId)throw new vt("INVALID_ENVELOPE","envelope.networkId must be a string");try{Je(e.networkId)}catch(e){throw new vt("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:e})}if(Fe(this.config.crypto.sha256,e.encryptedSymmetricKey)!==e.encryptedSymmetricKeyHash)throw new vt("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");return e}async decryptKey(e){const{crypto:t}=this.config,n=this.keyUrn(e.networkId,e.keyPath),i=await this.requireNode(),r=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:t}),s=Be(r.publicKey),o=Fe(t.sha256,s),c={type:Ze,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:o},a=Me(c),d={type:Ze,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,bodyHash:Fe(t.sha256,c),encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:o,alg:e.alg,keyVersion:e.keyVersion},u=await this.config.signInvocation({targetNode:i,resource:n,action:et,facts:d}),l=await this.config.fetch(`${this.config.host}/invoke`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:a});if(!l.ok)throw It(l.status,await Dt(l),"failed to decrypt");const y=function(e){const{crypto:t,request:n,facts:i,invocationCid:r,requestBodyHash:s,response:o}=e;if(o.type!==Qe)return{ok:!1,error:nt({code:"INVALID_RESPONSE",message:`response.type must be ${Qe}`})};if(o.targetNode!==n.targetNode)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(o.networkId!==n.networkId)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(o.nodeId!==n.targetNode)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(o.alg!==n.alg)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(o.keyVersion!==n.keyVersion)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(o.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(o.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(o.invocationCid!==r)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=He(t.sha256(qe(`${r}${s}`)));if(o.requestHash!==c)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(i.encryptedSymmetricKeyHash!==o.encryptedSymmetricKeyHash||i.receiverPublicKeyHash!==o.receiverPublicKeyHash||i.networkId!==o.networkId||i.targetNode!==o.targetNode||i.alg!==o.alg||i.keyVersion!==o.keyVersion)return{ok:!1,error:nt({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(e){const{nodeSignature:t,...n}=e;return Me(n)}(o)),d=je(o.nodeSignature);return t.verifyNodeSignature(o.nodeId,a,d)?{ok:!0,data:o}:{ok:!1,error:nt({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:t,request:c,facts:d,invocationCid:u.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!y.ok)throw new vt("INVALID_RESPONSE",kt(y.error.message),{cause:y.error});const p=function(e,t,n){const i=je(n.wrappedKey);return e.openWithReceiverKey(t,i)}(t,r.privateKey,y.data);try{return t.authDecrypt(p,je(e.ciphertext),void 0!==e.aad?je(e.aad):void 0)}catch(e){throw new vt("DECRYPT_FAILED","local decryption failed",{cause:e})}}};async function Dt(e){try{return await e.text()}catch{return""}}function Kt(e,t={}){const n=e;for(const e of["signRawNetworkAuthorization","createEncryptionCrypto"])if("function"!=typeof n[e])throw new vt("NODE_HOOK_MISSING",`TinyCloudNode.${e} is not available; named keys cannot sign invocations`);const i=n,r=e.hosts[0];if(void 0===r)throw new Error("TinyCloud node host has not been resolved");const s={host:r,crypto:i.createEncryptionCrypto(),fetch:t.fetch??globalThis.fetch.bind(globalThis),defaultNetworkId:()=>t.networkId??e.getDefaultEncryptionNetworkId(),signInvocation:e=>i.signRawNetworkAuthorization({targetNode:e.targetNode,networkId:e.resource,action:e.action,facts:e.facts}),decryptRoot:t=>{const n=e.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):e.encryption.decryptEnvelope(t,{proofs:[n]})}};return new Tt(s)}module.exports=t})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! For license information please see encryption-keys.mjs.LICENSE.txt */
|
|
2
|
+
class e extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const t="2.45.1";let n=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,i=`viem@${t}`;class r extends Error{constructor(e,s={}){const o=s.cause instanceof r?s.cause.details:s.cause?.message?s.cause.message:s.details,c=s.cause instanceof r&&s.cause.docsPath||s.docsPath,a=n?.({...s,docsPath:c});super([e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...o?[`Details: ${o}`]:[],...i?[`Version: ${i}`]:[]].join("\n"),s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=o,this.docsPath=c,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=t}walk(e){return s(this,e)}}function s(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?s(e.cause,t):t?null:e}class o extends r{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function c(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}class a extends r{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function d(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const i=e.replace("0x","");if(i.length>2*n)throw new a({size:Math.ceil(i.length/2),targetSize:n,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new a({size:e.length,targetSize:n,type:"bytes"});const i=new Uint8Array(n);for(let r=0;r<n;r++){const s="right"===t;i[s?r:n-r-1]=e[s?r:e.length-r-1]}return i}(e,{dir:t,size:n})}class u extends r{constructor({max:e,min:t,signed:n,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class l extends r{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function y(e){return c(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function p(e,{size:t}){if(y(e)>t)throw new l({givenSize:y(e),maxSize:t})}function h(e,t={}){const{signed:n,size:i}=t,r=BigInt(e);let s;i?s=n?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&r>s||r<o){const t="bigint"==typeof e?"n":"";throw new u({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:i,value:`${e}${t}`})}const c=`0x${(n&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?d(c,{size:i}):c}const f=new TextEncoder;const w={zero:48,nine:57,A:65,F:70,a:97,f:102};function k(e){return e>=w.zero&&e<=w.nine?e-w.zero:e>=w.A&&e<=w.F?e-(w.A-10):e>=w.a&&e<=w.f?e-(w.a-10):void 0}function v(e,t={}){let n=e;t.size&&(p(n,{size:t.size}),n=d(n,{dir:"right",size:t.size}));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let e=0,t=0;e<s;e++){const n=k(i.charCodeAt(t++)),s=k(i.charCodeAt(t++));if(void 0===n||void 0===s)throw new r(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=16*n+s}return o}function g(e,t={}){const n=f.encode(e);return"number"==typeof t.size?(p(n,{size:t.size}),d(n,{dir:"right",size:t.size})):n}const m=BigInt(2**32-1),b=BigInt(32);function I(e,t=!1){return t?{h:Number(e&m),l:Number(e>>b&m)}:{h:0|Number(e>>b&m),l:0|Number(e&m)}}function E(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function N(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function S(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function $(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const A=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=_(e[t]);return e};function O(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),N(e),e}class P{}const x=BigInt(0),T=BigInt(1),D=BigInt(2),K=BigInt(7),z=BigInt(256),R=BigInt(113),L=[],C=[],V=[];for(let e=0,t=T,n=1,i=0;e<24;e++){[n,i]=[i,(2*n+3*i)%5],L.push(2*(5*i+n)),C.push((e+1)*(e+2)/2%64);let r=x;for(let e=0;e<7;e++)t=(t<<T^(t>>K)*R)%z,t&D&&(r^=T<<(T<<BigInt(e))-T);V.push(r)}const M=function(e,t=!1){const n=e.length;let i=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=I(e[s],t);[i[s],r[s]]=[n,o]}return[i,r]}(V,!0),U=M[0],H=M[1],B=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),q=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class j extends P{constructor(e,t,n,i=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=r,E(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}clone(){return this._cloneInto()}keccak(){A(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,s=n[r],o=n[r+1],c=B(s,o,1)^n[i],a=q(s,o,1)^n[i+1];for(let n=0;n<50;n+=10)e[t+n]^=c,e[t+n+1]^=a}let t=e[2],r=e[3];for(let n=0;n<24;n++){const i=C[n],s=B(t,r,i),o=q(t,r,i),c=L[n];t=e[c],r=e[c+1],e[c]=s,e[c+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)n[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~n[(i+2)%10]&n[(i+4)%10]}e[0]^=U[i],e[1]^=H[i]}$(n)}(this.state32,this.rounds),A(this.state32),this.posOut=0,this.pos=0}update(e){S(this),N(e=O(e));const{blockLen:t,state:n}=this,i=e.length;for(let r=0;r<i;){const s=Math.min(t-this.pos,i-r);for(let t=0;t<s;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,128&t&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){S(this,!1),N(e),this.finish();const t=this.state,{blockLen:n}=this;for(let i=0,r=e.length;i<r;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return E(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){N(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,$(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:i,rounds:r,enableXOF:s}=this;return e||(e=new j(t,n,i,s,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}}const F=(e,t,n)=>function(e){const t=t=>e().update(O(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new j(t,e,n)),G=(()=>F(1,136,32))(),Y=new e(8192);function W(e,t){if(Y.has(`${e}.${t}`))return Y.get(`${e}.${t}`);const n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),i=function(e){const t=G(c(e,{strict:!1})?function(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){return v(h(e,t))}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(p(n,{size:t.size}),d(n,{size:t.size})):n}(e,t):c(e)?v(e,t):g(e,t)}(e):e);return t}(g(n)),r=(t?n.substring(`${t}0x`.length):n).split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&i[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());const s=`0x${r.join("")}`;return Y.set(`${e}.${t}`,s),s}const J=/^0x[a-fA-F0-9]{40}$/,X=new e(8192);function Z(e,t){const{strict:n=!0}=t??{},i=`${e}.${n}`;if(X.has(i))return X.get(i);const r=!(!J.test(e)||e.toLowerCase()!==e&&n&&W(e)!==e);return X.set(i,r),r}var Q=[{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 ee(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function te(e){return e.slice(10,e.indexOf("/"))}function ne(e){return e.slice(e.indexOf("/")+1)}function ie(e){const t={};for(const n of Q)te(n.urn)===e&&(t[ee(ne(n.urn))]=n.urn);return t}var re=ie("kv"),se={...ie("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},oe=(ie("duckdb"),ie("capabilities")),ce=(ie("hooks"),ie("encryption")),ae=ie("space"),de="applications",ue="account",le="applications/",ye="secrets",pe="default",he="public",fe="agents",we="tinycloud.encryption",ke=ce.NETWORK_CREATE,ve=[pe,de,ue,ye,he,fe],ge={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:pe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:pe,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:pe,path:"",actions:["read","write"]}]},me={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:de,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:de,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:de,path:"",actions:["read","write"]}]},be={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ue,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ue,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ue,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ue,path:"account",actions:["read","write","schema"]}]},Ie={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:ye,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:ye,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:ye,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:ye,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:ye,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:ye,path:"",actions:["read"],skipPrefix:!0}]},Ee={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:he,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:he,path:"",actions:["get","list","metadata"]}]},Ne={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:fe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:fe,path:"",actions:["get","put","del","list","metadata"]}]},Se={[pe]:ge,[de]:me,[ue]:be,[ye]:Ie,[he]:Ee,[fe]:Ne};function $e(e,t=1){return function(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`Invalid EIP-155 chain ID: ${e}`)}(t),`did:pkh:eip155:${t}:${function(e){if(!Z(e,{strict:!1}))throw new Error(`Invalid EVM address: ${e}`);return function(e){if(!Z(e,{strict:!1}))throw new o({address:e});return W(e,void 0)}(e)}(e)}`}function _e(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Ae(e,t,n){return!0===n||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function Oe(e,t,n){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const n=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,i="read"===n||"get"===n?re.GET:"write"===n||"put"===n?re.PUT:"delete"===n||"del"===n?re.DEL:"list"===n?re.LIST:"metadata"===n?re.METADATA:void 0;if(void 0===i)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const r=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${r}`,actions:[i],skipPrefix:!0}})}(e).flatMap(e=>Oe(e,t,n));const i=!0===e.skipPrefix||e.service===we;return[{service:e.service,space:e.service===we?"encryption":e.space??n,path:Ae(t,e.path,i),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 Pe(e){const t=new Set(e.filter(e=>e.service!==we).map(e=>e.space));return function(e){const t=new Map;for(const n of e){const e=`${n.service}\0${n.space}\0${n.path}`,i=t.get(e);if(i)for(const e of n.actions)i.actions.includes(e)||i.actions.push(e);else t.set(e,{...n,actions:[...n.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[oe.READ]}))])}function xe(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const n=t.includeAccountRegistryPermissions??!0,i=e.map(_e),r=i.flatMap(e=>{const t=e.prefix??e.app_id,n=e.space??de;return(e.permissions??[]).flatMap(e=>Oe(e,t,n))});n&&r.push(...Te.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of i){const t=s.get(e.app_id)??[];t.push(_e(e)),s.set(e.app_id,t)}return{manifests:i,resources:Pe(r),delegationTargets:[],registryRecords:n?[...s.entries()].map(([e,t])=>({key:`${le}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:i.some(e=>e.includePublicSpace??!0)}}([Se[e]],{includeAccountRegistryPermissions:!1})}ve.map(e=>({name:e,manifest:Se[e],persistedAsApplication:e===ye}));var Te=Object.freeze([{service:"tinycloud.kv",space:ue,path:le,actions:[re.GET,re.PUT,re.LIST]},{service:"tinycloud.kv",space:ue,path:"spaces/",actions:[re.GET,re.PUT,re.LIST]},{service:"tinycloud.kv",space:ue,path:"system/bootstrap/complete",actions:[re.GET,re.PUT]},{service:"tinycloud.delegation",space:ue,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ue,path:"account",actions:[se.READ,se.WRITE,se.SCHEMA]},{service:"tinycloud.capabilities",space:ue,path:"",actions:[oe.READ]}]),De=xe(pe),Ke={...De,resources:[...De.resources,...Te.map(e=>({...e,actions:[...e.actions]}))]},ze=Object.freeze(Object.fromEntries(ve.map(e=>[e,e===pe?Ke:xe(e)]))),Re=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ke]}]);function Le(e){return void 0===e?"":Ce(e)}function Ce(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(Ce).join(",")}]`;const t=Object.keys(e).sort(),n=[];for(const i of t){const t=e[i];void 0!==t&&n.push(`${JSON.stringify(i)}:${Ce(t)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}Object.freeze(ve.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:ze[e].resources,...e===ue?{rawAbilities:Re}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[ae.HOST]}]));var Ve="0123456789abcdef";function Me(e){let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=Ve[i>>4&15]+Ve[15&i]}return t}function Ue(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let i=0;i<e.length;i+=3){const r=e[i],s=i+1<e.length?e[i+1]:0,o=i+2<e.length?e[i+2]:0;n+=t[r>>2&63],n+=t[63&(r<<4|s>>4)],n+=i+1<e.length?t[63&(s<<2|o>>6)]:"=",n+=i+2<e.length?t[63&o]:"="}return n}function He(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),n=t.length;if(n%4!=0)throw new Error("invalid base64 input");const i=n/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),r=new Uint8Array(i),s={};for(let e=0;e<64;e++)s["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let o=0;for(let e=0;e<n;e+=4){const n=s[t[e]]??0,c=s[t[e+1]]??0,a="="===t[e+2]?0:s[t[e+2]]??0,d=n<<2|c>>4,u=(15&c)<<4|a>>2,l=(3&a)<<6|("="===t[e+3]?0:s[t[e+3]]??0);o<i&&(r[o++]=d),o<i&&(r[o++]=u),o<i&&(r[o++]=l)}return r}function Be(e){return(new TextEncoder).encode(e)}function qe(e,t){return Me(e(Be(Le(t))))}var je="urn:tinycloud:encryption:",Fe=/^[a-z0-9][a-z0-9-]*$/,Ge=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Ye(e){if("string"!=typeof e||0===e.length)throw new Ge("networkId must be a non-empty string");if(!e.startsWith(je))throw new Ge(`networkId must start with ${je} (got ${JSON.stringify(e)})`);const t=e.slice(25),n=t.lastIndexOf(":");if(n<=0||n===t.length-1)throw new Ge(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const i=t.slice(0,n),r=t.slice(n+1);if(!i.startsWith("did:"))throw new Ge(`networkId ownerDid must be a DID (got ${JSON.stringify(i)})`);const s=i.split(":");if(s.length<3||s.some(e=>0===e.length))throw new Ge(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(i)})`);if(!Fe.test(r))throw new Ge(`networkId name ${JSON.stringify(r)} must match ${Fe.source}`);return{networkId:e,ownerDid:i,name:r}}var We=je,Je="tinycloud.encryption.decrypt/v1",Xe="tinycloud.encryption.decrypt-result/v1",Ze="tinycloud.encryption/decrypt";function Qe(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}}function et(e){return{...e,service:"encryption",message:Qe(e)}}var tt="[a-z0-9][a-z0-9._-]{0,63}",nt=new RegExp(`^${tt}(?:/${tt}){0,7}$`),it=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,rt=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,st="did:pkh:eip155:",ot="tinycloud.encryption/key.create",ct="tinycloud.encryption/key.block",at="tinycloud.encryption/key.unblock",dt=(Object.freeze([Ze,ot,ct,at]),class extends Error{constructor(e,t){super(t),this.name="EncryptionResourceError",this.code=e}});function ut(e){if(!e.startsWith(st))return e;const t=e.slice(15),n=t.indexOf(":"),i=-1===n?"":t.slice(0,n),r=-1===n?"":t.slice(n+1);if(!/^\d+$/.test(i)||!/^0x[a-fA-F0-9]{40}$/.test(r))throw new dt("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(e)})`);const s=BigInt(i);if(0n===s||s>18446744073709551615n)throw new dt("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(i)})`);const o=$e(r,1).slice(17);return`${st}${s}:${o}`}function lt(e){const t=ut(e);if(t!==e)throw new dt("non_canonical_owner",`owner DID is not canonical (expected ${t})`)}function yt(e,t){if(0===e.length)throw new dt("empty_path",`${t} must not be empty`);if((new TextEncoder).encode(e).length>255)throw new dt("path_too_long",`${t} exceeds 255 bytes`);if(!nt.test(e))throw new dt("bad_path",`${t} ${JSON.stringify(e)} must match ${nt.source}`);const n=e.split("/");if("apps"===n[0]&&n.length<("key path"===t?3:2))throw new dt("bad_path",`${t} ${JSON.stringify(e)} under apps/ needs ${"key path"===t?"apps/<id>/<name>":"apps/<id>/"}`)}function pt(e){if("string"!=typeof e||!e.startsWith(We))throw new dt("not_encryption_urn",`resource must start with ${We}`);const t=e.slice(25),n=rt.exec(t);if(null===n)throw new dt("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(e)})`);const i=n[1],r=n[2],s=n[3];if(void 0===s){const e=ut(i),t=`${We}${e}:${r}`;try{Ye(t)}catch(e){if(e instanceof Ge)throw new dt("bad_network",e.message);throw e}return{kind:"network",ownerDid:e,network:r,networkId:t}}if(!it.test(r))throw new dt("bad_network",`network ${JSON.stringify(r)} must match ${it.source}`);lt(i);const o=`${We}${i}:${r}`;if(s.endsWith("/")){const e=s.slice(0,-1);return yt(e,"prefix"),{kind:"prefix",ownerDid:i,network:r,networkId:o,prefix:e}}return yt(s,"key path"),{kind:"key",ownerDid:i,network:r,networkId:o,path:s}}function ht(e){let t="";for(const n of e){const e=n.codePointAt(0);t+=e>=32&&e<=126?n:`\\u{${e.toString(16).toUpperCase().padStart(4,"0")}}`}return t}function ft(e){const t="string"==typeof e?e:String(e),n=Array.from(t);return ht(n.length>120?`${n.slice(0,120).join("")}...`:t)}var wt=class extends Error{constructor(e,t,n={}){super(ht(t),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=e,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},kt=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),vt=Object.assign(Object.create(null),{key_deleted:!0}),gt=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function mt(e,t,n){const i=gt.exec(t.trim()),r=i?.[1]?.slice(0,64),s=i?.[2]?.trim(),o={status:e,...void 0===r?{}:{nodeCode:r},...void 0===s||0===s.length?{}:{detail:s}};if(void 0!==r){const e=kt[r];if(void 0!==e)return new wt(e,`${n}: ${r}`,o);if(!0===vt[r])return new wt("KEY_UNAVAILABLE",`${n}: key unavailable (${r})`,{...o,rawState:r})}return new wt("NODE_ERROR",`${n}: node responded ${e}`,o)}function bt(e){let t;try{t=pt(e)}catch(t){throw new wt("INVALID_KEY_TARGET",`not a valid encryption key resource: ${ft(t instanceof Error?t.message:t)}`,{cause:t,input:e})}if("key"!==t.kind)throw new wt("INVALID_KEY_TARGET",`a ${t.kind} resource cannot be an invocation target; an exact key is required`,{input:e});return t}function It(e){const t=bt(e.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path,action:e.action,bodyHash:qe(e.crypto.sha256,e.body)}}function Et(e){const t=bt(e.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path}}var Nt={[Ze]:!0,[ot]:!0,[ct]:!0,[at]:!0};function St(e){return new wt("INVALID_RESPONSE",`node returned an invalid ${e}`)}function $t(e,t,n){const i="object"==typeof e&&null!==e?e:{};if("string"!=typeof i.alg||"number"!=typeof i.keyVersion||!Number.isInteger(i.keyVersion)||"string"!=typeof i.publicEncryptionKey||0===i.publicEncryptionKey.length)throw St("key descriptor");if(i.networkId!==t||i.keyPath!==n)throw new wt("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:t,keyPath:n,alg:i.alg,keyVersion:i.keyVersion,publicEncryptionKey:i.publicEncryptionKey}}function _t(e,t,n){const i=$t(e,t,n),r=e;if("string"!=typeof r.state||"string"!=typeof r.kind)throw St("key descriptor (state/kind missing)");return{...i,state:r.state,kind:r.kind,..."string"==typeof r.createdAt?{createdAt:r.createdAt}:{},..."string"==typeof r.updatedAt?{updatedAt:r.updatedAt}:{}}}function At(e){return e.startsWith("apps/")}var Ot=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],Pt=class{constructor(e){this.config=e}networkFor(e){return e?.networkId??this.config.defaultNetworkId()}keyUrn(e,t){try{return function(e,t){const n=function(e){let t;try{t=Ye(e)}catch(e){if(e instanceof Ge)throw new dt("bad_network",e.message);throw e}return lt(t.ownerDid),t.networkId}(e);yt(t,"key path");const i=`${n}/${t}`;return function(e,t){if(pt(e).networkId!==t)throw new dt("malformed",`built resource does not round-trip (got ${JSON.stringify(e)})`)}(i,n),i}(e,t)}catch(n){throw new wt("INVALID_KEY_TARGET",ft(n instanceof Error?n.message:n),{cause:n,input:`${e}/${t}`})}}requireNode(){if(void 0===this.nodeId){const e=this.readNodeInfo();this.nodeId=e,e.catch(()=>{this.nodeId===e&&(this.nodeId=void 0)})}return this.nodeId}refreshNodeInfo(){this.nodeId=void 0}async readNodeInfo(){const e=await this.config.fetch(`${this.config.host}/info`);if(!e.ok)throw mt(e.status,await xt(e),"failed to read node info");const t=await e.json();if(!function(e){const t=e?.features;return Array.isArray(t)&&t.includes("encryption-named-keys-v1")}(t))throw new wt("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof t.nodeId||0===t.nodeId.length)throw St("/info response (nodeId missing)");return t.nodeId}keysUrl(e,t){return`${this.config.host}/encryption/networks/${e}/keys/${t}`}async getPublicKey(e,t){const n=this.networkFor(t);this.keyUrn(n,e),await this.requireNode();const i=await this.config.fetch(this.keysUrl(n,e),{method:"GET"});if(!i.ok)throw mt(i.status,await xt(i),"failed to read key");return $t(await i.json(),n,e)}async describeKey(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);return null===i?null:_t(i,n,e)}async describePublic(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);if(null===i)throw new wt("KEY_NOT_FOUND",`key ${ft(e)} does not exist`,{status:404});return $t(i,n,e)}async describeBody(e,t){const n=this.networkFor(t),i=this.keyUrn(n,e),r=t?.ability??Ze;if(!0!==Nt[r])throw new wt("INVALID_KEY_TARGET",`${ft(r)} cannot describe a key`,{input:r});const s=await this.requireNode(),o=await this.config.signInvocation({targetNode:s,resource:i,action:r,facts:Et({targetNode:s,keyResource:i})}),c=await this.config.fetch(this.keysUrl(n,e),{method:"GET",headers:{Authorization:o.authorization}});if(404===c.status){const e=mt(404,await xt(c),"failed to describe key");if("KEY_NOT_FOUND"===e.code)return null;throw e}if(!c.ok)throw mt(c.status,await xt(c),"failed to describe key");return c.json()}async admin(e,t,n,i){const r=this.networkFor(i),s=this.keyUrn(r,n),o="keys"===e?{keyPath:n,deletable:At(n)}:{keyPath:n},c=await this.requireNode(),a=await this.config.signInvocation({targetNode:c,resource:s,action:t,facts:It({crypto:this.config.crypto,targetNode:c,keyResource:s,action:t,body:o})}),d=await this.config.fetch(`${this.config.host}/encryption/networks/${r}/${e}`,{method:"POST",headers:{Authorization:a.authorization,"Content-Type":"application/json"},body:Le(o)});if(!d.ok)throw mt(d.status,await xt(d),`failed to ${t}`);return _t(function(e){const t="object"==typeof e&&null!==e?e:{};return"object"==typeof t.descriptor&&null!==t.descriptor?t.descriptor:e}(await d.json()),r,n)}createKey(e,t){return this.admin("keys",ot,e,t)}blockKey(e,t){return this.admin("key-actions/block",ct,e,t)}unblockKey(e,t){return this.admin("key-actions/unblock",at,e,t)}async ensureKey(e,t){const n=()=>this.describeKey(e,{...t,ability:ot});let i=await n();if(null===i)try{i=await this.createKey(e,t)}catch(t){if(!(t instanceof wt)||"KEY_EXISTS"!==t.code)throw t;if(i=await n(),null===i)throw new wt("KEY_NOT_FOUND",`key ${ft(e)} reported as existing but could not be read back`)}return function(e,t){if("blocked"===e.state)throw new wt("KEY_BLOCKED",`key ${ft(e.keyPath)} is blocked`,{rawState:e.state});if("active"!==e.state)throw new wt("KEY_UNAVAILABLE",`key ${ft(e.keyPath)} is unavailable (state ${ft(e.state)})`,{rawState:e.state});if(e.kind!==t)throw new wt("KEY_KIND_MISMATCH",`key ${ft(e.keyPath)} exists with kind ${ft(e.kind)}, not ${t}`,{kind:e.kind});return e}(i,At(e)?"deletable":"deterministic")}async encrypt(e,t,n){const i=At(e)?await this.describePublic(e,n):await this.getPublicKey(e,n),{crypto:r}=this.config,s=r.randomBytes(32),o=r.authEncrypt(s,t,n?.aad),c=Ue(r.sealToNetworkKey(He(i.publicEncryptionKey),s));return{v:2,networkId:i.networkId,keyPath:i.keyPath,alg:i.alg??"x25519-aes256gcm/v1",keyVersion:i.keyVersion,encryptedSymmetricKey:c,encryptedSymmetricKeyHash:qe(r.sha256,c),ciphertext:Ue(o),...void 0!==n?.aad?{aad:Ue(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(e){const t="object"==typeof e&&null!==e?e:{};if(1===t.v&&void 0===t.keyPath)return this.decryptRoot(t);if(2===t.v&&"string"==typeof t.keyPath)return this.decryptKey(this.validateKeyEnvelope(t));throw new wt("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(e){const t=[];for(const n of e)try{t.push({ok:!0,data:await this.decrypt(n)})}catch(e){t.push({ok:!1,error:e instanceof wt?e:new wt("DECRYPT_FAILED","decrypt failed",{cause:e})})}return t}async decryptRoot(e){if(void 0===this.config.decryptRoot)throw new wt("DECRYPT_FAILED","no root-key decrypt path is configured");const t=await this.config.decryptRoot(e);if(!t.ok)throw new wt("DECRYPT_FAILED",ft(t.error.message),{cause:t.error});return t.data}validateKeyEnvelope(e){for(const t of Ot)if("string"!=typeof e[t]||0===e[t].length)throw new wt("INVALID_ENVELOPE",`envelope.${t} must be a non-empty string`);if("number"!=typeof e.keyVersion||!Number.isInteger(e.keyVersion))throw new wt("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof e.networkId)throw new wt("INVALID_ENVELOPE","envelope.networkId must be a string");try{Ye(e.networkId)}catch(e){throw new wt("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:e})}if(qe(this.config.crypto.sha256,e.encryptedSymmetricKey)!==e.encryptedSymmetricKeyHash)throw new wt("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");return e}async decryptKey(e){const{crypto:t}=this.config,n=this.keyUrn(e.networkId,e.keyPath),i=await this.requireNode(),r=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:t}),s=Ue(r.publicKey),o=qe(t.sha256,s),c={type:Je,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:o},a=Le(c),d={type:Je,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,bodyHash:qe(t.sha256,c),encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:o,alg:e.alg,keyVersion:e.keyVersion},u=await this.config.signInvocation({targetNode:i,resource:n,action:Ze,facts:d}),l=await this.config.fetch(`${this.config.host}/invoke`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:a});if(!l.ok)throw mt(l.status,await xt(l),"failed to decrypt");const y=function(e){const{crypto:t,request:n,facts:i,invocationCid:r,requestBodyHash:s,response:o}=e;if(o.type!==Xe)return{ok:!1,error:et({code:"INVALID_RESPONSE",message:`response.type must be ${Xe}`})};if(o.targetNode!==n.targetNode)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(o.networkId!==n.networkId)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(o.nodeId!==n.targetNode)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(o.alg!==n.alg)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(o.keyVersion!==n.keyVersion)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(o.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(o.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(o.invocationCid!==r)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=Me(t.sha256(Be(`${r}${s}`)));if(o.requestHash!==c)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(i.encryptedSymmetricKeyHash!==o.encryptedSymmetricKeyHash||i.receiverPublicKeyHash!==o.receiverPublicKeyHash||i.networkId!==o.networkId||i.targetNode!==o.targetNode||i.alg!==o.alg||i.keyVersion!==o.keyVersion)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(e){const{nodeSignature:t,...n}=e;return Le(n)}(o)),d=He(o.nodeSignature);return t.verifyNodeSignature(o.nodeId,a,d)?{ok:!0,data:o}:{ok:!1,error:et({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:t,request:c,facts:d,invocationCid:u.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!y.ok)throw new wt("INVALID_RESPONSE",ft(y.error.message),{cause:y.error});const p=function(e,t,n){const i=He(n.wrappedKey);return e.openWithReceiverKey(t,i)}(t,r.privateKey,y.data);try{return t.authDecrypt(p,He(e.ciphertext),void 0!==e.aad?He(e.aad):void 0)}catch(e){throw new wt("DECRYPT_FAILED","local decryption failed",{cause:e})}}};async function xt(e){try{return await e.text()}catch{return""}}function Tt(e,t={}){const n=e;for(const e of["signRawNetworkAuthorization","createEncryptionCrypto"])if("function"!=typeof n[e])throw new wt("NODE_HOOK_MISSING",`TinyCloudNode.${e} is not available; named keys cannot sign invocations`);const i=n,r=e.hosts[0];if(void 0===r)throw new Error("TinyCloud node host has not been resolved");const s={host:r,crypto:i.createEncryptionCrypto(),fetch:t.fetch??globalThis.fetch.bind(globalThis),defaultNetworkId:()=>t.networkId??e.getDefaultEncryptionNetworkId(),signInvocation:e=>i.signRawNetworkAuthorization({targetNode:e.targetNode,networkId:e.resource,action:e.action,facts:e.facts}),decryptRoot:t=>{const n=e.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):e.encryption.decryptEnvelope(t,{proofs:[n]})}};return new Pt(s)}export{Tt as createNamedKeyClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|