Keyborg/server/public/js/shared.bundle.js
2025-02-14 02:37:30 +03:00

2 lines
20 KiB
JavaScript

var R=class t{constructor(e){this._promise=e;this._promise=e}static fromPromise(e,r){let n=e.then(s=>new m(s)).catch(s=>new y(r(s)));return new t(n)}static fromSafePromise(e){let r=e.then(n=>new m(n));return new t(r)}static fromThrowable(e,r){return(...n)=>t.fromPromise(e(n),s=>r?r(s):s)}async unwrap(){let e=await this._promise;if(e.isErr())throw e.error;return e.value}async match(e,r){let n=await this._promise;return n.isErr()?r(n.error):e(n.value)}map(e){return new t(this._promise.then(r=>r.isErr()?new y(r.error):new m(e(r.value))))}mapAsync(e){return new t(this._promise.then(async r=>r.isErr()?x(r.error):new m(await e(r.value))))}mapErr(e){return new t(this._promise.then(r=>r.isErr()?new y(e(r.error)):new m(r.value)))}mapErrAsync(e){return new t(this._promise.then(async r=>r.isErr()?x(await e(r.error)):new m(r.value)))}andThen(e){return new t(this._promise.then(r=>r.isErr()?x(r.error):e(r.value).toAsync()))}andThenAsync(e){return new t(this._promise.then(r=>r.isErr()?x(r.error):e(r.value)))}nullableToOption(){return this.map(e=>e?f(e):v)}flatten(){return new t(this._promise.then(e=>e.flatten()))}flattenOption(e){return new t(this._promise.then(r=>r.flattenOption(e)))}flattenOptionOrDefault(e){return new t(this._promise.then(r=>r.flattenOptionOrDefault(e)))}matchOption(e,r){return new t(this._promise.then(n=>n.matchOption(e,r)))}matchOptionAndFlatten(e,r){return new t(this._promise.then(n=>n.matchOptionAndFlatten(e,r)))}then(e,r){return this._promise.then(e,r)}};function I(t){return new R(Promise.resolve(new m(t)))}function x(t){return new R(Promise.resolve(new y(t)))}var m=class t{constructor(e){this.value=e;this.value=e,Object.defineProperties(this,{tag:{writable:!1,enumerable:!1}})}tag="ok";isErr(){return!1}ifErr(e){return this}isErrOrNone(){return this.value instanceof T}isOk(){return!0}ifOk(e){return e(this.value),this}unwrap(){return this.value}unwrapOr(e){return this.value}unwrapOrElse(e){return this.value}unwrapErr(){return v}match(e,r){return e(this.value)}map(e){let r=e(this.value);return new t(r)}mapAsync(e){return R.fromSafePromise(e(this.value))}mapOption(e){return this.value instanceof T||this.value instanceof S?u(this.value.map(e)):u(f(e(this.value)))}andThen(e){return e(this.value)}andThenAsync(e){return e(this.value)}mapErr(e){return u(this.value)}mapErrAsync(e){return I(this.value)}flatten(){return ue(this)}flattenOption(e){return this.value instanceof T||this.value instanceof S?this.value.okOrElse(e):new t(this.value)}flattenOptionOr(e){return this.value instanceof T||this.value instanceof S?this.value.unwrapOr(e):new t(this.value)}matchOption(e,r){return this.value instanceof T||this.value instanceof S?u(this.value.match(e,r)):u(e(this.value))}toNullable(){return this.value}toAsync(){return I(this.value)}void(){return u()}toJSON(){return{tag:"ok",value:this.value}}},y=class t{constructor(e){this.error=e;this.error=e,Object.defineProperties(this,{tag:{writable:!1,configurable:!1,enumerable:!1}})}tag="err";isErr(){return!0}ifErr(e){return e(this.error),this}isOk(){return!1}ifOk(e){return this}isErrOrNone(){return!0}unwrap(){let e=`Tried to unwrap error: ${ae(this.error)}`;throw new Error(e)}unwrapOr(e){return e}unwrapOrElse(e){return e()}unwrapErr(){return f(this.error)}match(e,r){return r(this.error)}map(e){return new t(this.error)}mapAsync(e){return x(this.error)}mapErr(e){return new t(e(this.error))}mapErrAsync(e){return R.fromPromise(new Promise(()=>{throw""}),()=>e(this.error))}mapOption(e){return o(this.error)}andThen(e){return new t(this.error)}andThenAsync(e){return new t(this.error).toAsync()}flatten(){return ue(this)}flattenOption(e){return new t(this.error)}flattenOptionOr(e){return new t(this.error)}matchOption(e,r){return o(this.error)}toNullable(){return null}toAsync(){return x(this.error)}void(){return o(this.error)}toJSON(){return{tag:"err",error:this.error}}};function u(t){return new m(t)}function o(t){return new y(t)}function Be(t,e){return(...r)=>{try{let n=t(...r);return u(n)}catch(n){return o(e?e(n):n)}}}function ae(t){if(t instanceof Error)return t.message?t.message:"code"in t&&typeof t.code=="string"?t.code:"An unknown error occurred";if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"message"in t){let e=t;return typeof e.message=="string"?e.message:String(e.message)}return"An unknown error occurred"}function ue(t){let e=t;for(;e instanceof m&&(e.value instanceof m||e.value instanceof y);)e=e.value;return e}var O=class extends Error{constructor(e){super(`Failed to parse ${e} as result`)}};function De(t){let e;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){return o(new O(ae(n)))}else e=t;if(typeof e!="object"||e===null)return o(new O("Expected an object but received type ${typeof data}."));let r=e;if("tag"in r)switch(r.tag){case"ok":{if("value"in r)return u(r.value);break}case"err":{if("error"in r)return o(r.error);break}}return o(new O("Object does not contain 'tag' and 'value' or 'error' property"))}var S=class t{constructor(e){this.value=e;Object.defineProperties(this,{tag:{writable:!1,enumerable:!1}})}tag="some";isSome(){return!0}ifSome(e){return e(this.value),this}isNone(){return!1}ifNone(e){return this}map(e){return new t(e(this.value))}flatMap(e){return e(this.value)}andThen(e){return e(this.value)}unwrap(){return this.value}unwrapOr(e){return this.value}unwrapOrElse(e){return this.value}or(e){return this}orElse(e){return this}match(e,r){return e(this.value)}toString(){return`Some(${this.value})`}toJSON(){return{tag:"some",value:this.value}}toNullable(){return this.value}toBoolean(){return!0}okOrElse(e){return u(this.value)}},T=class t{tag="none";constructor(){Object.defineProperties(this,{tag:{writable:!1,enumerable:!1}})}isSome(){return!1}ifSome(e){return this}isNone(){return!0}ifNone(e){return e(),this}map(e){return new t}andThen(e){return v}flatMap(e){return new t}unwrap(){throw new Error("Tried to unwrap a non-existent value")}unwrapOr(e){return e}unwrapOrElse(e){return e()}or(e){return e}orElse(e){return e()}match(e,r){return r()}toString(){return"None"}toJSON(){return{tag:"none"}}toNullable(){return null}toBoolean(){return!1}okOrElse(e){return o(e())}};function f(t){return new S(t)}var v=new T;function Ce(t){return t?f(t):v}var V=class t extends Error{constructor(r,n){super(t.getBestMsg(n)||"Schema validation error");this.input=r;this.detail=n;this.name="SchemaValidationError"}type="SchemaValiationError";format(){return{input:this.input,error:t.formatDetail(this.detail)}}get info(){return t.getBestMsg(this.detail)}static getBestMsg(r){switch(r.kind){case"typeMismatch":case"unexpectedProperties":case"missingProperties":case"general":case"unionValidation":return t.formatMsg(r);case"propertyValidation":case"arrayElement":return r.msg||t.getBestMsg(r.detail);default:return"Unknown error"}}static formatDetail(r){switch(r.kind){case"general":case"typeMismatch":return t.formatMsg(r);case"propertyValidation":return{[r.property]:r.msg||this.formatDetail(r.detail)};case"unexpectedProperties":case"missingProperties":{let n=r.msg||(r.kind==="unexpectedProperties"?"Property is not allowed in a strict schema object":"Property is required, but missing");return r.keys.reduce((s,c)=>(s[c]=n,s),{})}case"arrayElement":{let n={};return r.msg&&(n.msg=r.msg),n[`index_${r.index}`]=this.formatDetail(r.detail),n}case"unionValidation":{let n=r.details?.map(s=>this.formatDetail(s));return r.msg&&n.unshift("Msg: "+r.msg),n}default:return"Unknown error type"}}static formatMsg(r){if(r.msg||r.kind==="general")return r.msg||"Unknown error";switch(r.kind){case"typeMismatch":return`Expected ${r.expected}, but received ${r.received}`;case"unexpectedProperties":return`Properties not allowed: ${r.keys.join(", ")}`;case"missingProperties":return`Missing required properties: ${r.keys.join(", ")}`;case"unionValidation":return"Input did not match any union member";default:return"Unknown error"}}};function a(t,e){return new V(t,e)}var i=class{constructor(e){this.msg=e}checks=[];parse(e){return this.validateInput(e).andThen(r=>this.applyValidationChecks(r))}static validatePrimitive(e,r,n){let s=typeof e;return s===r?u(e):o(a(e,{kind:"typeMismatch",expected:r,received:s,msg:n}))}addCheck(e){return this.checks.push(e),this}applyValidationChecks(e){for(let r of this.checks){let n=r(e);if(n)return o(n)}return u(e)}static isNullishSchema(e){return e.parse(null).isOk()||e.parse(void 0).isOk()}},N=class t extends i{static emailRegex=/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;static ipRegex=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;validateInput(e){return i.validatePrimitive(e,"string",this.msg)}max(e,r){return this.addCheck(n=>{if(n.length>e)return a(n,{kind:"general",msg:r||`String must be at most ${e} characters long`})})}min(e,r){return this.addCheck(n=>{if(n.length<e)return a(n,{kind:"general",msg:r||`String must be at most ${e} characters long`})})}regex(e,r){return this.addCheck(n=>{if(!e.test(n))return a(n,{kind:"general",msg:r||`String must match pattern ${String(e)}`})})}email(e){return this.regex(t.emailRegex,e||"String must be a valid email address")}ip(e){return this.regex(t.ipRegex,e||"String must be a valid ip address")}},F=class extends i{constructor(r,n){super(n);this.literal=r}validateInput(r){return i.validatePrimitive(r,"string",this.msg).andThen(n=>n===this.literal?u(n):o(a(r,{kind:"typeMismatch",expected:this.literal,received:n,msg:this.msg})))}},M=class extends i{validateInput(e){return i.validatePrimitive(e,"number",this.msg)}gt(e,r){return this.addCheck(n=>{if(n<=e)return a(n,{kind:"general",msg:r||`Number must be greater than ${e}`})})}gte(e,r){return this.addCheck(n=>{if(n<e)return a(n,{kind:"general",msg:r||`Number must be greater than or equal to ${e}`})})}lt(e,r){return this.addCheck(n=>{if(n>=e)return a(n,{kind:"general",msg:r||`Number must be less than ${e}`})})}lte(e,r){return this.addCheck(n=>{if(n>e)return a(n,{kind:"general",msg:r||`Number must be less than or equal to ${e}`})})}int(e){return this.addCheck(r=>{if(!Number.isInteger(r))return a(r,{kind:"general",msg:e||"Number must be an integer"})})}positive(e){return this.gt(0,e||"Number must be positive")}nonnegative(e){return this.gte(0,e||"Number must be nonnegative")}negative(e){return this.lt(0,e||"Number must be negative")}nonpositive(e){return this.lte(0,e||"Number must be nonpositive")}finite(e){return this.addCheck(r=>{if(!Number.isFinite(r))return a(r,{kind:"general",msg:e||"Number must be an integer"})})}safe(e){return this.addCheck(r=>{if(!Number.isSafeInteger(r))return a(r,{kind:"general",msg:e||"Number must be an integer"})})}multipleOf(e,r){return this.addCheck(n=>{if(n%e!==0)return a(n,{kind:"general",msg:r||`Number must be a multiple of ${e}`})})}},B=class extends i{validateInput(e){return i.validatePrimitive(e,"bigint",this.msg)}},D=class extends i{validateInput(e){return i.validatePrimitive(e,"boolean",this.msg)}},j=class extends i{validateInput(e){return i.validatePrimitive(e,"object",this.msg).andThen(r=>{if(r instanceof Date)return u(r);let n=r?.constructor?.name??"unknown";return o(a(e,{kind:"typeMismatch",expected:"Date instance",received:n,msg:this.msg}))})}},q=class extends i{validateInput(e){return i.validatePrimitive(e,"symbol",this.msg)}},$=class extends i{validateInput(e){return i.validatePrimitive(e,"undefined",this.msg)}},C=class extends i{validateInput(e){if(e===null)return u(e);let r=typeof e=="object"?e?.constructor?.name??"unknown":typeof e;return o(a(e,{kind:"typeMismatch",expected:"null",received:r,msg:this.msg}))}},J=class extends i{validateInput(e){if(e==null)return u();let r=typeof e=="object"?e?.constructor?.name??"unknown":typeof e;return o(a(e,{kind:"typeMismatch",expected:"void (undefined/null)",received:r,msg:this.msg}))}},K=class extends i{validateInput(e){return u(e)}},L=class extends i{validateInput(e){return u(e)}},z=class extends i{validateInput(e){return o(a(e,{kind:"typeMismatch",expected:"never",received:typeof e,msg:this.msg}))}},Q=class extends i{constructor(r,n){let s,c;typeof n=="string"?s=n:typeof n=="object"&&(c=n);super(s);this.shape=r;this.objectMsg=c}strictMode=!1;objectMsg;validateInput(r){return i.validatePrimitive(r,"object",this.msg||this.objectMsg?.mismatch).andThen(n=>{if(n===null)return o(a(r,{kind:"typeMismatch",expected:"Non-null object",received:"null",msg:this.msg||this.objectMsg?.nullObject}));let s={},c=new Set(Object.keys(this.shape));for(let E of Object.keys(n)){let g=this.shape[E];if(g===void 0){if(this.strictMode){let pe=new Set(Object.keys(n)).difference(new Set(Object.keys(this.shape))).keys().toArray();return o(a(r,{kind:"unexpectedProperties",keys:pe,msg:this.msg||this.objectMsg?.unexpectedProperty}))}continue}let k=g.parse(n[E]);if(k.isErr())return o(a(r,{kind:"propertyValidation",property:E,detail:k.error.detail,msg:this.msg||this.objectMsg?.propertyValidation}));c.delete(E),s[E]=k.value}let h=c.keys().filter(E=>!i.isNullishSchema(this.shape[E])).toArray();return h.length>0?o(a(r,{kind:"missingProperties",keys:h,msg:this.msg||this.objectMsg?.missingProperty})):u(s)})}strict(){return this.strictMode=!0,this}pick(r){let n={};for(let s of Object.keys(r))r[s]&&(n[s]=this.shape[s]);return l.obj(n)}},W=class t extends i{constructor(r,n){let s,c;typeof n=="string"?s=n:typeof n=="object"&&(c=n);super(s);this.schemas=r;this.unionMsg=c}unionMsg;static getTypeFromSchemaName(r){switch(r){case"StringSchema":case"LiteralSchema":return"string";case"NumberSchema":return"number";case"BigintSchema":return"bigint";case"BooleanSchema":return"boolean";case"UndefinedSchema":return"undefined";case"SymbolSchema":return"symbol";default:return"object"}}validateInput(r){let n=[],s=!0;for(let c of this.schemas){let h=c.parse(r);if(h.isOk())return u(h.value);s=h.error.detail?.kind==="typeMismatch"&&s,n.push(h.error.detail)}return s?o(a(r,{kind:"typeMismatch",expected:this.schemas.map(c=>t.getTypeFromSchemaName(c.constructor.name)).join(" | "),received:typeof r,msg:this.msg||this.unionMsg?.mismatch})):o(a(r,{kind:"unionValidation",msg:this.msg||this.unionMsg?.unionValidation||"Input did not match any union member",details:n}))}},Z=class extends i{constructor(r,n){let s,c;typeof n=="string"?s=n:typeof n=="object"&&(c=n);super(s);this.schema=r;this.arrayMsg=c}arrayMsg;validateInput(r){if(!Array.isArray(r))return o(a(r,{kind:"typeMismatch",expected:"Array",received:"Non-array",msg:this.msg||this.arrayMsg?.mismatch}));for(let n=0;n<r.length;n++){let s=this.schema.parse(r[n]);if(s.isErr())return o(a(r,{kind:"arrayElement",index:n,detail:s.error.detail,msg:this.msg||this.arrayMsg?.element}))}return u(r)}},G=class extends i{constructor(r,n){super(n);this.schema=r}validateInput(r){return r===void 0?u(r):this.schema.parse(r)}},H=class extends i{constructor(r,n){super(n);this.schema=r}validateInput(r){return r===null?u(r):this.schema.parse(r)}},X=class extends i{constructor(r,n){super(n);this.schema=r}validateInput(r){return r==null?u(r):this.schema.parse(r)}},Y=class extends i{constructor(r,n){super();this.okSchema=r;this.errSchema=n}validateInput(r){return i.validatePrimitive(r,"object").andThen(n=>{if("tag"in n)switch(n.tag){case"ok":return"value"in n?this.okSchema.parse(n.value).match(s=>u(u(s)),s=>o(a(r,{kind:"propertyValidation",property:"value",detail:s.detail}))):i.isNullishSchema(this.okSchema)?u(u()):o(a(r,{kind:"missingProperties",keys:["value"],msg:"If tag is set to 'ok', than result must contain a 'value' property"}));case"err":return"error"in n?this.errSchema.parse(n.error).match(s=>u(o(s)),s=>o(a(r,{kind:"propertyValidation",property:"error",detail:s.detail}))):i.isNullishSchema(this.errSchema)?u(o()):o(a(r,{kind:"missingProperties",keys:["error"],msg:"If tag is set to 'err', than result must contain a 'error' property"}));default:return o(a(r,{kind:"propertyValidation",property:"tag",detail:{kind:"typeMismatch",expected:"'ok' or 'err'",received:`'${n.tag}'`}}))}else return o(a(r,{kind:"missingProperties",keys:["tag"],msg:"Result must contain a tag property"}))})}},_=class extends i{constructor(r){super();this.schema=r}validateInput(r){return i.validatePrimitive(r,"object").andThen(n=>{if("tag"in n)switch(n.tag){case"some":return"value"in n?this.schema.parse(n.value).match(s=>u(f(s)),s=>o(a(r,{kind:"propertyValidation",property:"value",detail:s.detail}))):i.isNullishSchema(this.schema)?u(f()):o(a(r,{kind:"missingProperties",keys:["value"],msg:"If tag is set to 'some', than option must contain a 'value' property"}));case"none":return u(v);default:return o(a(r,{kind:"propertyValidation",property:"tag",detail:{kind:"typeMismatch",expected:"'some' or 'none'",received:`'${n.tag}'`}}))}else return o(a(r,{kind:"missingProperties",keys:["tag"],msg:"Option must contain a tag property"}))})}},l={string:t=>new N(t),literal:(t,e)=>new F(t,e),number:t=>new M(t),bigint:t=>new B(t),boolean:t=>new D(t),date:t=>new j(t),symbol:t=>new q(t),undefined:t=>new $(t),null:t=>new C(t),void:t=>new J(t),any:t=>new K(t),unknown:t=>new L(t),never:t=>new z(t),obj:(t,e)=>new Q(t,e),union:(t,e)=>new W(t,e),array:(t,e)=>new Z(t,e),optional:(t,e)=>new G(t,e),nullable:(t,e)=>new H(t,e),nullish:(t,e)=>new X(t,e),result:(t,e)=>new Y(t,e),option:t=>new _(t)};function p(t,e){return l.obj({type:l.literal(t),info:e??l.string()})}function d(t){return e=>({type:t.shape.type.literal,info:e})}var b=p("QueryExecutionError"),lr=d(b),de=p("NoAdminEntryError"),cr=d(de),me=p("FailedToReadFileError"),pr=d(me),he=p("InvalidSyntaxError"),dr=d(he),Ee=p("InvalidPathError"),mr=d(Ee),ee=p("AdminPasswordNotSetError"),hr=d(ee),A=p("RequestValidationError"),le=d(A),ye=p("ResponseValidationError"),ce=d(ye),P=p("FailedToParseRequestAsJSONError"),Er=d(P),U=p("TooManyRequestsError"),yr=d(U),re=p("UnauthorizedError"),fr=d(re),te=p("InvalidPasswordError"),Tr=d(te),ne=p("AdminPasswordAlreadySetError"),gr=d(ne),se=p("PasswordsMustMatchError"),vr=d(se),oe=p("CommandExecutionError"),Sr=d(oe),fe=p("DeviceDoesNotExistError"),xr=d(fe),Te=p("DeviceAlreadyBoundError"),Rr=d(Te),ge=p("DeviceNotBoundError"),wr=d(ge),ie=p("UsbipUnknownError"),Ur=d(ie),ve=p("NotFoundError"),kr=d(ve),Se=p("NotAllowedError"),Or=d(Se);var w=class{constructor(e,r,n){this.path=e;this.method=r;this.schema=n;this.pathSplitted=e.split("/"),this.paramIndexes=this.pathSplitted.reduce((s,c,h)=>(c.startsWith(":")&&(s[c.slice(1)]=h),s),{})}pathSplitted;paramIndexes;makeRequest(e,r){return this.schema.req.parse(e).toAsync().mapErr(n=>le(n.info)).andThenAsync(async n=>{let s=this.pathSplitted;for(let[g,k]of Object.entries(r))s[this.paramIndexes[g]]=k;let c=s.join("/");console.log(n);let E=await(await fetch(c,{method:this.method,headers:{"Content-Type":"application/json",Accept:"application/json; charset=utf-8"},body:JSON.stringify(n)})).json();return this.schema.res.parse(E).toAsync().map(g=>g).mapErr(g=>ce(g.info))})}makeSafeRequest(e,r){return this.makeRequest(e,r).mapErr(n=>{if(n.type==="RequestValidationError")throw"Failed to validate request";return n})}};var xe={req:l.obj({password:l.string()}),res:l.result(l.void(),l.union([ee,b,P,A,U,te]))},Br=new w("/login","POST",xe),Re={req:l.obj({password:l.string().min(10,"Password must be at least 10 characters long").regex(/^[a-zA-Z0-9]+$/,"Password must consist of lower or upper case latin letters and numbers"),passwordRepeat:l.string()}).addCheck(t=>{if(t.passwordRepeat!==t.password)return a(t,{kind:"general",msg:"Passwords must match"})}),res:l.result(l.void(),l.union([se,ne,b,P,A,U]))},Dr=new w("/setup","POST",Re),we={req:l.void(),res:l.result(l.void(),l.union([b,U,re,oe,ie]))},jr=new w("/api/updateDevices","POST",we),Ue={req:l.void(),res:l.result(l.obj({app:l.literal("Keyborg"),version:l.string()}),l.union([U]))},qr=new w("/version","POST",Ue);export{i as BaseSchema,y as Err,F as LiteralSchema,T as None,Q as ObjectSchema,m as Ok,_ as OptionSchema,R as ResultAsync,De as ResultFromJSON,Y as ResultSchema,V as SchemaValidationError,S as Some,N as StringSchema,a as createValidationError,o as err,x as errAsync,ue as flattenResult,Ce as fromNullableVal,Be as fromThrowable,ae as getMessageFromError,Br as loginApi,v as none,u as ok,I as okAsync,Dr as passwordSetupApi,f as some,jr as updateDevicesApi,qr as versionApi,l as z};