react-playmakers
Version:
React wrapper providing utilities for PlayMakers integration
1 lines • 59.9 kB
JavaScript
import{Amplify as e}from"aws-amplify";import{fetchAuthSession as t,signIn as r,confirmSignIn as a,signOut as s,signInWithRedirect as o,getCurrentUser as n}from"aws-amplify/auth";import i from"axios";import{jsx as c}from"react/jsx-runtime";import{Hub as u}from"aws-amplify/utils";import l,{useState as d,useEffect as h,useContext as m,createContext as w,useRef as p}from"react";import{CookiesProvider as g}from"react-cookie";function y(){return y=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var a in r)({}).hasOwnProperty.call(r,a)&&(e[a]=r[a])}return e},y.apply(null,arguments)}function f(e,t){if(null==e)return{};var r={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.includes(a))continue;r[a]=e[a]}return r}async function E(e=!1){try{var r,a;const{accessToken:s}=null!=(r=(await t({forceRefresh:e})).tokens)?r:{};return s&&null!=s&&s.toString()?!e&&null!=s&&null!=(a=s.payload)&&a.exp&&1e3*s.payload.exp-(new Date).getTime()<3e5?await E(!0):null==s?void 0:s.toString():null}catch(e){return null}}async function b(e,t={}){t.accessToken=await E();const r=document.createElement("form");r.method="POST",r.action=e,Object.keys(t).forEach(e=>{const a=document.createElement("input");a.type="hidden",a.name=e,a.value=t[e],r.appendChild(a)}),document.body.appendChild(r),r.submit()}const S={};async function I({cacheExpiration:e,url:t,method:r,params:a={},files:s=[]}){const o=await(async(e,t="",r="",a=2e3)=>{var s;const o=`${e}(${t}){${JSON.stringify(r)}}`,n=S[o];if("get"!==t&&(a=a<500?a:500),n&&(new Date).getTime()-n.timestamp<a)return null==(s=await n.response)?void 0:s.data})(t,r,a,e);if(void 0!==o)return o;const n={params:"get"===r?a:void 0,headers:{}};let c=a;s&&s.length?(c=new FormData,Object.entries(a).forEach(([e,t])=>{c.append(e,t)}),n.headers["Content-Type"]="multipart/form-data",s.forEach(e=>{c.append("files",e)})):n.headers["Content-Type"]="application/json";const u=await E();u&&(n.headers.Authorization=`Bearer ${u}`);try{const e=i(y({data:c,method:r,url:t},n));return((e,t="",r="",a)=>{const s=`${e}(${t}){${JSON.stringify(r)}}`;S[s]={response:a,timestamp:(new Date).getTime()}})(t,r,a,e),(await e).data}catch(e){var l,d;const t=(null==(l=e.response)?void 0:l.status)||400,{code:r}=e;throw console.error("Connection error",r,t),(null==(d=e.response)?void 0:d.data)||e}}const v=["url"];class R{constructor(t){var r=this;this.baseUrl=void 0,this.cacheExpiration=void 0,this.uploadsUrl=void 0,this.projectId=void 0,this.twitterSignInUrl=void 0,this.call=async function(e){let{url:t}=e,a=f(e,v);return await I(y({cacheExpiration:r.cacheExpiration,url:`${r.baseUrl}/${t}`},a))},this.exports=["baristaRequest","createAsset","updateAsset","updateAssetFile","getAsset","getGlobalAssets","getProjectAssets","getSchemaAssets","deleteAsset","getCategories","getParentCategories","createCategory","deleteCategory","renameCategory","getUserComments","getSubmissionComments","getComment","createComment","updateComment","deleteComment","getProjects","getProject","createProject","updateProject","updateProjectConfig","updateProjectThumbnail","createSchema","updateSchema","deleteSchema","getSchemas","getSchemasByCategory","getSchema","updateSchemaThumbnail","createSubmission","updateSubmission","deleteSubmission","getSubmission","getSubmissions","getSubmissionsBySchema","getSubmissionsByIds","updateSubmissionsStates","signUp","signUpConfirmation","resendConfirmationCode","sendPasswordResetCode","passwordReset","getMe","getUser","getUserMetadata","getTokensFromTwitterToken","getCreators","updateAvatar","createUserParent","linkFederated","unlinkFederated","vote","downVote","upVote","cancelVote","getVote","voteBalance","getNotifications","markAllNotificationsAsRead","updateNotification","deleteNotification","getTags","redirectTwitterLogin","getSteamProfile","getQuestType","getQuestTypes","getQuestTypeCategories","getQuests","getQuest","createQuest","deleteQuest","updateQuest","getUserQuest","getUserQuests","getUserQuestsByProject","getUserQuestsByQuest","completeQuest","getRewardTypes","getRewardType","getRewardsByProject","getReward","createReward","updateReward","deleteReward","redeemReward","getUserRewards","getUserRewardsByProject","getUserRewardsByReward","getUserReward","updateUserRewardState"],this.extendSubmission=e=>(e.zip||(e.zip=`${this.uploadsUrl}/${e.id}/submission.zip`),e),this.baristaRequest=async function({schema:e,submission:t}){return await r.call({method:"post",params:{schema:e,submission:t},url:"barista"})},this.createAsset=async function(e){return await r.call({method:"post",params:e,url:"asset"})},this.updateAsset=async function(e,t){return await r.call({method:"put",params:t,url:`asset/${e}`})},this.updateAssetFile=async function(e,t){return await r.call({files:[t],method:"put",url:`asset/${e}/upload`})},this.getAsset=async function(e){return await r.call({method:"get",url:`asset/${e}`})},this.getGlobalAssets=async function(e){return await r.call({method:"get",params:e,url:"assets/global"})},this.getProjectAssets=async function(e,t=r.projectId){return await r.call({method:"get",params:e,url:`assets/by/project/${t}`})},this.getSchemaAssets=async function(e,t={}){return await r.call({method:"get",params:t,url:`assets/by/schema/${e}`})},this.deleteAsset=async function(e){return await r.call({method:"delete",url:`asset/${e}`})},this.getCategories=async function(e,t=r.projectId,a={}){return await r.call({method:"get",params:y({categoryId:e},a),url:`categories/${t}`})},this.getParentCategories=async function(e){return await r.call({method:"get",url:`category/${e}`})},this.createCategory=async function(e,t,a=r.projectId){return await r.call({method:"post",params:{name:e,parentId:t,projectId:a},url:"category"})},this.deleteCategory=async function(e){return await r.call({method:"delete",url:`category/${e}`})},this.renameCategory=async function(e,t){return await r.call({method:"put",params:{name:t},url:`category/${e}`})},this.getUserComments=async function(e,t){return await r.call({method:"get",params:t,url:`comments/by/user/${e}`})},this.getSubmissionComments=async function(e,t){return await r.call({method:"get",params:t,url:`comments/${e}`})},this.getComment=async function(e){return await r.call({method:"get",url:`comment/${e}`})},this.createComment=async function(e,t,a){return await r.call({method:"post",params:{body:t,state:a},url:`comment/${e}`})},this.updateComment=async function(e,t,a){return await r.call({method:"put",params:{body:t,state:a},url:`comment/${e}`})},this.deleteComment=async function(e){return await r.call({method:"delete",url:`comment/${e}`})},this.getProjects=async function(e={}){return await r.call({method:"get",params:e,url:"projects"})},this.getProject=async function(e=r.projectId){return await r.call({method:"get",url:`project/${e}`})},this.createProject=async function(e){return await r.call({method:"post",params:e,url:"project"})},this.updateProject=async function(e,t=r.projectId){return await r.call({method:"put",params:e,url:`project/${t}`})},this.updateProjectConfig=async function(e,t=r.projectId){return await r.call({method:"put",params:e,url:`project/${t}/config`})},this.updateProjectThumbnail=async function(e,t=r.projectId){return await r.call({files:[e],method:"put",url:`project/${t}/thumbnail`})},this.createSchema=async function(e){return await r.call({method:"post",params:e,url:"schema"})},this.updateSchema=async function(e,t){return await r.call({method:"put",params:t,url:`schema/${e}`})},this.getSchemas=async function(e=r.projectId,t={}){return await r.call({method:"get",params:t,url:`schemas/by/project/${e}`})},this.getSchemasByCategory=async function(e){return await r.call({method:"get",url:`schemas/by/category/${e}`})},this.getSchema=async function(e){return await r.call({method:"get",url:`schema/${e}`})},this.deleteSchema=async function(e){return await r.call({method:"delete",url:`schema/${e}`})},this.updateSchemaThumbnail=async function(e,t){return await r.call({files:[t],method:"put",url:`schema/${e}/thumbnail`})},this.createSubmission=async function(e={},t=[]){return r.extendSubmission(await r.call({files:t,method:"post",params:e,url:"submission"}))},this.updateSubmission=async function(e,t={},a=[]){return r.extendSubmission(await r.call({files:a,method:"put",params:t,url:`submission/${e}`}))},this.getSubmission=async function(e){return r.extendSubmission(await r.call({method:"get",url:`submission/${e}`}))},this.deleteSubmission=async function(e){return await r.call({method:"delete",url:`submission/${e}`})},this.getSubmissions=async function(e={}){return(await r.call({method:"get",params:e,url:"submissions"})).map(e=>r.extendSubmission(e))},this.getSubmissionsBySchema=async function(e){return(await r.call({method:"get",params:{schemaId:e},url:`submissions/by/schema/${e}`})).map(e=>r.extendSubmission(e))},this.getSubmissionsByIds=async function(e){return(await r.call({method:"get",params:{submissionIds:e},url:"submissions/by/ids"})).map(e=>r.extendSubmission(e))},this.updateSubmissionsStates=async function(e,t){return await r.call({method:"put",params:{state:t,submissionIds:e},url:"submissions/by/ids"})},this.signUp=async function(e,t,a){return await r.call({method:"post",params:{email:e,password:a,username:t},url:"user/auth/signup"})},this.resendConfirmationCode=async function(e,t){if(!e&&!t)throw new Error("Either email or username must be provided.");const a=y({},e&&{email:e},t&&{username:t});return await r.call({method:"post",params:a,url:"user/auth/resendConfirmation"})},this.sendPasswordResetCode=async function(e){return await r.call({method:"post",params:{email:e},url:"user/auth/sendPasswordResetCode"})},this.passwordReset=async function(e,t,a){return await r.call({method:"post",params:{code:t,password:a,username:e},url:"user/auth/passwordReset"})},this.signUpConfirmation=async function(e,t,a){const s=y({},a&&{email:a},e&&{username:e},{confirmationCode:t});return await r.call({method:"post",params:s,url:"user/auth/signupConfirmation"})},this.getMe=async function(){try{return await r.call({method:"get",url:"user/auth/me"})}catch(e){throw new Error("Failed to get user info.")}},this.getUser=async function(e){return await r.call({method:"get",url:`user/${e}`})},this.getUserMetadata=async function(e){return await r.call({method:"post",params:{idToken:e},url:"user/refreshMetadata"})},this.getTokensFromTwitterToken=async function(e,t){return await r.call({method:"post",params:{accessToken:e,accessTokenSecret:t},url:"user/auth/exchangeTwitterToken"})},this.getCreators=async function(){return await r.call({method:"get",url:"creators"})},this.updateAvatar=async function(e){return await r.call({files:[e],method:"put",url:"user"})},this.createUserParent=async function(e,t){return await r.call({method:"post",params:{provider:t,username:e},url:"user/federated/createParent"})},this.linkFederated=async function(e,t){return await r.call({method:"post",params:{accessToken:e,provider:t},url:"user/federated/linkFederated"})},this.unlinkFederated=async function(e,t){return await r.call({method:"post",params:{provider:t,sourceUsername:e},url:"user/federated/unlinkFederated"})},this.vote=async function(e,t){return await r.call({method:"post",url:`${"up"===t?"vote/up":"vote/down"}/${e}`})},this.downVote=async function(e){return await r.call({method:"post",url:`vote/down/${e}`})},this.upVote=async function(e){return await r.call({method:"post",url:`vote/up/${e}`})},this.cancelVote=async function(e){return await r.call({method:"delete",url:`vote/cancel/${e}`})},this.getVote=async function(e){const t=await r.call({method:"get",url:`vote/${e}`});return(null==t?void 0:t.value)||0},this.voteBalance=async function(e){const t=await r.call({method:"get",url:`vote/balance/${e}`});return(null==t?void 0:t.balance)||0},this.getNotifications=async function(e={}){return await r.call({method:"get",params:e,url:"notifications"})},this.markAllNotificationsAsRead=async function(){return await r.call({method:"put",url:"notifications"})},this.updateNotification=async function(e,t={}){return await r.call({method:"put",params:t,url:`notification/${e}`})},this.deleteNotification=async function(e){return await r.call({method:"delete",url:`notification/${e}`})},this.getTags=async function(e=r.projectId,t={}){return await r.call({method:"get",params:t,url:`tags/by/project/${e}`})},this.redirectTwitterLogin=()=>{window.location.replace(this.twitterSignInUrl)},this.getSteamProfile=async function(){return await r.call({method:"get",url:"quest/api/fetch/steam?operation=profile"})},this.getQuestType=async function(e){return await r.call({method:"get",url:`questTypes/${e}`})},this.getQuestTypes=async function(e={}){return await r.call({method:"get",params:e,url:"questTypes"})},this.getQuestTypeCategories=async function(e={}){return await r.call({method:"get",params:e,url:"questTypes/category"})},this.getQuest=async function(e){return await r.call({method:"get",url:`quest/${e}`})},this.getQuests=async function(e,t=r.projectId){return await r.call({method:"get",params:e,url:`quests/by/project/${t}`})},this.getUserQuests=async function(e={},t=r.projectId){return await r.call({method:"get",params:e,url:`userQuests/by/project/${t}`})},this.completeQuest=async function(e,t){return await r.call({method:"post",params:t,url:`quest/${e}/complete`})},this.createQuest=async function(e){return await r.call({method:"post",params:e,url:"quest"})},this.updateQuest=async function(e,t){return await r.call({method:"put",params:t,url:`quest/${e}`})},this.deleteQuest=async function(e){return await r.call({method:"delete",url:`quest/${e}`})},this.getUserQuest=async function(e){return await r.call({method:"get",url:`userQuest/${e}`})},this.getUserQuestsByQuest=async function(e={},t){return await r.call({method:"get",params:e,url:`userQuests/by/quest/${t}`})},this.getUserQuestsByProject=async function(e={},t=r.projectId){return await r.call({method:"get",params:e,url:`userQuests/by/project/${t}`})},this.getRewardTypes=async function(e={}){return await r.call({method:"get",params:e,url:"rewardTypes"})},this.getRewardType=async function(e){return await r.call({method:"get",url:`rewardType/${e}`})},this.getRewardsByProject=async function(e,t=r.projectId){return await r.call({method:"get",params:e,url:`rewards/by/project/${t}`})},this.getReward=async function(e){return await r.call({method:"get",url:`reward/${e}`})},this.redeemReward=async function(e){return await r.call({method:"post",url:`reward/${e}/redeem`})},this.createReward=async function(e){return await r.call({method:"post",params:e,url:"reward"})},this.updateReward=async function(e,t){return await r.call({method:"put",params:t,url:`reward/${e}`})},this.deleteReward=async function(e){return await r.call({method:"delete",url:`reward/${e}`})},this.getUserRewards=async function(e={}){return await r.call({method:"get",params:e,url:"userRewards"})},this.getUserRewardsByProject=async function(e={},t=r.projectId){return await r.call({method:"get",params:e,url:`userRewards/by/project/${t}`})},this.getUserRewardsByReward=async function(e,t={}){return await r.call({method:"get",params:t,url:`userRewards/by/reward/${e}`})},this.getUserReward=async function(e){return await r.call({method:"get",url:`userReward/${e}`})},this.updateUserRewardState=async function(e,t){return await r.call({method:"put",params:{state:t},url:`userReward/${e}`})},this.baseUrl=t.API_BASEURL,this.cacheExpiration=t.API_CACHE_EXPIRATION,this.uploadsUrl=t.UPLOADS_BASEURL,this.projectId=t.PROJECT_ID;const a=encodeURIComponent(t.TWITTER.CALLBACK_URL);this.twitterSignInUrl=`${this.baseUrl}/auth/redirect/twitter?redirectUrl=${a}`,e.configure({Auth:{Cognito:{loginWith:{oauth:{domain:t.COGNITO.DOMAIN,redirectSignIn:t.COGNITO.REDIRECT_SIGNIN,redirectSignOut:t.COGNITO.REDIRECT_SIGNOUT,responseType:"code",scopes:["aws.cognito.signin.user.admin","email","profile","openid"]},username:!0},userPoolClientId:t.COGNITO.CLIENT_ID,userPoolId:t.COGNITO.POOL_ID}}})}}const T=["children"],$={API_BASEURL:"https://api.playmakers.co",API_CACHE_EXPIRATION:2e3,BARISTA_BASEURL:"https://barista.playmakers.co",BARISTA_VERSION:"latest",COGNITO:{CLIENT_ID:"1bkjbgkktdujdv23r62eue2elo",DOMAIN:"cognito.playmakers.co",POOL_ID:"eu-north-1_qMIFaOOnN",REDIRECT_SIGNIN:[`${window.location.origin}/handle-from-federated`],REDIRECT_SIGNOUT:[`${window.location.origin}/handle-signout`],REGION:"eu-north-1"},IDSERVER_BASEURL:"https://id.playmakers.co",NOTIFICATIONS_POLL_PERIOD:3e4,PROJECT_ID:void 0,SUBMISSION_UPLOAD_POLL_PERIOD:2e3,SUBMISSION_UPLOAD_TIMEOUT:9e4,TWITTER:{CALLBACK_URL:`${window.location.origin}/handle-from-twitter`},UPLOADS_BASEURL:"https://file.playmakers.co"},P=/*#__PURE__*/l.createContext($),C=()=>l.useContext(P),j=e=>{let{children:t}=e,r=f(e,T);const a=y({},$,r);return a.COGNITO=y({},$.COGNITO,r.COGNITO),c(P.Provider,{value:a,children:c(g,{defaultSetOptions:{path:"/"},children:c(N,{children:c(Q,{children:t})})})})},U=/*#__PURE__*/l.createContext({}),A=()=>l.useContext(U),N=({children:e})=>{const t=C(),r=new R(t),a={};for(const e of r.exports)a[e]=r[e],a[e].methodName=e;return c(U.Provider,{value:a,children:e})},O={discord:{displayName:"Discord",identityProvider:{custom:"Discord"}},facebook:{displayName:"Facebook",identityProvider:"Facebook"},google:{displayName:"Google",identityProvider:"Google"},twitch:{displayName:"Twitch",identityProvider:{custom:"Twitch"}},twitter:{displayName:"X",identityProvider:"Twitter"},ultra:{displayName:"Ultra",identityProvider:{custom:"Ultra"}}},k=/*#__PURE__*/w(void 0);function Q({children:e}){const{signUp:i,signUpConfirmation:l,getMe:m,resendConfirmationCode:w,sendPasswordResetCode:p,passwordReset:g,updateAvatar:y,createUserParent:f,linkFederated:E,unlinkFederated:b,redirectTwitterLogin:S,getUserMetadata:I,getSteamProfile:v}=A(),[R,T]=d(null),$="signedIn"===window.localStorage.getItem("amplify-authenticator-authState");async function P(){let e;try{e=await n(),(R&&!e||!R&&e||(null==R?void 0:R.username)!==e.username||R.userId!==e.userId)&&e&&await U()}catch(t){throw(R||e)&&await U(),t}}async function C(e){let r;try{var a,s;if(r=e||await m(),!r)return;const o=await t(),n=null==o||null==(a=o.tokens)||null==(a=a.accessToken)?void 0:a.toString();n&&(r.accessToken=n);const i=null==o||null==(s=o.tokens)||null==(s=s.idToken)?void 0:s.toString();return i&&(r.idToken=i),T(r),window.localStorage.setItem("amplify-authenticator-authState","signedIn"),r}catch(e){throw console.error("error getting user",e),T(null),e}}async function j(e){try{let t;return e?t=await C(e):(await new Promise(e=>setTimeout(e,1e3)),t=await C()),t||console.error("Failed to refresh local user"),t}catch(e){throw console.error("Error refreshing local user",e),e}}async function U(){await s(),window.localStorage.removeItem("amplify-authenticator-authState"),T(null)}return h(()=>{!async function(){C()}()},[]),c(k.Provider,{value:{FederatedListener:()=>(h(()=>{const e=u.listen("auth",({payload:e})=>{switch(e.event){case"signInWithRedirect":C();break;case"signInWithRedirect_failure":console.error("An error has occurred during the OAuth flow.")}});return()=>{e()}},[]),null),confirmSignIn:async function(e){const{isSignedIn:t,nextStep:r}=await a({challengeResponse:e});return"DONE"===r.signInStep&&t&&C(),{isSignedIn:t,nextStep:r}},createUserParent:f,getSteamProfile:async()=>{try{const e=await v();return e&&await j(),e}catch(e){throw console.error("Error fetching steam profile",e),new Error("Error fetching steam profile",{cause:e})}},getUserMetadata:async function(){try{if(null==R||!R.idToken)return;return await I(R.idToken)}catch(e){throw console.error("Error getting metadata",e),e}},isLoggedIn:$,linkFederated:E,passwordReset:async function(e,t,r){return U(),await g(e,t,r)},providerData:O,redirectTwitterLogin:S,refreshLoggedInUser:j,resendConfirmationCode:w,sendForgotPassword:p,signIn:async(e,t)=>{try{if(!e||!t)throw new Error("Missing username or password");P();const{isSignedIn:a,nextStep:s}=await r({password:t,username:e});return"DONE"===s.signInStep&&a&&await C(),{isSignedIn:a,nextStep:s}}catch(e){throw console.error("Error signing in",e),e}},signInWithRedirect:async function(e){P();const t=O[e].identityProvider;await o({provider:t})},signOut:U,signUp:i,signUpConfirmation:l,unlinkFederated:b,updateUserAvatar:async function(e){const t=await y(e);return null!=t&&t.url&&T(e=>(e&&(e.avatar=t.url),e)),t},userData:R},children:e})}function B(){const e=m(k);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const q={},L=async(e,t,r)=>{const a=`${e.name||e.methodName}(${JSON.stringify(t)})`,s=await(async(e,t=2e3)=>{const r=q[e];if(r&&(new Date).getTime()-r.timestamp<t)return await r.response})(a,r);if(void 0!==s)return s;const o=e(...t);return((e,t)=>{q[e]={response:t,timestamp:(new Date).getTime()}})(a,o),await o},D=(e,t)=>{if(e)if(t)delete q[`${e}(${JSON.stringify(t)})`];else for(const t in q)t.startsWith(`${e}(`)&&delete q[t];else for(const e in q)delete q[e]},_=(e,t,r=!0,a=1,s=10)=>{const[o,n]=d(a),i=e=>(e.length<(s||10)&&t(!1),e);return{appendNextPage:async(t,a)=>{if(!r)return;const c=o+1,u=await t({limit:s,page:c}),l=a?u.map(a):u;e(e=>(e.push(...l),e)),i(l),n(c)},checkHasMore:i,currentPage:o,hasMore:r,refreshLastPage:async(t,r)=>{const a=await t({limit:s,page:o}),n=r?a.map(r):a;e(e=>{const t=e.length%s;return e.splice(-t,t),e.push(...n),e}),i(n)}}},M=e=>{const{createAsset:t,getAsset:r,updateAsset:a,updateAssetFile:s,deleteAsset:o}=A();let n=e;const[i,c]=d(null),[u,l]=d(!1),[m,w]=d(null),p=async(t=!1)=>{try{if(!e)throw c(null),l(!1),new Error("No asset to fetch");t||l(!1);const a=await L(r,[e],3e5);return c(a),a}catch(t){throw console.error(`Error fetching asset ${e}`,t),new Error(`Error fetching asset ${e}`,{cause:t})}finally{l(!0)}},g=async(t=m)=>{if(n&&t&&"string"!=typeof t)try{await s(n,t),D("getAsset",[n])}catch(t){throw console.error(`Error updating file for asset '${n}'`,t),new Error(`Error updating file for asset ${e}`,{cause:t})}};return h(()=>{p()},[e]),y({},i,{asset:i,delete:async()=>{try{if(!e)throw new Error("No asset to delete");await o(e)}catch(t){throw console.error(`Error deleting asset '${e}'`,t),new Error(`Error deleting asset '${e}'`,{cause:t})}},fetched:u,push:async r=>{const s=y({},i,r);if(!s)throw new Error("No asset");const{data:o,description:u,name:l,projectId:d,schemaId:h,tags:w=[],type:p,url:f,newFile:E}=s,b={};void 0!==o&&(b.data=o),void 0!==u&&u&&(b.description=u),l&&(b.name=l),void 0!==w&&(b.tags=w),void 0!==f&&(b.url=f),e||(d&&(b.projectId=d),h&&(b.schemaId=h),p&&(b.type=p));try{const r=e?await a(e,b):await t(b);if(!r)throw new Error("Asset not uploaded");return n=null==r?void 0:r.id,(E||m)&&await g(E||m),D("getAsset",[h]),d||h||D("getGlobalAssets"),d&&D("getProjectAssets"),D("getSchemaAssets"),c(r),r}catch(t){throw console.error(`Error pushing asset '${e}'`,t),new Error(`Error pushing asset '${e}'`,{cause:t})}},pushFile:g,refresh:p,setAsset:c,setFile:w})},F=(e={})=>{const{schemaId:t,projectId:r,tags:a,type:s,matchTags:o,page:n,limit:i}=e,{getGlobalAssets:c,getProjectAssets:u,getSchemaAssets:l,deleteAsset:m}=A(),[w,p]=d([]),[g,f]=d(!1),[E,b]=d(!0),{appendNextPage:S,refreshLastPage:I,checkHasMore:v,currentPage:R}=_(p,b,E,null==e?void 0:e.page,null==e?void 0:e.limit),T=e=>e.map(e=>y({},e,{delete:()=>m(e.id)})),$=async(e={})=>{let d;return d=t?await L(l,[t,y({limit:i,matchTags:o,page:n,type:s},e)],3e5):r?await L(u,[y({limit:i,page:n,tags:a,type:s},e),r],3e5):await L(c,[y({limit:i,page:n,tags:a,type:s},e)],6e5),T(d)},P=async(e=!1)=>{try{e||f(!1);const t=v(await $());return p(t),t}catch(e){throw console.error("Error fetching assets",e),new Error("Error fetching assets",{cause:e})}finally{f(!0)}};return h(()=>{P()},[t,r,a,s,o,n]),{assets:w,currentPage:R,fetchMore:async(e=!1)=>{try{f(!1),e?t?await I(async e=>T(await l(t,y({matchTags:o,type:s},e)))):r?await I(async e=>T(await u(y({tags:a,type:s},e),r))):await I(async e=>T(await c(y({tags:a,type:s},e)))):S($)}catch(e){throw console.error("Error fetching assets",e),new Error("Error fetching assets",{cause:e})}finally{f(!0)}},fetched:g,hasMore:E,refresh:P}},x=(e,t={})=>F(y({},t,{projectId:e})),V=(e,t={})=>F(y({},t,{schemaId:e})),J=(e,t={})=>F(y({},t,{tags:e})),G=(e={})=>F(y({},e,{type:"tutorial"})),H=(e,t={})=>G(y({},t,{projectId:e})),W=(e,t={})=>G(y({},t,{schemaId:e})),Z=(e,t={})=>G(y({},t,{tags:e})),z=["schemas"],Y=e=>{const{createSchema:t,getSchema:r,updateSchema:a,updateSchemaThumbnail:s}=A();let o=e;const[n,i]=d(null),[c,u]=d(!1),[l,m]=d(null),w=async(t=!1)=>{try{if(!e)throw i(null),u(!1),new Error("No schema to fetch");t||u(!1);const a=await L(r,[e],12e4);return i(a),u(!0),a}catch(t){throw console.error(`Error fetching schema ${e}`,t),new Error(`Error fetching schema ${e}`,{cause:t})}},p=async(e=l)=>{if(e&&"string"!=typeof e)try{if(!o)throw new Error("No schema to push thumbnail to");await s(o,e),D("getSchema",[o])}catch(e){throw console.error(`Error updating thumbnail for schema '${o}'`,e),new Error(`Error updating thumbnail for schema '${o}'`,{cause:e})}},g=["data"];return h(()=>{w()},[e]),y({},n,{displayInteractive:(null==n?void 0:n.displayInteractive)||"",displayThumbnail:(null==n?void 0:n.displayThumbnail)||"",fetched:c,push:async r=>{const s=y({},n,r);if(!s)throw new Error("No schema to push");const{newThumbnailFile:c}=s;c&&delete s.newThumbnailFile;const u=null==n?void 0:n.state,d=y({},s,{description:s.description||"",displayInteractive:s.displayInteractive||"{}",displayThumbnail:s.displayThumbnail||"{}",state:s.state||"draft"});"open"!==u&&"closed"!==u||g.forEach(e=>delete d[e]);try{const r=e?await a(e,d):await t(d);if(!r)throw new Error("Schema not uploaded");return o=null==r?void 0:r.id,(c||l)&&await p(c||l),D("getSchema",[o]),D("getSchemas"),i(r),r}catch(t){throw console.error(`Error pushing schema '${e}'`,t),new Error(`Error pushing schema '${e}'`,{cause:t})}},pushThumbnail:p,refresh:w,schema:n,setSchema:i,setThumbnail:m})},X=(e={})=>{const{PROJECT_ID:t}=C(),{getSchemas:r,updateSchema:a,deleteSchema:s}=A(),[o,n]=d([]),[i,c]=d(!1),[u,l]=d(!0),{appendNextPage:m,refreshLastPage:w,checkHasMore:p,currentPage:g}=_(n,l,u,null==e?void 0:e.page,null==e?void 0:e.limit),f=e=>e.map(e=>y({},e,{delete:()=>S(e.id),pushState:t=>b(e.id,t)})),E=async(a=!1)=>{try{if(!t)throw new Error("No project ID to fetch schemas");a||c(!1);const s=f(p(await L(r,[t,e],12e4)));return n(s),s}catch(e){throw console.error("Error fetching schemas",e),new Error("Error fetching schemas",{cause:e})}finally{c(!0)}};h(()=>{E()},[JSON.stringify(e),t]);const b=async(e,t)=>{try{const o=f([await a(e,{state:t})])[0];if(!o)throw new Error("Schema not uploaded");return D("getSchema",[e]),D("getSchemas"),r=e,s=o,n(e=>e.map(e=>e.id===r?y({},e,s):e)),o}catch(t){throw console.error(`Error pushing schema '${e}'`,t),new Error(`Error pushing schema '${e}'`,{cause:t})}var r,s},S=async e=>{try{const t=await s(e);return D("getSchema",[e]),D("getSchemas"),n(t=>t.filter(t=>t.id!==e)),t}catch(t){throw console.error(`Error deleting schema '${e}'`,t),new Error(`Error deleting schema '${e}'`,{cause:t})}};return{currentPage:g,fetchMore:async a=>{try{c(!1),a?await w(async a=>f(await r(t,y({},e,a)))):await m(async a=>f(await L(r,[t,y({},e,a)],12e4)))}catch(e){throw console.error("Error fetching more schemas",e),new Error("Error fetching more schemas",{cause:e})}finally{c(!0)}},fetched:i,hasMore:u,refresh:E,schemas:o}},K=(e,t)=>{const r=X(y({state:e},t)),{schemas:a}=r,s=f(r,z);return y({schemas:a.filter(t=>t.state===e)},s)},ee=()=>{const{BARISTA_BASEURL:e,BARISTA_VERSION:t}=C(),{baristaRequest:r}=A(),[a,s]=d(!1),[o,n]=d(!1),[i,c]=d(void 0);return h(()=>{const a=`${e}/${t}/barista_bundle.js`;s(!1),n(!1);const o=({type:e})=>{"load"===e?(window.BARISTA.setApiBaristaRequest(r),c(window.BARISTA),s(!0)):n(!0)};let i=document.querySelector(`script[src="${a}"]`);return i?window.BARISTA&&(c(window.BARISTA),s(!0)):(i=document.createElement("script"),i.type="application/javascript",i.src=a,i.async=!0,document.body.appendChild(i)),i.addEventListener("load",o),i.addEventListener("error",o),()=>{i.removeEventListener("load",o),i.removeEventListener("error",o)}},[e,t]),{BARISTA:i,baristaLoaded:a,baristaLoadingError:o}},te=(e,t,r)=>{const{schema:a}=Y(e),{BARISTA:s,baristaLoaded:o}=ee(),[n,i]=d("ready"),[c,u]=d(null),[l,m]=d(null),[w,p]=d(null),[g,y]=d(null);h(()=>{o&&a&&async function(){const e=await s.Schema.parse(a.data);let r;p(e),t?(r=await s.Submission.parse(t),await r.assignSchema(e,"forceChildren")):r=await new s.Submission(e),p(e),f(r)}()},[a,o]);const f=e=>{y(e),u(e.toFrontEnd()),r(e.toString())},E=()=>{u(g.toFrontEnd()),r(g.toString())};if(!o)return{};async function b(e,t,r){var a;r instanceof File&&(r=await(a=r,new Promise(e=>{const t=new FileReader;t.onload=t=>e(t.target.result),t.readAsDataURL(a)})));const s=function(e,t){return c.find(t=>t.id===e).keys.find(e=>e.id===t)}(e,t);s.setValue(r),E()}function S(e){i(c.length>0&&c[0].hasProposals()?"actionRequired":e)}async function I(e,t){const r=function(e){return c.find(t=>t.id===e)}(e);r.acceptProposal(t),S("ready"),E()}async function v(){i("pending");try{const e=await g.computeRules(!0);if(E(),0===e.length)return S("ok");const{corrected:t,notCorrected:r,withProposals:a}=await g.correctRules(2);m({corrected:t,notCorrected:r,withProposals:a}),E(),S(0===r.length&&0===a.length?"ok":"ready")}catch(e){i("error")}}async function R(e){const t=await s.Submission.reconstructFromZip(e,w,!0);f(t)}async function T(){const e=await g.convertToZip(),t=URL.createObjectURL(e),r=document.createElement("a");r.href=t,r.download="submission.zip",document.body.appendChild(r),r.click(),window.URL.revokeObjectURL(t),document.body.removeChild(r)}return{acceptProposal:I,baristaAcceptProposal:I,baristaComputeRules:v,baristaCorrectedRules:l,baristaDownloadAsZip:T,baristaProcessZip:R,baristaSchema:w,baristaSetSubmissionStatus:S,baristaSetValue:b,baristaSubmission:g,baristaSubmissionController:c,baristaSubmissionStatus:n,computeRules:v,correctedRules:l,downloadAsZip:T,processZip:R,setSubmissionStatus:S,setValue:b,submissionController:c,submissionStatus:n}},re=e=>{const{getParentCategories:t,createCategory:r,deleteCategory:a,renameCategory:s,getCategories:o}=A(),[n,i]=d(!1),[c,u]=d([]),[l,m]=d(null);return h(()=>{(async(r=!1)=>{if(e){i(r);try{u((await L(t,[e],3e5)).slice(0,-1)),m(await L(o,[e,void 0,{}],3e5)),i(!0)}catch(t){throw console.error("Error fetching category",e,t),new Error(`Error fetching category '${e}'`,{cause:t})}}})()},[e]),y({},l,{category:l,create:async(e,a,s)=>{try{const n=await r(e,a,s);return D("getCategories"),D("getParentCategories"),m(await L(o,[n.id],3e5)),u((await L(t,[n.id],3e5)).slice(0,-1)),n}catch(t){throw console.error(`Error attempting to create category '${e}'`,t),new Error(`Error attempting to create category '${e}'`,{cause:t})}finally{i(!0)}},delete:async()=>{try{if(null==l||!l.id)throw new Error("No category to delete");await a(null==l?void 0:l.id)}catch(e){throw console.error(`Error attempting to delete category '${null==l?void 0:l.name}'`,e),new Error(`Error attempting to delete category '${null==l?void 0:l.name}'`,{cause:e})}},fetched:n,parents:c,rename:async t=>{try{if(null==l||!l.id)throw new Error("No category to rename");const r=await s(null==l?void 0:l.id,t);return m(await L(o,[e],3e5)),r}catch(e){throw console.error(`Error attempting to rename category '${t}'`,e),new Error(`Error attempting to rename category '${t}'`,{cause:e})}}})},ae=(e,t={})=>{const{getCategories:r,createCategory:a}=A(),[s,o]=d(!1),[n,i]=d([]),[c,u]=d(!0),{appendNextPage:l,refreshLastPage:m,checkHasMore:w,currentPage:p}=_(i,u,c,null==t?void 0:t.page,null==t?void 0:t.limit),g=async(t=!1)=>{o(t);try{const t=w(await r(void 0,e));return i(t),t}catch(e){throw console.error("Error fetching categories",e),new Error("Error fetching categories",{cause:e})}finally{o(!0)}};return h(()=>{g()},[e,null==t?void 0:t.page]),{categories:n,create:a,currentPage:p,fetchMore:async t=>{try{o(!1),t?await m(async t=>await r(void 0,e,t)):await l(async t=>await r(void 0,e,t))}catch(e){throw console.error("Error fetching more schemas",e),new Error("Error fetching more schemas",{cause:e})}finally{o(!0)}},fetched:s,hasMore:c,refetch:g}};var se;!function(e){e.PUBLIC="public",e.STUDIO_REJECTED="studioRejected",e.STUDIO_ACCEPTED="studioAccepted"}(se||(se={}));const oe=e=>{const{createComment:t,getComment:r,updateComment:a,deleteComment:s}=A(),[o,n]=d(null),[i,c]=d(!1),u=async(t=!1)=>{try{if(!e)throw new Error("No comment to fetch");t||c(!1);const a=await L(r,[e],12e4);return n(a),a}catch(t){throw console.error(`Error fetching comment ${e}`,t),new Error(`Error fetching comment ${e}`,{cause:t})}finally{c(!0)}},l=async(r,a,s)=>{e&&console.warn("It is not intended to create a comment if useComment() is specified with an id!");try{const e=await t(r,a,s);return n(e),D("getUserComments",[e.ownerId]),D("getSubmissionComments",[r]),e}catch(e){throw console.error(`Error creating comment for submission ${r}`,e),new Error(`Error creating comment for submission ${r}`,{cause:e})}};return h(()=>{e&&u()},[e]),y({comment:o},o,{commentBody:(null==o?void 0:o.body)||"",commentId:(null==o?void 0:o.id)||"",commentOwnerId:(null==o?void 0:o.ownerId)||"",commentState:(null==o?void 0:o.state)||"",createApproveComment:async(e,t="")=>await l(e,t,se.STUDIO_ACCEPTED),createComment:async(e,t,r=se.PUBLIC)=>await l(e,t,r),createRejectComment:async(e,t="")=>await l(e,t,se.STUDIO_REJECTED),deleteComment:async()=>{if(!e)throw new Error("No comment to delete");await s(e)},editComment:async t=>{if(!e)throw new Error("No comment to edit");return await a(e,t)},fetched:i,hideComment:async()=>{if(!e)throw new Error("No comment to hide");return await a(e,void 0,"hidden")},moderateComment:()=>a((null==o?void 0:o.id)||"",void 0,"hidden"),refresh:u})},ne=(e,t,r={})=>{const{getUserComments:a,getSubmissionComments:s,updateComment:o,deleteComment:n}=A(),[i,c]=d([]),[u,l]=d(!1),{appendNextPage:m,refreshLastPage:w,currentPage:p,hasMore:g}=_(c,null==r?void 0:r.page,null==r?void 0:r.limit),f=e=>e.map(e=>y({},e,{changeVisibility:()=>v(e.id),delete:()=>S(e.id),edit:t=>I(e.id,t)})),E=async(o=!0,n)=>{if(!e)throw new Error("No scope defined");if(!["submission","owner"].includes(e))throw new Error("Invalid scope");return o?"owner"===e?await L(a,[t,y({},r,n)],12e4):await L(s,[t,y({},r,n)],6e4):"owner"===e?await a(t,y({},r,n)):await s(t,y({},r,n))},b=async()=>{try{l(!1);const e=f(await E());return c(e),e}catch(e){throw console.error(`Error fetching comments for user ${t}`,e),new Error(`Error fetching comments for user ${t}`,{cause:e})}finally{l(!0)}},S=async e=>{try{await n(e),D("getUserComments"),D("getSubmissionComments"),c(t=>t.filter(t=>t.id!==e))}catch(t){throw console.error(`Error deleting comment '${e}'`,t),new Error(`Error deleting comment '${e}'`,{cause:t})}},I=async(e,t)=>{try{const r=await o(e,t);return D("getUserComments"),D("getSubmissionComments"),r}catch(t){throw console.error(`Error editing comment '${e}'`,t),new Error(`Error editing comment '${e}'`,{cause:t})}},v=async e=>{try{var t;const r="public"===(null==(t=i.find(t=>t.id===e))?void 0:t.state)?"hidden":"public",a=await o(e,void 0,r);return D("getSubmissionComments"),D("getUserComments"),a}catch(t){throw console.error(`Error updating comment visibility '${e}'`,t),new Error(`Error updating comment visibility '${e}'`,{cause:t})}};return h(()=>{t&&b()},[e,t,null==r?void 0:r.page]),{comments:i,currentPage:p,fetchMore:async e=>{try{l(!1),e?await w(async e=>f(await E(!1,e))):await m(async e=>f(await E(!0,e)))}catch(e){throw console.error("Error fetching more comments",e),new Error("Error fetching more comments",{cause:e})}finally{l(!0)}},fetched:u,hasMore:g,refresh:b}},ie=(e,t)=>ne("owner",e,t),ce=(e,t)=>ne("submission",e,t),ue=["url","callbackUrl"],le=()=>{const e=new de(C()),{redirectSteam:t,redirectTikTok:r,redirectYouTube:a}=e;return{redirectSteam:t,redirectTikTok:r,redirectYouTube:a}};class de{constructor(e){var t=this;this.idServerUrl=void 0,this.projectId=void 0,this.call=async function(e){let{url:r,callbackUrl:a}=e,s=f(e,ue);return a=window.location.origin+(a||""),t.projectId&&(a=`${a}?projectId=${t.projectId}`),console.log("cbUrl",a),console.log("projectId",t.projectId),await b(`${t.idServerUrl}${r}`,y({},s,{callbackUrl:a}))},this.exports=["redirectSteam","redirectTikTok","redirectYouTube"],this.redirectSteam=async function(e){return await t.call({callbackUrl:e?`/quests/${e}`:"/quests",url:"/auth/redirect/steam"})},this.redirectTikTok=async function(e){return await t.call({callbackUrl:e?`/quests/${e}`:"/quests",url:"/auth/redirect/tiktok"})},this.redirectYouTube=async function(e){return await t.call({callbackUrl:e?`/quests/${e}`:"/quests",url:"/auth/redirect/youtube"})},this.idServerUrl=e.IDSERVER_BASEURL,this.projectId=e.PROJECT_ID}}const he=({params:e,poll:t=!1}={})=>{const{userData:r}=B(),{getNotifications:a,markAllNotificationsAsRead:s,updateNotification:o,deleteNotification:n}=A(),{NOTIFICATIONS_POLL_PERIOD:i}=C(),[c,u]=d(!1),[l,m]=d([]),[w,g]=d([]),[f,E]=d(!0),{appendNextPage:b,refreshLastPage:S,checkHasMore:I,currentPage:v}=_(m,E,f,null==e?void 0:e.page,null==e?void 0:e.limit),R=p(!0),T=p((new Date).toISOString()),$=e=>e.map(e=>y({},e,{delete:async()=>{try{e.isDeleted=!0,await n(e.id)}catch(t){console.error(`Error deleting notification ${e.id}.`,t),e.isDeleted=!1}},isDeleted:!1,markAsSeen:async()=>{try{await o(e.id,{seen:!0}),e.seen=!0}catch(t){console.error(`Error marking notification ${e.id} as seen.`,t)}}})),P=async(t=!1)=>{u(t);try{const t=I($(await a(e)));return m(t),t}catch(e){throw console.error("Error fetching notifications",e),new Error("Error fetching notifications",{cause:e})}finally{u(!0)}};return((e,t)=>{const r=p(()=>{});h(()=>{r.current=e},[e]),h(()=>{if(null!==t){const e=setInterval(function(){null==r.current||r.current()},t);return()=>clearInterval(e)}},[t])})(async()=>{if(!R.current&&t)try{const t=$(await a(y({},e,{startDate:T.current})));g(t),t.length>0&&(T.current=new Date(new Date(t[0].createdAt).getTime()+1).toISOString())}catch(e){console.error("Error fetching notifications",e)}},R.current||!t?null:i>500?i:500),h(()=>(r?(R.current=!1,P()):R.current=!0,()=>{R.current=!0,m([])}),[r]),{currentPage:v,fetchMore:async t=>{try{u(!1),t?await S(async t=>$(await a(y({},e,t)))):await b(async t=>$(await a(y({},e,t))))}catch(e){throw console.error("Error fetching more projects",e),new Error("Error fetching more projects",{cause:e})}finally{u(!0)}},fetched:c,markAllAsRead:async()=>{try{await s(),m(l.map(e=>y({},e,{seen:!0})))}catch(e){throw console.error("Error marking all notifications as read",e),new Error("Error marking all notifications as read",{cause:e})}},notifications:l.filter(e=>!e.isDeleted),refetch:P,toNotify:w}},me=(e={})=>{const{getProjects:t}=A(),[r,a]=d([]),[s,o]=d(!0),{appendNextPage:n,refreshLastPage:i,checkHasMore:c,currentPage:u}=_(a,o,s,null==e?void 0:e.page,null==e?void 0:e.limit),[l,m]=d(!1),w=async()=>{try{m(!1);const r=c(await L(t,[e],6e4));return a(r),r}catch(e){throw console.error("Error fetching projects",e),new Error("Error fetching projects",{cause:e})}finally{m(!0)}};return h(()=>{w()},[null==e?void 0:e.page]),{currentPage:u,fetchMore:async r=>{try{m(!1),r?await i(async r=>t(y({},e,r))):await n(async r=>await L(t,[y({},e,r)],6e4))}catch(e){console.error("Error fetching more projects",e)}finally{m(!0)}},fetched:l,hasMore:s,projects:r,refresh:w}},we=e=>{const{createProject:t,getProject:r,updateProject:a,updateProjectConfig:s,updateProjectThumbnail:o}=A();let n=e;const[i,c]=d(null),[u,l]=d(!1),[m,w]=d(null),[p,g]=d(null),f=async(e=p)=>{try{if(!e)throw new Error("No config to update");await s(e,n),D("getProject",[n])}catch(e){throw console.error("Error updating config",e),new Error(`Error updating config from project '${n}'`,{cause:e})}},E=async(e=m)=>{if(e&&"string"!=typeof e)try{await o(e,n),D("getProject",[n])}catch(e){throw console.error("Error updating thumbnail",e),new Error(`Error updating thumbnail from project '${n}'`,{cause:e})}},b=async(e=!1)=>{l(e);try{const e=await L(r,[n],6e4);return c(e),e}catch(e){throw console.error("Error fetching project",n,e),new Error(`Error fetching project '${n}'`,{cause:e})}finally{l(!0)}};return h(()=>{b()},[n]),y({},i,{fetched:u,project:i,push:async e=>{e=y({},i,e);try{var r;if(!e)throw new Error("No project to push");if(!e.name)throw new Error("Missing required parameters 'name' for project.");const{name:s,hidden:o,gameEngine:i,numMonthlyUsers:u,platform:l,newThumbnailFile:d}=e,h={gameEngine:i,hidden:o,name:s,numMonthlyUsers:u,platform:l};let w;if(n?(w=await a(h,n),D("getProject",[n])):w=await t(h),!w)throw new Error("Project not pushed");return n=null==(r=w)?void 0:r.id,p&&await f(),(d||m)&&await E(d||m),c(w),w}catch(e){throw console.error(`Error pushing project ${(null==i?void 0:i.id)||""}`,e),new Error(`Error pushing project ${(null==i?void 0:i.id)||""}`,{cause:e})}},pushNewOwner:async e=>{try{const{ownerId:t}=await a({ownerUsername:e});t&&c(y({},i,{ownerId:t})),D("getProject",[n])}catch(e){throw console.error("Error updating owner",e),new Error(`Error updating owner from project '${n}'`,{cause:e})}},pushThumbnail:E,refresh:b,setConfig:g,setThumbnail:w,updateConfig:f})},pe=e=>{const{completeQuest:t,createQuest:r,updateQuest:a,deleteQuest:s,getQuest:o}=A(),[n,i]=d(null),[c,u]=d(!e),l=async(t=!1,r)=>{t||u(!1),r&&D("getQuest",[e]);try{if(!e)throw new Error("No quest id provided");const t=await L(o,[e],12e4);return i(t),t}catch(t){throw console.error(`Error fetching quest ${e}`,t),new Error(`Error fetching quest ${e}`,{cause:t})}finally{u(!0)}};return h(()=>{e&&l()},[e]),{complete:async e=>{if(null==n||!n.id)throw new Error("No quest to complete");try{const r=n.id,a=await t(r,e);return D("getUserQuests"),D("getUserQuestsByQuest"),D("getUserQuestsByProject"),a}catch(e){throw console.error(`Error completing quest '${n.id}'`,e),new Error(`Error completing quest '${n.id}'`,{cause:e})}},delete:async()=>{if(null==n||!n.id)throw new Error("No quest to delete");try{s(n.id),D("getQuest",[n.id]),D("getQuests")}catch(e){throw console.error("Error deleting quest",e),new Error("Error deleting quest",{cause:e})}},fetched:c,push:async t=>{const s=y({},n,t);if(!s)throw new Error("No quest to push");try{const t=e?await a(e,s):await r(s);if(!t)throw new Error("Failed to push quest");return i(t),D("getQuest",[t.id]),D("getQuests"),t}catch(e){throw console.error("Error pushing quest",e),new Error("Error pushing quest",{cause:e})}},quest:n,refresh:e=>l(e,!0)}},ge=(e={})=>{const{completeQuest:t,getQuests:r,deleteQuest:a,updateQuest:s}=A(),[o,n]=d([]),[i,c]=d(!1),u=async(t=!1,a)=>{t||c(!1),a&&D("getQuests");try{const t=(e=>e.map(e=>y({},e,{complete:t=>w(e.id,t),delete:()=>m(e.id),push:t=>l(e.id,t)})))(await L(r,[e],12e4));return n(t),t}catch(e){throw console.error("Error fetching quests",e),new Error("Error fetching quests",{cause:e})}finally{c(!0)}},l=async(e,t)=>{try{const o=await s(e,t);if(!o)throw new Error("Quest not uploaded");return r=e,a=o,n(e=>e.map(e=>e.id===r?y({},e,a):e)),D("getQuests"),o}catch(t){throw console.error(`Error pushing quest '${e}'`,t),new Error(`Error pushing quest '${e}'`,{cause:t})}var r,a},m=async e=>{try{await a(e),n(t=>t.filter(t=>t.id!==e)),D("getQuests")}catch(t){throw console.error(`Error deleting quest '${e}'`,t),new Error(`Error deleting quest '${e}'`,{cause:t})}},w=async(e,r)=>{try{const a=await t(e,r);return D("getUserQuests"),D("getUserQuestsByQuest"),D("getUserQuestsByProject"),a}catch(t){throw console.error(`Error completing quest '${e}'`,t),new Error(`Error completing quest '${e}'`,{cause:t})}};return h(()=>{u()},[JSON.stringify(e)]),{fetched:i,questList:o,quests:o,refresh:e=>u(e,!0)}},ye=e=>{const{getQuestType:t}=A(),[r,a]=d(null),[s,o]=d(!1),n=async(r=!1,s=!1)=>{r||o(!1),s&&D("getQuestType",[e]);try{if(!e)throw new Error("No id provided");const r=await L(t,[e],3e5);return a(r),r}catch(t){throw console.error(`Error fetching quest type ${e}`,t),new Error(`Error fetching quest type ${e}`,{cause:t})}finally{o(!0)}};return h(()=>{n()},[e]),{fetched:s,questType:r,refresh:e=>n(e,!0)}},fe=(e={})=>{const{getQuestTypes:t}=A(),[r,a]=d([]),[s,o]=d(!1),n=async(r=!1)=>{r||o(!1);try{const r=await L(t,[e],3e5);return a(r),r}catch(e){throw console.error("Error fetching quest types",e),new Error("Error fetching quest types",{cause:e})}finally{o(!0)}};return h(()=>{n()},[JSON.stringify(e)]),{fetched:s,questTypes:r,questTypesList:r,refresh:e=>n(e)}},Ee=(e={})=>{const{getQuestTypeCategories:t}=A(),[r,a]=d([]),[s,o]=d(!1),n=async(r=!1,s)=>{r||o(!1),s&&D("getQuestTypeCategories",[e]);try{const r=await L(t,[e],3e5);return a(r),r}catch(e){throw console.error("Error fetching quest type categories",e),new Error("Error fetching quest type categories",{cause:e})}finally{o(!0)}};return h(()=>{n()},[JSON.stringify(e)]),{categories:r,fetched:s,refresh:e=>n(e,!0)}},be=e=>{const{getReward:t,createReward:r,updateReward:a,deleteReward:s,redeemReward:o}=A(),[n,i]=d(null),[c,u]=d(!1),l=async(r=!1,a)=>{r||u(!1),a&&D("getReward",[e]);try{if(!e)throw new Error("No reward to fetch");const r=await L(t,[e],12e4);return i(r),r}catch(e){throw console.error("Error fetching reward",e),new Error("Error fetching reward",{cause:e})}finally{u(!0)}};return h(()=>{e&&l()},[e]),{createReward:async t=>{const a=y({},n,t);if(!a)throw new Error("No reward to create");try{const t=await r(a);return i(t),D("getReward",[e]),D("getRewardsByProject"),t}catch(e){throw console.error("Error while creating reward",e),new Error("Error while creating reward",{cause:e})}},deleteReward:async()=>{try{if(null==n||!n.id)throw new Error("No reward to delete");await s(n.id),i(null),D("getReward",[e]),D("getRewardsByProject")}catch(e){throw console.error("Error deleting reward",e),new Error("Error deleting reward",{cause:e})}},fetched:c,redeemReward:async()=>{try{const t=(null==n?void 0:n.id)||e;if(!t)throw new Error("No reward to redeem");const r=await o(t);return D("getReward",[e]),D("getRewardsByProject"),r}catch(e){throw console.error("Error redeeming reward",e),new Error("Error redeeming reward",{cause:e})}},refresh:e=>l(e,!0),reward:n,setReward:i,updateReward:async t=>{try{if(null==n||!n.id)throw new Error("No reward to update");const r=await a(n.id,t);return i(r),D("getReward",[e]),D("getRewardsByProject"),r}catch(e){throw console.error("Error updating reward",e),new Error("Error updating reward",{cause:e})}}}},Se=(e,t={})=>{const{getRewardsByProject:r,updateReward:a,deleteReward:s,redeemReward:o}=A(),[n,i]=d([]),[c,u]=d(!1),l=async(a=!1,s)=>{a||u(!1),s&&D("getRewardsByProject");try{const a=(e=>e.map(e=>y({},e,{delete:()=>p(e.id),push:t=>w(e.id,t),redeem:()=>m(e.id)})))(await L(r,[t,e],12e4));return i(a),a}catch(e){throw console.error("Error fetching rewards",e),new Error("Error fetching rewards",{cause:e})}finally{u(!0)}},m=async e=>{try{if(!e)throw new Error("No reward to redeem");const t=await o(e);return D("getRewardsByProject"),t}catch(e){throw console.error("Error redeeming reward",e),new Error("Error redeeming reward",{cause:e})}},w=async(e,t)=>{try{const o=await a(e,t);if(!o)throw new Error("Reward not uploaded");return r=e,s=o,i(e=>e.map(e=>e.id===r?y({},e,s):e)),D("getRewardsByProject"),o}catch(t){throw console.error(`Error pushing reward '${e}'`,t),new Error(`Error pushing reward '${e}'`,{cause:t})}var r,s},p=async e=>{try{await s(e),i(t=>t.filter(t=>t.id!==e)),D("getRewardsByProject")}catch(t){throw console.error(`Error deleting reward '${e}'`,t),new Error(`Error deleting reward '${e}'`,{cause:t})}};return h(()=>{l()},[e,JSON.stringify(t)]),{fetched:c,refresh:e=>l(e,!0),rewardList:n,rewards:n}},Ie=e=>{const{getRewardType:t}=A(),[r,a]=d(null),[s,o]=d(!1),n=async(r=!1,s)=>{r||o(!1),s&&D("getRewardType",[e]);try{if(!e)throw new Error("No reward type to fetch");const r=await L(t,[e],12e4);return a(r),r}catch(e){throw console.error("Error fetching reward type",e),new Error("Error fetching reward type",{cause:e})}finally{o(!1)}};return h(()=>{e&&n()},[e]),{fetched:s,refresh:e=>n(e,!0),rewardType:r}},ve=(e={})=>{const{getRewardTypes:t}=A(),[r,a]=d([]),[s,o]=d(!1),n=async(r=!1,s)=>{r||o(!1),s&&D("getRewardTypes");try{const r=await L(t,[e],3e5);return a(r),r}catch(e){throw console.error("Error fetching reward types",e),new Error("Error fetching reward types",{cause:e})}finally{o(!0)}};return h(()=>{n()},[JSON.stringify(e)]),{fetched:s,refresh:e=>n(e,!0),rewardTypes:r}},Re=["submissions"],Te=(e,t=!1)=>{const{createSubmission:r,getSubmission:a,updateSubmission:s,deleteSubmission:o}=A(),{createApproveComment:n,createRejectComment:i}=oe(),[c,u]=d(e),[l,m]=d(!1),[w,p]=d({}),[g,f]=d([]),[E,b]=d(!1),[S,I]=d(null),[v,R]=d(!1),{SUBMISSION_UPLOAD_POLL_PERIOD:T,SUBMISSION_UPLOAD_TIMEOUT:$}=C(),P=()=>{u(e),p({description:"",name:"",postTitle:"",schemaId:"",state:""})},j=async(e=!1)=>{if(!c)return P();try{var t;b(e);const r=await a(c);return I(null==(t=r.state)?void 0:t.startsWith("pending")),p(r),b(!0),r}catch(e){console.error(`Error fetching submission ${c}`,e)}};h(()=>{j()},[c,l]),h(()=>{const e=async(t=Date.now())=>{var r;if(null==(r=(await j()).state)||!r.startsWith("pending"))return;const a=Date.now()-t;$&&a>$?R(!0):setTimeout(()=>e(t),T)};t&&S&&e()},[S]);const U=async e=>{p(e=>y({},e,{state:"approved"})),await O({state:"approved"})?void 0!==e&&await n(w.id,e):m(e=>!e)},N=async e=>{p(e=>y({},e,{state:"rejected"})),await O({state:"rejected"})?void 0!==e&&await i(w.id,e):m(e=>!e)},O=async(e,t=!1)=>{if(!(e=y({},w,e)))return void console.error("No submission to push");if(!e.name||!e.postTitle||!e.schemaId)return void console.error(`Missing required parameters for ${w.id||""} submission. `+(e.name?"":"Name is missing. ")+(e.schemaId?"":"schemaId is missing. "));const a={description:e.description||"",name:e.name,postTitle:e.postTitle,schemaId:e.schemaId,state:e.state||"draft"};try{let e;if(e=c?await s(c,a,g):await r(a,g),!e)throw new Error("Submission not created");return p(e),u(e.id),t&&m(e=>!e),e}catch(e){console.error(`Error pushing submission ${w.id||""}`,e)}};return y({submission:w}