UNPKG

baqend

Version:

Baqend JavaScript SDK

2 lines 122 kB
/*! baqend 4.2.6 | Copyright (c) 2021 Baqend GmbH | License information baqend.es2015.min.js.LICENSE.txt */ var Baqend=function(e){var t={};function n(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return e[s].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(s,r,function(t){return e[t]}.bind(null,r));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=21)}([function(e,t,n){"use strict";n.r(t),n.d(t,"Message",(function(){return s.b})),n.d(t,"OAuthMessage",(function(){return s.c})),n.d(t,"StatusCode",(function(){return s.d})),n.d(t,"Connector",(function(){return i})),n.d(t,"FetchConnector",(function(){return a.FetchConnector})),n.d(t,"XMLHttpConnector",(function(){return c})),n.d(t,"IFrameConnector",(function(){return u})),n.d(t,"NodeConnector",(function(){return d.NodeConnector}));var s=n(11),r=n(5);class i{static isUsable(e,t,n,s){return!1}static create(e,t,n,s){let r=e,a=t,o=n,c=s;if("undefined"!=typeof location&&(r||(r=location.hostname,a=Number(location.port)),void 0===o&&(o="https:"===location.protocol)),o=void 0===o||!!o,void 0===c&&(c=i.DEFAULT_BASE_PATH),-1!==r.indexOf("/")){const e=/^(https?):\/\/([^/:]+|\[[^\]]+])(:(\d*))?(\/\w+)?\/?$/.exec(r);if(!e)throw new Error(`The connection uri host ${r} seems not to be valid`);o="https"===e[1],r=e[2].replace(/(\[|])/g,""),a=Number(e[4]),c=e[5]||""}else"localhost"!==r&&/^[a-z0-9-]*$/.test(r)&&(r+=i.HTTP_DOMAIN);a||(a=o?443:80);const u=i.toUri(r,a,o,c);let d=this.connections[u];if(!d){for(let e=this.connectors.length-1;e>=0;e-=1){const t=this.connectors[e];if(t.isUsable&&t.isUsable(r,a,o,c)){d=new t(r,a,o,c);break}}if(!d)throw new Error("No connector is usable for the requested connection.");this.connections[u]=d}return d}static toUri(e,t,n,s){let r=(n?"https://":"http://")+(-1!==e.indexOf(":")?`[${e}]`:e);return r+=n&&443!==t||!n&&80!==t?":"+t:"",r+=s,r}constructor(e,t,n,s){this.host=e,this.port=t,this.secure=n,this.basePath=s,this.origin=i.toUri(this.host,this.port,this.secure,"")}send(e){let t={status:0,headers:{}};return Promise.resolve().then(()=>this.prepareRequest(e)).then(()=>new Promise(t=>{this.doSend(e,e.request,t)})).then(e=>{t=e}).then(()=>this.prepareResponse(e,t)).then(()=>(e.doReceive(t),t)).catch(e=>{throw t.entity=null,r.PersistentError.of(e)})}prepareRequest(e){if(!e.mimeType()){const{type:t}=e.request;"json"===t?e.mimeType("application/json;charset=utf-8"):"text"===t?e.mimeType("text/plain;charset=utf-8"):"stream"===t&&e.mimeType("application/octet-stream")}let t;switch(this.toFormat(e),e.responseType()){case"json":t="application/json";break;case"text":t="text/*";break;default:t="application/json,text/*;q=0.5,*/*;q=0.1"}e.accept()||e.accept(t);const n=e.tokenStorage();if(n){const{token:t}=n;t&&e.header("authorization","BAT "+t)}return e}prepareResponse(e,t){let n;t.status=1223===t.status?204:t.status;const s=t.headers||{},r=204===t.status?null:t.entity;if(r&&(n=e.responseType(),!n||t.status>=400)){const e=s["content-type"]||s["Content-Type"];e&&e.indexOf("application/json")>-1&&(n="json")}s.etag&&(s.etag=s.etag.replace(/--\w+/,""));const i=e.tokenStorage();if(i){const e=s["baqend-authorization-token"]||s["Baqend-Authorization-Token"];e&&i.update(e)}return new Promise(e=>{e(r&&this.fromFormat(t,r,n))}).then(e=>{t.entity=e},e=>{throw new Error(`Response was not valid ${n}: ${e.message}`)})}}i.DEFAULT_BASE_PATH="/v1",i.HTTP_DOMAIN=".app.baqend.com",i.RESPONSE_HEADERS=["baqend-authorization-token","content-type","baqend-size","baqend-acl","etag","last-modified","baqend-created-at","baqend-custom-headers","Baqend-MFA-Auth-Token"],i.connectors=[],i.connections={};var a=n(18),o=n(4);class c extends i{static isUsable(e,t,n,s){return"undefined"!=typeof XMLHttpRequest}doSend(e,t,n){if("OAUTH"===t.method){this.oAuthHandle&&this.oAuthHandle({status:409,headers:{},entity:'{"message": "A new OAuth request was sent."}'}),localStorage.removeItem("oauth-response");const e=e=>{"oauth-response"===e.key&&this.oAuthHandle&&e.newValue&&this.oAuthHandle(JSON.parse(e.newValue))};return this.oAuthHandle=t=>{n(t),localStorage.removeItem("oauth-response"),removeEventListener("storage",e,!1)},void addEventListener("storage",e,!1)}const s=new XMLHttpRequest,r=this.origin+this.basePath+t.path;s.onreadystatechange=()=>{if(s.responseType&&2===s.readyState&&s.status>=400&&(s.responseType="text"),4===s.readyState){const e={headers:{},status:s.status,entity:s.response||s.responseText};i.RESPONSE_HEADERS.forEach(t=>{e.headers[t]=s.getResponseHeader(t)||""}),n(e)}},s.upload&&e.progress()&&(s.upload.onprogress=e.progress()),s.onerror=e=>{n({status:0,headers:{},error:new Error(`Fetch of ${r} failed with a network error ${e}`)})},s.open(t.method,r,!0);const{entity:a}=t,{headers:o}=t,c=Object.keys(o);for(let e=0,t=c.length;e<t;e+=1){const t=c[e];s.setRequestHeader(t,o[t])}switch(s.withCredentials=e.withCredentials,e.responseType()){case"arraybuffer":s.responseType="arraybuffer";break;case"blob":case"data-url":case"base64":s.responseType="blob"}s.send(a)}fromFormat(e,t,n){if("json"===n)return JSON.parse(t);if("data-url"===n||"base64"===n){const e=new FileReader;return e.readAsDataURL(t),new Promise((t,n)=>{e.onload=t,e.onerror=n}).then(()=>{let{result:t}=e;return"base64"===n&&"string"==typeof t&&(t=t.substring(t.indexOf(",")+1)),t})}return t}toFormat(e){let{type:t}=e.request;if(t){let{entity:n}=e.request,s=e.mimeType();switch(t){case"blob":s=s||n.type;break;case"arraybuffer":case"form":break;case"data-url":{const e=n.match(/^data:(.+?)(;base64)?,(.*)$/),r=e[2];if(n=e[3],t="blob",s=s||e[1],!r){n=decodeURIComponent(n);break}}case"base64":{const e=Object(o.atob)(n),r=e.length,i=new Uint8Array(r);for(let t=0;t<r;t+=1)i[t]=e.charCodeAt(t);t="blob",n=new Blob([i],{type:s});break}case"json":"string"!=typeof n&&(n=JSON.stringify(n));break;case"text":break;default:throw new Error("Supported request format:"+t)}e.entity(n,t).mimeType(s)}}}i.connectors.push(c);class u extends c{static isUsable(e,t,n){if("undefined"==typeof location||"undefined"==typeof document)return!1;const s="https:"===location.protocol,r=location.port||(s?443:80);return location.hostname!==e||r!==t||s!==n}constructor(e,t,n,s){super(e,t,n,s),this.queue=null,this.connected=!1,this.mid=0,this.messages={},this.doReceive=this.doReceive.bind(this),addEventListener("message",this.doReceive,!1)}load(e){var t;const n=this.origin+this.basePath+e.path(),s="baqend-sdk-connect-"+Math.floor(1e5*Math.random());this.iframe=document.createElement("iframe"),this.iframe.name=s,this.iframe.setAttribute("style",u.style),document.body.appendChild(this.iframe);const r=document.createElement("form");r.target=s,r.method="post",r.action=n,r.setAttribute("style",u.style);const i=null===(t=e.tokenStorage())||void 0===t?void 0:t.token;if(i){const e=document.createElement("input");e.type="hidden",e.name="BAT",e.value=i,r.appendChild(e)}document.body.appendChild(r),this.queue=[],this.iframe.addEventListener("load",this.onLoad.bind(this),!1),r.submit()}onLoad(){if(!this.queue)return;const{queue:e}=this;for(let t=0;t<e.length;t+=1)this.postMessage(e[t]);this.queue=null}doSend(e,t,n){if(e.isBinary)return void super.doSend(e,t,n);this.iframe||(e.request.path="/connect",this.load(e));const s={mid:this.mid+=1,method:t.method,path:t.path,headers:t.headers,entity:t.entity,responseHeaders:i.RESPONSE_HEADERS};this.messages[s.mid]=n;const r=JSON.stringify(s);this.queue?this.queue.push(r):this.postMessage(r),this.connected||setTimeout(()=>{this.messages[s.mid]&&(delete this.messages[s.mid],n({status:0,error:new Error("Connection refused."),headers:{}}))},1e4)}postMessage(e){this.iframe.contentWindow.postMessage(e,this.origin)}doReceive(e){if(e.origin!==this.origin||"{"!==e.data[0])return;const t=JSON.parse(e.data),n=this.messages[t.mid];n&&(delete this.messages[t.mid],this.connected=!0,n({status:t.status,headers:t.headers,entity:t.entity}))}}u.style="width:1px;height:1px;position:absolute;top:-10px;left:-10px;",i.connectors.push(u);var d=n(19)},function(e,t,n){"use strict";n.r(t),n.d(t,"ListAllResources",(function(){return r})),n.d(t,"ApiVersion",(function(){return i})),n.d(t,"Specification",(function(){return a})),n.d(t,"GetBloomFilter",(function(){return o})),n.d(t,"GetBloomFilterExpirations",(function(){return c})),n.d(t,"DeleteBloomFilter",(function(){return u})),n.d(t,"GetOrestesConfig",(function(){return d})),n.d(t,"UpdateOrestesConfig",(function(){return h})),n.d(t,"Connect",(function(){return l})),n.d(t,"ConnectViaPost",(function(){return p})),n.d(t,"Status",(function(){return f})),n.d(t,"BannedIp",(function(){return g})),n.d(t,"Banned",(function(){return y})),n.d(t,"Unban",(function(){return m})),n.d(t,"UnbanIp",(function(){return b})),n.d(t,"GetBucketNames",(function(){return w})),n.d(t,"GetBucketIds",(function(){return O})),n.d(t,"ExportBucket",(function(){return E})),n.d(t,"ImportBucket",(function(){return T})),n.d(t,"TruncateBucket",(function(){return S})),n.d(t,"CreateObject",(function(){return v})),n.d(t,"GetObject",(function(){return M})),n.d(t,"ReplaceObject",(function(){return A})),n.d(t,"DeleteObject",(function(){return k})),n.d(t,"GetAllSchemas",(function(){return P})),n.d(t,"UpdateAllSchemas",(function(){return _})),n.d(t,"ReplaceAllSchemas",(function(){return C})),n.d(t,"GetSchema",(function(){return D})),n.d(t,"UpdateSchema",(function(){return N})),n.d(t,"ReplaceSchema",(function(){return I})),n.d(t,"DeleteSchema",(function(){return x})),n.d(t,"AdhocQuery",(function(){return R})),n.d(t,"AdhocQueryPOST",(function(){return F})),n.d(t,"AdhocCountQuery",(function(){return B})),n.d(t,"AdhocCountQueryPOST",(function(){return j})),n.d(t,"ListQueryResources",(function(){return L})),n.d(t,"CreateQuery",(function(){return q})),n.d(t,"ListThisQueryResources",(function(){return U})),n.d(t,"GetQueryCode",(function(){return J})),n.d(t,"RunQuery",(function(){return $})),n.d(t,"GetQueryParameters",(function(){return V})),n.d(t,"UpdatePartially",(function(){return G})),n.d(t,"UpdateField",(function(){return z})),n.d(t,"Login",(function(){return H})),n.d(t,"Register",(function(){return Q})),n.d(t,"Me",(function(){return W})),n.d(t,"ValidateUser",(function(){return Y})),n.d(t,"Logout",(function(){return K})),n.d(t,"NewPassword",(function(){return X})),n.d(t,"ResetPassword",(function(){return Z})),n.d(t,"Verify",(function(){return ee})),n.d(t,"ChangeUsername",(function(){return te})),n.d(t,"VerifyUsername",(function(){return ne})),n.d(t,"OAuth2",(function(){return se})),n.d(t,"OAuth1",(function(){return re})),n.d(t,"DeletePassword",(function(){return ie})),n.d(t,"UserToken",(function(){return ae})),n.d(t,"RevokeUserToken",(function(){return oe})),n.d(t,"MFAInitChallenge",(function(){return ce})),n.d(t,"MFAInitFinish",(function(){return ue})),n.d(t,"MFAToken",(function(){return de})),n.d(t,"MFADelete",(function(){return he})),n.d(t,"MFAStatus",(function(){return le})),n.d(t,"AssumeRole",(function(){return pe})),n.d(t,"GetBaqendCode",(function(){return fe})),n.d(t,"SetBaqendCode",(function(){return ge})),n.d(t,"DeleteBaqendCode",(function(){return ye})),n.d(t,"PostBaqendModule",(function(){return me})),n.d(t,"GetBaqendModule",(function(){return be})),n.d(t,"GetAllModules",(function(){return we})),n.d(t,"GetAllCodeContent",(function(){return Oe})),n.d(t,"ListFiles",(function(){return Ee})),n.d(t,"ListBuckets",(function(){return Te})),n.d(t,"DownloadArchive",(function(){return Se})),n.d(t,"UploadPatchArchive",(function(){return ve})),n.d(t,"GetFileBucketMetadata",(function(){return Me})),n.d(t,"SetFileBucketMetadata",(function(){return Ae})),n.d(t,"DeleteFileBucket",(function(){return ke})),n.d(t,"CreateFile",(function(){return Pe})),n.d(t,"DownloadFile",(function(){return _e})),n.d(t,"UploadFile",(function(){return Ce})),n.d(t,"GetFileMetadata",(function(){return De})),n.d(t,"UpdateFileMetadata",(function(){return Ne})),n.d(t,"DeleteFile",(function(){return Ie})),n.d(t,"CreateManifest",(function(){return xe})),n.d(t,"DownloadAsset",(function(){return Re})),n.d(t,"RevalidateAssets",(function(){return Fe})),n.d(t,"EditRevalidationJob",(function(){return Be})),n.d(t,"GetRevalidationStatus",(function(){return je})),n.d(t,"CancelRevalidation",(function(){return Le})),n.d(t,"GetAllRevalidationStatus",(function(){return qe})),n.d(t,"CleanUpAssets",(function(){return Ue})),n.d(t,"CleanUpStorage",(function(){return Je})),n.d(t,"ListIndexes",(function(){return $e})),n.d(t,"CreateDropIndex",(function(){return Ve})),n.d(t,"DropAllIndexes",(function(){return Ge})),n.d(t,"DeviceRegister",(function(){return ze})),n.d(t,"DevicePush",(function(){return He})),n.d(t,"DeviceRegistered",(function(){return Qe})),n.d(t,"VAPIDKeys",(function(){return We})),n.d(t,"VAPIDPublicKey",(function(){return Ye})),n.d(t,"GCMAKey",(function(){return Ke})),n.d(t,"UploadAPNSCertificate",(function(){return Xe})),n.d(t,"ConfigAPI",(function(){return Ze})),n.d(t,"GetInstallationById",(function(){return et})),n.d(t,"CreateNewInstallation",(function(){return tt})),n.d(t,"UpdateInstallationByDomainAndConfigVersion",(function(){return nt})),n.d(t,"UpdateInstallationById",(function(){return st})),n.d(t,"CloneInstallationByDomainAndConfigVersion",(function(){return rt})),n.d(t,"CloneInstallationById",(function(){return it})),n.d(t,"ActivateInstallationByDomainAndConfigVersion",(function(){return at})),n.d(t,"ActivateInstallationById",(function(){return ot})),n.d(t,"FindSpecificInstallation",(function(){return ct})),n.d(t,"GetAllDomains",(function(){return ut})),n.d(t,"DeactivateTestingInstallationById",(function(){return dt})),n.d(t,"Mail",(function(){return ht})),n.d(t,"Ready",(function(){return lt})),n.d(t,"Live",(function(){return pt})),n.d(t,"Startup",(function(){return ft}));var s=n(0);const r=s.Message.create({method:"GET",path:"/",status:[200]}),i=s.Message.create({method:"GET",path:"/version",status:[200]}),a=s.Message.create({method:"GET",path:"/spec",status:[200]}),o=s.Message.create({method:"GET",path:"/bloomfilter?rules=false",status:[200]}),c=s.Message.create({method:"GET",path:"/bloomfilter/expirations",status:[200]}),u=s.Message.create({method:"DELETE",path:"/bloomfilter?flush=true",status:[204]}),d=s.Message.create({method:"GET",path:"/config",status:[200]}),h=s.Message.create({method:"PUT",path:"/config",status:[200,202]}),l=s.Message.create({method:"GET",path:"/connect",status:[200]}),p=s.Message.create({method:"POST",path:"/connect",status:[200]}),f=s.Message.create({method:"GET",path:"/status",status:[200]}),g=s.Message.create({method:"GET",path:"/banned/:ip",status:[204]}),y=s.Message.create({method:"GET",path:"/banned",status:[]}),m=s.Message.create({method:"DELETE",path:"/banned",status:[204]}),b=s.Message.create({method:"DELETE",path:"/banned/:ip",status:[204]}),w=s.Message.create({method:"GET",path:"/db",status:[200]}),O=s.Message.create({method:"GET",path:"/db/:bucket/ids?start=0&count=-1",status:[200]}),E=s.Message.create({method:"GET",path:"/db/:bucket",status:[200]}),T=s.Message.create({method:"PUT",path:"/db/:bucket",status:[200]}),S=s.Message.create({method:"DELETE",path:"/db/:bucket",status:[200]}),v=s.Message.create({method:"POST",path:"/db/:bucket",status:[201,202]}),M=s.Message.create({method:"GET",path:"/db/:bucket/:oid",status:[200,304]}),A=s.Message.create({method:"PUT",path:"/db/:bucket/:oid",status:[200,202]}),k=s.Message.create({method:"DELETE",path:"/db/:bucket/:oid",status:[202,204]}),P=s.Message.create({method:"GET",path:"/schema",status:[200]}),_=s.Message.create({method:"POST",path:"/schema",status:[200]}),C=s.Message.create({method:"PUT",path:"/schema",status:[200]}),D=s.Message.create({method:"GET",path:"/schema/:bucket",status:[200]}),N=s.Message.create({method:"POST",path:"/schema/:bucket",status:[200]}),I=s.Message.create({method:"PUT",path:"/schema/:bucket",status:[200]}),x=s.Message.create({method:"DELETE",path:"/schema/:bucket",status:[204]}),R=s.Message.create({method:"GET",path:"/db/:bucket/query?q&start=0&count=-1&sort=&eager=&hinted=&triggeredBy=&ttl=",status:[200]}),F=s.Message.create({method:"POST",path:"/db/:bucket/query?start=0&count=-1&sort=&triggeredBy=&ttl=",status:[200]}),B=s.Message.create({method:"GET",path:"/db/:bucket/count?q",status:[200]}),j=s.Message.create({method:"POST",path:"/db/:bucket/count",status:[200]}),L=s.Message.create({method:"GET",path:"/query",status:[200]}),q=s.Message.create({method:"POST",path:"/query",status:[201]}),U=s.Message.create({method:"GET",path:"/query/:qid",status:[200]}),J=s.Message.create({method:"GET",path:"/query/:qid/source",status:[200]}),$=s.Message.create({method:"GET",path:"/query/:qid/result?start=0&count=-1",status:[200]}),V=s.Message.create({method:"GET",path:"/query/:qid/parameters",status:[200]}),G=s.Message.create({method:"POST",path:"/db/:bucket/:oid",status:[200]}),z=s.Message.create({method:"POST",path:"/db/:bucket/:oid/:field",status:[200]}),H=s.Message.create({method:"POST",path:"/db/User/login",status:[200]}),Q=s.Message.create({method:"POST",path:"/db/User/register",status:[200,204]}),W=s.Message.create({method:"GET",path:"/db/User/me",status:[200]}),Y=s.Message.create({method:"GET",path:"/db/User/validate",status:[200]}),K=s.Message.create({method:"GET",path:"/db/User/logout",status:[204]}),X=s.Message.create({method:"POST",path:"/db/User/password",status:[200]}),Z=s.Message.create({method:"POST",path:"/db/User/reset",status:[200]}),ee=s.Message.create({method:"GET",path:"/db/User/verify?token=",status:[204]}),te=s.Message.create({method:"POST",path:"/db/User/changeUsername",status:[204]}),ne=s.Message.create({method:"GET",path:"/db/User/verifyUsername?token=",status:[204]}),se=s.Message.create({method:"GET",path:"/db/User/OAuth/:provider?state=&code=&oauth_verifier=&oauth_token=&error_description=",status:[200]}),re=s.Message.create({method:"GET",path:"/db/User/OAuth1/:provider",status:[200]}),ie=s.Message.create({method:"DELETE",path:"/db/User/password",status:[204]}),ae=s.Message.create({method:"POST",path:"/db/User/:oid/token",status:[200]}),oe=s.Message.create({method:"DELETE",path:"/db/User/:oid/token",status:[204]}),ce=s.Message.create({method:"GET",path:"/db/User/mfa/init",status:[200]}),ue=s.Message.create({method:"POST",path:"/db/User/mfa/init",status:[200]}),de=s.Message.create({method:"POST",path:"/db/User/mfa/token",status:[200]}),he=s.Message.create({method:"DELETE",path:"/db/User/mfa",status:[204]}),le=s.Message.create({method:"GET",path:"/db/User/mfa/status",status:[200]}),pe=s.Message.create({method:"POST",path:"/db/Role/:oid/assume",status:[200]}),fe=s.Message.create({method:"GET",path:"/code/:bucket/:type",status:[200]}),ge=s.Message.create({method:"PUT",path:"/code/:bucket/:type",status:[200,202]}),ye=s.Message.create({method:"DELETE",path:"/code/:bucket/:type",status:[202,204]}),me=s.Message.create({method:"POST",path:"/code/:bucket",status:[200,204]}),be=s.Message.create({method:"GET",path:"/code/:bucket",status:[200,204]}),we=s.Message.create({method:"GET",path:"/code",status:[200]}),Oe=s.Message.create({method:"GET",path:"/code-content",status:[200]}),Ee=s.Message.create({method:"GET",path:"/file/:bucket/ids?path=/&start=&count=-1&deep=false",status:[200]}),Te=s.Message.create({method:"GET",path:"/file/buckets",status:[200]}),Se=s.Message.create({method:"GET",path:"/file",status:[200]}),ve=s.Message.create({method:"POST",path:"/file",status:[200]}),Me=s.Message.create({method:"GET",path:"/file/:bucket",status:[200]}),Ae=s.Message.create({method:"PUT",path:"/file/:bucket",status:[204]}),ke=s.Message.create({method:"DELETE",path:"/file/:bucket",status:[204]}),Pe=s.Message.create({method:"POST",path:"/file/:bucket",status:[200]}),_e=s.Message.create({method:"GET",path:"/file/:bucket/*oid",status:[200,304]}),Ce=s.Message.create({method:"PUT",path:"/file/:bucket/*oid",status:[200]}),De=s.Message.create({method:"HEAD",path:"/file/:bucket/*oid",status:[200]}),Ne=s.Message.create({method:"POST",path:"/file/:bucket/*oid",status:[200]}),Ie=s.Message.create({method:"DELETE",path:"/file/:bucket/*oid",status:[200,204]}),xe=s.Message.create({method:"POST",path:"/pwa/manifest",status:[202]}),Re=s.Message.create({method:"GET",path:"/asset/*url",status:[200,304]}),Fe=s.Message.create({method:"POST",path:"/asset/revalidate",status:[202]}),Be=s.Message.create({method:"POST",path:"/asset/revalidate/:id",status:[204]}),je=s.Message.create({method:"GET",path:"/asset/revalidate/:id",status:[200,202]}),Le=s.Message.create({method:"DELETE",path:"/asset/revalidate/:id",status:[202]}),qe=s.Message.create({method:"GET",path:"/asset/revalidate?state=",status:[200]}),Ue=s.Message.create({method:"POST",path:"/asset/cleanup",status:[202]}),Je=s.Message.create({method:"POST",path:"/asset/cleanup/storage",status:[202]}),$e=s.Message.create({method:"GET",path:"/index/:bucket",status:[200]}),Ve=s.Message.create({method:"POST",path:"/index/:bucket",status:[202]}),Ge=s.Message.create({method:"DELETE",path:"/index/:bucket",status:[202]}),ze=s.Message.create({method:"POST",path:"/db/Device/register",status:[200]}),He=s.Message.create({method:"POST",path:"/db/Device/push",status:[204]}),Qe=s.Message.create({method:"GET",path:"/db/Device/registered",status:[200]}),We=s.Message.create({method:"POST",path:"/config/VAPIDKeys",status:[200]}),Ye=s.Message.create({method:"GET",path:"/config/VAPIDPublicKey",status:[200]}),Ke=s.Message.create({method:"POST",path:"/config/GCMKey",status:[204]}),Xe=s.Message.create({method:"POST",path:"/config/APNSCert",status:[204]}),Ze=s.Message.create({method:"GET",path:"/speedkit/installation/:domain/:configVersion",status:[200]}),et=s.Message.create({method:"GET",path:"/speedkit/installation/:id",status:[200]}),tt=s.Message.create({method:"POST",path:"/speedkit/installation/:domain",status:[200]}),nt=s.Message.create({method:"PUT",path:"/speedkit/installation/:domain/:configVersion",status:[200]}),st=s.Message.create({method:"PUT",path:"/speedkit/installation/:id",status:[200]}),rt=s.Message.create({method:"POST",path:"/speedkit/installation/:domain/:configVersion/clone",status:[200]}),it=s.Message.create({method:"POST",path:"/speedkit/installation/:id/clone",status:[200]}),at=s.Message.create({method:"POST",path:"/speedkit/installation/:domain/:configVersion/activate?testing=",status:[200]}),ot=s.Message.create({method:"POST",path:"/speedkit/installation/:id/activate?testing=",status:[200]}),ct=s.Message.create({method:"GET",path:"/speedkit/installation?domain=&status=&start=0&count=-1",status:[200]}),ut=s.Message.create({method:"GET",path:"/speedkit/installation/domain",status:[200]}),dt=s.Message.create({method:"PUT",path:"/speedkit/installation/:id/deactivate?force=",status:[200]}),ht=s.Message.create({method:"POST",path:"/mail",status:[200]}),lt=s.Message.create({method:"GET",path:"/-/ready",status:[200]}),pt=s.Message.create({method:"GET",path:"/-/live",status:[200]}),ft=s.Message.create({method:"GET",path:"/-/startup",status:[200]})},function(e,t,n){"use strict";n.r(t),n.d(t,"Metadata",(function(){return o})),n.d(t,"MetadataState",(function(){return s})),n.d(t,"Permission",(function(){return c.a})),n.d(t,"Validator",(function(){return h})),n.d(t,"ValidationResult",(function(){return p})),n.d(t,"Code",(function(){return y})),n.d(t,"Modules",(function(){return m})),n.d(t,"Logger",(function(){return b})),n.d(t,"PushMessage",(function(){return O})),n.d(t,"TokenStorage",(function(){return E})),n.d(t,"GlobalStorage",(function(){return T})),n.d(t,"WebStorage",(function(){return S}));var s,r=n(8),i=n(4),a=n(5);!function(e){e[e.UNAVAILABLE=-1]="UNAVAILABLE",e[e.PERSISTENT=0]="PERSISTENT",e[e.DIRTY=1]="DIRTY"}(s||(s={}));class o extends i.Lockable{static create(e,t){if(e.isEntity)return new o(e);if(e.isEmbeddable)return{type:e,db:t,setDirty(){}};throw new Error("Illegal type "+e)}static get(e){return e._metadata}get db(){return this.entityManager||(this.entityManager=n(10).db),this.entityManager}set db(e){if(this.entityManager)throw new Error("DB has already been set.");this.entityManager=e}get bucket(){return this.type.name}get key(){if(!this.decodedKey&&this.id){const e=this.id.lastIndexOf("/");this.decodedKey=decodeURIComponent(this.id.substring(e+1))}return this.decodedKey}set key(e){const t=""+e;if(this.id)throw new Error("The id can't be set twice.");this.id=`/db/${this.bucket}/${encodeURIComponent(t)}`,this.decodedKey=t}get isAttached(){return!!this.entityManager}get isAvailable(){return this.state>s.UNAVAILABLE}get isPersistent(){return this.state===s.PERSISTENT}get isDirty(){return this.state===s.DIRTY}constructor(e){super(),this.entityManager=null,this.decodedKey=null,this.id=null,this.state=s.DIRTY,this.enabled=!0,this.id=null,this.version=null,this.type=e,this.acl=new r.a}enable(e){this.enabled=e}throwUnloadedPropertyAccess(e){if(this.enabled&&!this.isAvailable)throw new a.PersistentError(`Illegal property access on ${this.id}#${e} , ensure that this reference is loaded before it's properties are accessed.`)}setUnavailable(){this.state=s.UNAVAILABLE}setPersistent(){this.state=s.PERSISTENT}setDirty(){this.state=s.DIRTY}setRemoved(){this.isAvailable&&(this.setDirty(),this.version=null)}}var c=n(17);const u={};let d=u;try{d=n(20)}catch(e){}class h{static compile(e,t){const n=[],s=e.attributes();for(let e=s.next();!e.done;e=s.next()){const t=e.value;n.push(t.name)}const r=new Function(...n,t);return function(e){if(d===u)throw new Error("Validation code will not be executed. Make sure that the validator package is correctly provided as an external dependency.");const t=n.map(t=>e[t]);return r.apply({},t)}}get value(){return this.entity[this.key]}get isValid(){return 0===this.errors.length}is(e,t){return e instanceof Function?this.is("is",e):(!1===t(this.value,d)&&this.errors.push(e),this)}constructor(e,t){this.errors=[],this.key=e,this.entity=t}callMethod(e,t,n){const s=n||[];try{s.unshift(this.toStringValue()),!1===d[e].apply(this,s)&&this.errors.push(t||e)}catch(e){this.errors.push(t||e.message)}return this}toStringValue(){const{value:e}=this;return"string"==typeof e||e instanceof Date?e:JSON.stringify(e)}toJSON(){return{isValid:this.isValid,errors:this.errors}}}const l=["contains","equals","matches"];Object.keys(d).forEach(e=>{(e.startsWith("is")||l.includes(e))&&(h.prototype[e]=function(...t){const n="string"==typeof t[0]?t.shift():null;return this.callMethod(e,n,t)})});class p{constructor(){this.fields={}}get isValid(){return Object.keys(this.fields).every(e=>this.fields[e].isValid)}toJSON(){const e={};return Object.keys(this.fields).forEach(t=>{e[t]=this.fields[t].toJSON()}),e}}var f=n(1),g=n(0);class y{constructor(e,t){this.metamodel=e,this.entityManagerFactory=t}functionToString(e){if(!e)return"";let t=e.toString();return t=t.substring(t.indexOf("{")+1,t.lastIndexOf("}")),"\n"===t.charAt(0)&&(t=t.substring(1)),"\n"===t.charAt(t.length-1)&&(t=t.substring(0,t.length-1)),t}stringToFunction(e,t){return new Function(e,t)}loadModules(){const e=new f.GetAllModules;return this.entityManagerFactory.send(e).then(e=>e.entity)}loadCode(e,t,n=!1){const s="string"==typeof e?e:e.name,r=new f.GetBaqendCode(s,t).responseType("text");return this.entityManagerFactory.send(r).then(e=>this.parseCode(s,t,n,e.entity),e=>{if(e.status===g.StatusCode.OBJECT_NOT_FOUND)return null;throw e})}saveCode(e,t,n){const s="string"==typeof e?e:e.name,r=new f.SetBaqendCode(s,t).entity(n instanceof Function?this.functionToString(n):n,"text").responseType("text");return this.entityManagerFactory.send(r).then(e=>this.parseCode(s,t,n instanceof Function,e.entity))}deleteCode(e,t){const n="string"==typeof e?e:e.name,s=new f.DeleteBaqendCode(n,t);return this.entityManagerFactory.send(s).then(()=>this.parseCode(n,t,!1,null))}parseCode(e,t,n,s){if("validate"===t){const t=this.metamodel.entity(e);return t.validationCode=null===s?null:h.compile(t,s),n?t.validationCode:s}return s&&n?this.stringToFunction(["module","exports"],s):s}}class m{constructor(e){this.entityManager=e}get(e,t,n,s,r){if(t instanceof Function)return this.get(e,{},t,n,s);if(n instanceof Function)return this.get(e,t,{},n,s);const i=n||{},a=new f.GetBaqendModule(e).addQueryString(t||"").responseType(i.responseType||null);return this.send(a,s,r)}post(e,t,n,s,r){if("function"==typeof n)return this.post(e,t,{},n,s);const i=n||{},a=new f.PostBaqendModule(e).entity(t,i.requestType).mimeType(i.mimeType||null).responseType(i.responseType||null);return this.send(a,s,r)}send(e,t,n){return this.entityManager.send(e).then(e=>e.entity).then(t,n)}}class b{constructor(){this.entityManager=null,this.levelIndex=2}static create(e){const t=this.prototype,n=(()=>{function e(...n){t.log.apply(e,n)}return Object.getOwnPropertyNames(t).forEach(n=>{Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e})();return n.init(e),n}get level(){return b.LEVELS[this.levelIndex]}set level(e){const t=b.LEVELS.indexOf(e);if(-1===t)throw new Error("Unknown logging level "+e);this.levelIndex=t}log(...e){const t=-1===b.LEVELS.indexOf(e[0])?"info":e.shift();if(this.levelIndex>b.LEVELS.indexOf(t))return Promise.resolve(null);let n="string"==typeof e[0]?this.format(e.shift(),e):"[no message]",s=null;if(e.length){const t=e.pop();if(s=t,("object"!=typeof t||Array.isArray(t))&&(s={data:t}),t instanceof Error){const{stack:e,data:n,message:r,name:i,status:a}=t;s={name:i,message:r,stack:e,status:a,data:n}}}return e.length&&(n+=", "+e.join(", ")),this.logJSON(Object.assign({date:(new Date).toISOString(),message:n,level:t,data:s},this.entityManager.me&&{user:this.entityManager.me.id}))}format(e,t){if(0===t.length)return e;return String(e).replace(b.FORMAT_REGEXP,e=>{if("%%"===e)return"%";if(!t.length)return e;switch(e){case"%s":return String(t.shift());case"%d":return String(Number(t.shift()));case"%j":try{return JSON.stringify(t.shift())}catch(e){return"[Circular]"}default:return e}})}init(e){this.entityManager=e,this.levelIndex=2,b.LEVELS.forEach(e=>{this[e]=this.log.bind(this,e)})}logJSON(e){return this.entityManager.isReady?this.entityManager.send(new f.CreateObject("logs.AppLog",e)):this.entityManager.ready(this.logJSON.bind(this,e))}}b.LEVELS=["trace","debug","info","warn","error"],b.FORMAT_REGEXP=/%[sdj%]/g;var w=n(3);class O{constructor(e,t,n,s,r,i){const a="string"==typeof s?{sound:s,badge:r,data:i}:s||{};this.devices=O.initDevices(e),this.message=t,this.subject=n,Object.assign(this,a)}static initDevices(e){if(e instanceof Set)return e;if(e instanceof w.Entity)return new Set([e]);if(!e||e[Symbol.iterator])return new Set(e);throw new Error("Only Sets, Lists and Arrays can be used as devices.")}addDevice(e){this.devices.add(e)}toJSON(){if(!this.devices||!this.devices.size)throw new Error("Set of devices is empty.");return Object.assign({},this,{devices:Array.from(this.devices,e=>e.id)})}}class E{static parse(e){return{val:e,createdAt:1e3*parseInt(e.substring(0,8),16),expireAt:1e3*parseInt(e.substring(8,16),16),sig:e.substring(e.length-40),data:e.substring(0,e.length-40)}}get token(){return this.tokenData?this.tokenData.val:null}static create(e){return Promise.resolve(new E(e))}constructor(e,t,n){this.tokenData=t?E.parse(t):null,this.origin=e,this.temporary=!!n}saveToken(e,t,n){this._saveToken!==E.prototype._saveToken&&(console.log("Using deprecated TokenStorage._saveToken implementation."),this._saveToken(e,t,n))}_saveToken(e,t,n){}update(e){const t=e?E.parse(e):null;this.tokenData&&t&&this.tokenData.expireAt>t.expireAt||(this.tokenData=t,this.saveToken(this.origin,e,this.temporary))}signPath(e,t=!0){const{tokenData:n}=this,s=Promise.resolve(e.split("/").map(encodeURIComponent).join("/"));return n&&t?s.then(e=>E.hmac(e+n.data,n.sig).then(t=>`${e}?BAT=${n.data+t}`)).catch(e=>(console.warn("Can't sign the resource, run the SDK on a secured origin, or provide an alternative hmac implementation on TokenStorage.hmac",e),s)):s}}E.hmac=i.hmac;class T extends E{static create(e){return Promise.resolve(new T(e,T.tokens[e]))}saveToken(e,t,n){n||(t?T.tokens[e]=t:delete T.tokens[e])}}T.tokens={},E.GLOBAL=T;class S extends E{static isAvailable(){try{return"undefined"!=typeof localStorage&&(localStorage.setItem("bq_webstorage_test","bq"),localStorage.removeItem("bq_webstorage_test"),!0)}catch(e){return!1}}static create(e){let t=!1,n=localStorage.getItem("BAT:"+e);return n||"undefined"==typeof sessionStorage||(n=sessionStorage.getItem("BAT:"+e),t=!!n),Promise.resolve(new S(e,n,t))}saveToken(e,t,n){const s=n?sessionStorage:localStorage;t?s.setItem("BAT:"+e,t):s.removeItem("BAT:"+e)}}S.isAvailable()&&(E.WEB_STORAGE=S)},function(e,t,n){"use strict";n.r(t),n.d(t,"Accessor",(function(){return s})),n.d(t,"Enhancer",(function(){return a})),n.d(t,"Factory",(function(){return o})),n.d(t,"ManagedFactory",(function(){return d})),n.d(t,"EntityFactory",(function(){return h})),n.d(t,"LoginOption",(function(){return c})),n.d(t,"UserFactory",(function(){return l})),n.d(t,"DeviceFactory",(function(){return f})),n.d(t,"FileFactory",(function(){return k})),n.d(t,"Managed",(function(){return C})),n.d(t,"Entity",(function(){return I})),n.d(t,"Role",(function(){return B})),n.d(t,"User",(function(){return R})),n.d(t,"File",(function(){return A}));class s{getValue(e,t){return e[t.name]}setValue(e,t,n){e[t.name]=n}}const r=Symbol("BaqendId"),i=Symbol("BaqendType");class a{createProxy(e){return class extends e{}}static getBaqendType(e){return e[i]}static getIdentifier(e){return e[r]}static setIdentifier(e,t){e[r]=t}enhance(e,t){if(t[i]!==e){if(Object.prototype.hasOwnProperty.call(t,i))throw new Error("Type is already used by a different manager");t[i]=e,a.setIdentifier(t,e.ref),this.enhancePrototype(t.prototype,e)}}enhancePrototype(e,t){t.isEmbeddable||(e.toString===Object.prototype.toString&&Object.defineProperty(e,"toString",{value:function(){return this._metadata.id||this._metadata.bucket},enumerable:!1}),t.superType&&"Object"===t.superType.name&&t.superType.declaredAttributes.forEach(t=>{t.isMetadata||this.enhanceProperty(e,t)}),t.declaredAttributes.forEach(t=>{this.enhanceProperty(e,t)}))}enhanceProperty(e,t){const{name:n}=t;Object.defineProperty(e,n,{get(){return this._metadata.throwUnloadedPropertyAccess(n),null},set(e){this._metadata.throwUnloadedPropertyAccess(n),Object.defineProperty(this,n,{value:e,writable:!0,enumerable:!0,configurable:!0})},configurable:!0,enumerable:!0})}}class o{constructor(){this.type=null,this.prototype=null}static extend(e,t){t!==o.prototype&&this.extend(e,Object.getPrototypeOf(t));const n=Object.getOwnPropertyNames(t);for(let s=0,r=n.length;s<r;s+=1){const r=n[s];Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}return e}static createFactory(e){const t=o.extend((function(...e){return t.newInstance(e)}),this.prototype);return t.prototype=e.prototype,t.type=e,t}new(...e){return this.newInstance(e)}newInstance(e){if(!e||0===e.length)return new this.type;const t=[null];Array.prototype.push.apply(t,e);return new(Function.prototype.bind.apply(this.type,t))}}var c,u=n(2);class d extends o{constructor(){super(...arguments),this.methods=null,this.managedType=null,this.db=null}static create(e,t){const n=this.createFactory(e.typeConstructor);return n.methods=n.prototype,n.managedType=e,n.db=t,n}fromJSON(e){const t=this.newInstance();return this.managedType.fromJsonValue(u.Metadata.create(this.managedType,this.db),e,t,{persisting:!1})}addMethods(e){Object.assign(this.methods,e)}addMethod(e,t){this.methods[e]=t}}class h extends d{newInstance(e){const t=super.newInstance(e);return u.Metadata.get(t).db=this.db,t}load(e,t,n,s){return"function"==typeof t?this.load(e,{},t,n):this.db.load(this.managedType.typeConstructor,e,t).then(n,s)}ref(e){return this.db.getReference(this.managedType.ref,e)}fromJSON(e){const t=this.db.getReference(this.managedType.ref,e.id);return this.managedType.fromJsonValue(u.Metadata.get(t),e,t,{persisting:!1})}find(){return this.db.createQueryBuilder(this.managedType.typeConstructor)}partialUpdate(e,t){return this.ref(e).partialUpdate(t)}executeQuery(e,t,n){return this.db.executeQuery(this.managedType.typeConstructor,e,t,n)}}!function(e){e[e.NO_LOGIN=-1]="NO_LOGIN",e[e.SESSION_LOGIN=0]="SESSION_LOGIN",e[e.PERSIST_LOGIN=1]="PERSIST_LOGIN"}(c||(c={}));class l extends h{get LoginOption(){return c}get me(){return this.db.me}register(e,t,n,s,r){if(n instanceof Function)return this.register(e,t,!0,n,s);const i="string"==typeof e?this.fromJSON({username:e}):e;return this.db.register(i,t,void 0===n||n).then(s,r)}login(e,t,n,s,r){return n instanceof Function?this.login(e,t,!0,n,s):this.db.login(e,t,void 0===n||n).then(s,r)}loginWithToken(e,t,n,s){return t instanceof Function?this.loginWithToken(e,!0,t,n):(this.db.token=e,this.db.renew(t).then(n,s))}logout(e,t){return this.db.logout().then(e,t)}newPassword(...e){if("string"==typeof e[2]){const[t,n,s,r,i]=e;return this.db.newPassword(t,n,s).then(r,i)}let[t,n,s,r,i]=e;return s instanceof Function&&(i=r,r=s,s=!0),this.db.newPasswordWithToken(t,n,s).then(r,i)}resetPassword(e,t,n){return this.db.resetPassword(e).then(t,n)}changeUsername(e,t,n,s,r){return this.db.changeUsername(e,t,n).then(s,r)}requestAPIToken(e,t,n){return this.db.requestAPIToken(this.managedType.typeConstructor,e).then(t,n)}revokeAllTokens(e,t,n){return this.db.revokeAllTokens(this.managedType.typeConstructor,e).then(t,n)}}l.DefaultOptions={google:{width:585,height:545,scope:"email",path:"https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online"},facebook:{width:1140,height:640,scope:"email",path:"https://www.facebook.com/v7.0/dialog/oauth?response_type=code"},github:{width:1040,height:580,scope:"user:email",path:"https://github.com/login/oauth/authorize?response_type=code&access_type=online"},twitter:{version:1,width:740,height:730},linkedin:{width:630,height:530,scope:"r_liteprofile",path:"https://www.linkedin.com/oauth/v2/authorization?response_type=code"},salesforce:{width:585,height:545,scope:"email"}},["Google","Facebook","GitHub","Twitter","LinkedIn","Salesforce"].forEach(e=>{const t="loginWith"+e;l.prototype[t]=function(n,s,r,i){if(s instanceof Function)return this[t](n,{},s,r);const a=Object.assign(Object.assign(Object.assign({},l.DefaultOptions[e.toLowerCase()]),"string"==typeof n?{clientId:n}:n),s||{});return this.db.loginWithOAuth(e,a).then(r,i)}});var p=n(1);class f extends h{get PushMessage(){return u.PushMessage}get me(){return this.db.deviceMe}get isRegistered(){return this.db.isDeviceRegistered}loadWebPushKey(){const e=new p.VAPIDPublicKey;return e.responseType("arraybuffer"),this.db.send(e).then(e=>e.entity)}register(e,t,n,s,r){if(n instanceof Function)return this.register(e,t,null,n,s);const i="string"==typeof t?{token:t}:t;return this.db.registerDevice(e,i,n).then(s,r)}push(e,t,n){return this.db.pushDevice(e).then(t,n)}}var g,y,m=n(5),b=n(8),w=n(4),O=n(0),E=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(n[s[r]]=e[s[r]])}return n};const T="/file".length,S=Symbol("Id"),v=Symbol("Metadata"),M=Symbol("Data");class A{get id(){return this[S]}get url(){throw new Error("This method is removed. Use the asynchronous File.createURL() method instead.")}get name(){return this.id.substring(this.id.lastIndexOf("/",this.id.length-2)+1)}get mimeType(){if(this.isFolder)throw new Error("A folder has no mimeType");return this.checkAvailable(),this[v].mimeType}get acl(){return this.checkAvailable(),this[v].acl}get lastModified(){if(this.isFolder)throw new Error("A folder has no lastModified");return this.checkAvailable(),this[v].lastModified}get createdAt(){if(this.isFolder)throw new Error("A folder has no creation date");return this.checkAvailable(),this[v].createdAt}get eTag(){if(this.isFolder)throw new Error("A folder has no eTag");return this.checkAvailable(),this[v].eTag}get headers(){if(this.isFolder)throw new Error("A folder has no custom headers");return this.checkAvailable(),this[v].headers}get size(){if(this.isFolder)throw new Error("A folder has no size");return this.checkAvailable(),this[v].size}get bucket(){return this.id.substring(T+1,this.id.indexOf("/",T+1))}get key(){return this.id.substring(this.id.indexOf("/",T+1)+1)}get path(){return this.id.substring(T)}get parent(){return this.id.substring(T,this.id.lastIndexOf("/",this.id.length-2))}get isMetadataLoaded(){return!!this[v]}constructor(e){this.db=null,this[g]=null,this[y]=null;const t="string"==typeof e?{id:e}:e||{};if(t.id){if(-1===t.id.indexOf("/","/file/".length)||0!==t.id.indexOf("/file/"))throw new Error("Invalid file reference "+t.id);this[S]=t.id}else this[S]=this.createIdFromOptions(t);this.setDataOptions(t),this.isFolder="/"===this.id.charAt(this.id.length-1)}static parseETag(e){if(!e)return null;const t=e.match(/^(?:[wW]\/)?["'](.*)["']$/);return t?t[1]:null}createURL(e){if(this.isFolder)throw new Error("Url can not be created for folders.");return this.db.createURL(this.id,"boolean"==typeof e?e:"www"!==this.bucket)}upload(e,t,n){var s;const r=e||{};if(this.isFolder)throw new Error("A folder cannot be uploaded");this.setDataOptions(r);const i=new p.UploadFile(this.bucket,this.key).entity(this[M].data,null===(s=this[M])||void 0===s?void 0:s.type),a=this[v];return a&&(i.acl(a.acl),i.contentLength(a.size),i.mimeType(a.mimeType),i.customHeaders(a.headers)),i.progress(r.progress||null),this.conditional(i,r),this.db.addToBlackList(this.id),this.db.send(i).then(e=>(this[M]=null,this.fromJSON(e.entity),this)).then(t,n)}download(e,t,n){const s=e||{};if(this.isFolder)throw new Error("A folder cannot be downloaded");const r=s.type||(w.isNode?"buffer":"blob"),i=new p.DownloadFile(this.bucket,this.key).responseType(r);return this.db.ensureCacheHeader(this.id,i,s.refresh),this.db.send(i).then(e=>(this.db.addToWhiteList(this.id),this.fromHeaders(e.headers),e.entity),e=>{if(e.status===O.StatusCode.OBJECT_NOT_FOUND)return null;throw e}).then(t,n)}delete(e,t,n){const s=e||{},r=new p.DeleteFile(this.bucket,this.key);return this.conditional(r,s),this.isFolder||this.db.addToBlackList(this.id),this.db.send(r).then(e=>this.isFolder?e.entity.map(e=>new this.db.File(e)):this).then(t,n)}createIdFromOptions(e){var t;let n;if(e.path)n=e.path;else{const s=Object(w.trailingSlashIt)(e.parent||"/www");if(s.length<3)throw new Error("Invalid parent name: "+s);n=s+(e.name||(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.name)||Object(w.uuid)())}if("/"!==n.charAt(0)&&(n="/"+n),-1!==n.indexOf("//")||n.length<3)throw new Error("Invalid path: "+n);return"/file"+n}conditional(e,t){if(t.force)return;const n=this[v];n&&(n.lastModified||n.eTag)?(e.ifUnmodifiedSince(n.lastModified),e.ifMatch(n.eTag)):e.ifNoneMatch("*")}loadMetadata(e,t,n){const s=e||{};if(this.isFolder)throw new Error("A folder has no mata data.");const r=new p.GetFileMetadata(this.bucket,this.key);return this.db.ensureCacheHeader(this.id,r,s.refresh),this.db.send(r).then(e=>(this.fromHeaders(e.headers),this),e=>{if(e.status===O.StatusCode.OBJECT_NOT_FOUND)return null;throw e}).then(t,n)}saveMetadata(e,t,n){const s=e||{},r=this.toJSON(),i=new p.UpdateFileMetadata(this.bucket,this.key).entity(r);return this.conditional(i,s),this.db.send(i).then(e=>(this.fromJSON(e.entity),this)).then(t,n)}setDataOptions(e){const{data:t,type:n}=e,s=E(e,["data","type"]);if(!t)return;this[M]={type:n,data:t};const r=this.guessMimeType(e)||void 0;this.fromJSON(Object.assign(Object.assign({},s),{mimeType:r}))}guessMimeType(e){const{mimeType:t}=e;if(t)return t;if("undefined"!=typeof Blob&&e.data instanceof Blob)return e.data.type;if("data-url"===e.type&&"string"==typeof e.data){const t=e.data.match(/^data:(.+?)(;base64)?,.*$/);return t&&t[1]}return null}fromHeaders(e){this.fromJSON({eTag:A.parseETag(e.etag),lastModified:e["last-modified"],createdAt:e["baqend-created-at"],mimeType:e["content-type"],acl:e["baqend-acl"]&&JSON.parse(e["baqend-acl"]),size:+e["baqend-size"],headers:e["baqend-custom-headers"]&&JSON.parse(e["baqend-custom-headers"])})}fromJSON(e){const{id:t}=e;if(t&&this.id!==t)throw new Error(`This file id ${this.id} does not match the given json id ${t}`);const n=this[v]||{};let s;e.acl instanceof b.a?s=e.acl:(s=n.acl||new b.a,e.acl&&s.fromJSON(e.acl)),this[v]=Object.assign(Object.assign({},this[v]),{mimeType:e.mimeType,lastModified:e.lastModified&&new Date(e.lastModified)||n.lastModified,createdAt:e.createdAt&&new Date(e.createdAt)||n.createdAt,eTag:e.eTag||n.eTag,acl:s,size:"number"==typeof e.size?e.size:e.contentLength,headers:e.headers||n.headers||{}})}toJSON(){var e,t;this.checkAvailable();const n=null!==(e=this[v])&&void 0!==e?e:{};return{id:this.id,mimeType:n.mimeType,eTag:n.eTag,acl:null===(t=n.acl)||void 0===t?void 0:t.toJSON(),size:n.size,lastModified:n.lastModified&&n.lastModified.toISOString(),createdAt:n.createdAt&&n.createdAt.toISOString(),headers:n.headers}}checkAvailable(){if(!this.isMetadataLoaded)throw new m.PersistentError(`The file metadata of ${this.id} is not available.`)}}g=v,y=M;class k extends o{constructor(){super(...arguments),this.db=null}static create(e){const t=this.createFactory(A);return t.db=e,t}newInstance(e){const t=super.newInstance(e);return t.db=this.db,t}fromJSON(e){const t=this.newInstance([e.id]);return t.fromJSON(e),t}saveMetadata(e,t,n,s){const r=new p.SetFileBucketMetadata(e,t);return this.db.send(r).then(n,s)}loadMetadata(e,t,n,s){const r=new p.GetFileBucketMetadata(e);return this.db.send(r).then(e=>{const t={};return u.Permission.BASE_PERMISSIONS.forEach(n=>{t[n]=u.Permission.fromJSON(e.entity[n]||{})}),t},e=>{if(e.status===O.StatusCode.OBJECT_NOT_FOUND)return null;throw e}).then(n,s)}listBuckets(e,t){return this.db.send(new p.ListBuckets).then(e=>e.entity.map(e=>this.new(e+"/"))).then(e,t)}listFiles(e,t,n,s,r){let i;if("string"==typeof e){const t=Object(w.trailingSlashIt)(e);i=this.new({path:t})}else i=e;const a=i.key,{bucket:o}=i;return this.db.send(new p.ListFiles(o,a,t?t.key:void 0,n)).then(e=>e.entity.map(e=>this.new(e))).then(s,r)}}function P(e){return function(t,n,s){s.enumerable=e}}var _=function(e,t,n,s){var r,i=arguments.length,a=i<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,s);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(i<3?r(a):i>3?r(t,n,a):r(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a};class C{static init(e,t){const n=a.getBaqendType(e.constructor);n.isEntity&&Object.defineProperty(e,"_metadata",{value:u.Metadata.create(n),configurable:!0}),t&&Object.assign(e,t)}static extend(e){return e.prototype=Object.create(this.prototype,{constructor:{value:e,configurable:!0,writable:!0}}),e.extend=C.extend,e}constructor(e){C.init(this,e)}toString(){return a.getBaqendType(this.constructor).ref}toJSON(){const e=a.getBaqendType(this.constructor);return e.toJsonValue(u.Metadata.create(e),this,{persisting:!1})}}_([P(!1)],C.prototype,"toString",null),_([P(!1)],C.prototype,"toJSON",null);var D=n(15),N=function(e,t,n,s){var r,i=arguments.length,a=i<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,s);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(i<3?r(a):i>3?r(t,n,a):r(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a};class I extends C{get id(){return this._metadata.id}set id(e){if(this._metadata.id)throw new Error("The id can't be set twice: "+e);0===(""+e).indexOf(`/db/${this._metadata.bucket}/`)?this._metadata.id=e:this.key=e}get key(){return this._metadata.key}set key(e){this._metadata.key=e}get version(){return this._metadata.version}get acl(){return this._metadata.throwUnloadedPropertyAccess("acl"),this._metadata.acl}attach(e){e.attach(this)}ready(e){return this._metadata.ready().then(()=>this).then(e)}save(e,t,n){return"function"==typeof e?this.save({},e,t):this._metadata.db.save(this,e).then(t,n)}insert(e,t,n){return"function"==typeof e?this.insert({},e,t):this._metadata.db.insert(this,e).then(t,n)}update(e,t,n){return"function"==typeof e?this.update({},e,t):this._metadata.db.update(this,e).then(t,n)}load(e,t,n){if("function"==typeof e)return this.load({},e,t);const s=Object.assign({local:!0},e);if(null===this.id)throw new m.PersistentError("This object can't be loaded, it does have an id.");return this._metadata.db.load(this.id,void 0,s).then(t,n)}delete(e,t,n){return"function"==typeof e?this.delete({},e,t):this._metadata.db.delete(this,e).then(t,n)}optimisticSave(e,t,n){return this._metadata.db.optimisticSave(this,e).then(t,n)}attr(){throw new Error("Attr is not yet implemented.")}validate(){return this._metadata.db.validate(this)}partialUpdate(e){return new D.EntityPartialUpdateBuilder(this,e)}getReferencing(e){const{db:t}=this._metadata,n=this._metadata.type.getReferencing(t,e),s=Array.from(n).map(([e,n])=>{const s=t.createQueryBuilder(e.typeConstructor),r=[];n.forEach(e=>{r.push(s.equal(e,this))});return(1===r.length?r[0]:s.or(r)).resultList()});return Promise.all(s).then(e=>e.filter(e=>!!e.length)).then(e=>Array.prototype.concat.apply([],e))}toString(){const e=a.getBaqendType(this.constructor);return this.id||e.ref}toJSON(e){let t=e;"boolean"==typeof t&&(t={excludeMetadata:t}),"object"!=typeof t&&(t={});const n=this._metadata;return n.type.toJsonValue(n,this,t)}}N([P(!0)],I.prototype,"id",null),N([P(!1)],I.prototype,"key",null),N([P(!0)],I.prototype,"version",null),N([P(