/**
 * Minified by jsDelivr using Terser v5.48.0.
 * Original file: /npm/@instantdb/admin@1.0.65/dist/commonjs/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.InstantError=exports.setInstantWarningsEnabled=exports.InstantAPIError=exports.WebhooksManager=exports.Webhooks=exports.createInstantRouteHandler=exports.i=exports.lookup=exports.tx=exports.id=exports.init_experimental=void 0,exports.init=init;const uuid_1=require("uuid"),core_1=require("@instantdb/core");Object.defineProperty(exports,"tx",{enumerable:!0,get:function(){return core_1.tx}}),Object.defineProperty(exports,"lookup",{enumerable:!0,get:function(){return core_1.lookup}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return core_1.i}}),Object.defineProperty(exports,"id",{enumerable:!0,get:function(){return core_1.id}}),Object.defineProperty(exports,"InstantAPIError",{enumerable:!0,get:function(){return core_1.InstantAPIError}}),Object.defineProperty(exports,"setInstantWarningsEnabled",{enumerable:!0,get:function(){return core_1.setInstantWarningsEnabled}}),Object.defineProperty(exports,"InstantError",{enumerable:!0,get:function(){return core_1.InstantError}}),Object.defineProperty(exports,"createInstantRouteHandler",{enumerable:!0,get:function(){return core_1.createInstantRouteHandler}});const version_ts_1=__importDefault(require("./version.js")),subscribe_ts_1=require("./subscribe.js"),cookie_1=require("cookie"),eventsource_1=require("@instantdb/eventsource"),polyfill_ts_1=require("./polyfill.js"),webhooks_1=require("@instantdb/webhooks");function configWithDefaults(e){return{apiURI:"https://api.instantdb.com",...e}}function instantConfigWithDefaults(e){const t={apiURI:"https://api.instantdb.com"},n={...t,...e};return n.apiURI||(n.apiURI=t.apiURI),n}function withImpersonation(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function validateConfigAndImpersonation(e,t){if(!(t&&("token"in t||"guest"in t)||e.adminToken)){if(t&&"email"in t)throw new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`.");throw new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}}function authorizedHeaders(e,t){validateConfigAndImpersonation(e,t);const{adminToken:n,appId:s}=e,i={"content-type":"application/json","app-id":s};return n&&(i.authorization=`Bearer ${n}`),t?withImpersonation(i,t):i}function isNextJSVersionThatCachesFetchByDefault(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function getDefaultFetchOpts(){return isNextJSVersionThatCachesFetchByDefault()?{cache:"no-store"}:{}}async function jsonReject(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new core_1.InstantAPIError({status:t.status,body:s}))}catch(s){return e(new core_1.InstantAPIError({status:t.status,body:{type:void 0,message:n}}))}}async function jsonFetch(e,t){const n=getDefaultFetchOpts(),s={...t?.headers||{},"Instant-Admin-Version":version_ts_1.default,"Instant-Core-Version":core_1.version},i=await fetch(e,{...n,...t,headers:s});if(200===i.status){const e=await i.json();return Promise.resolve(e)}return jsonReject(e=>Promise.reject(e),i)}function makeEventSourceWrapper(e){return class{source;static OPEN=eventsource_1.EventSource.OPEN;static CONNECTING=eventsource_1.EventSource.CONNECTING;static CLOSED=eventsource_1.EventSource.CLOSED;url;constructor(e){this.url=e,this.source=this.#e(e)}get onopen(){return this.source.onopen}set onopen(e){this.source.onopen=e}get onmessage(){return this.source.onmessage}set onmessage(e){this.source.onmessage=e}get onerror(){return this.source.onerror}set onerror(e){this.source.onerror=e}get readyState(){return this.source.readyState}close(){this.source.close()}#e(t){const n=new eventsource_1.EventSource(t,{messageEvent:polyfill_ts_1.MessageEventPolyfill,fetch:(t,n)=>fetch(t,{...n,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":version_ts_1.default,"@instantdb/core":core_1.version}})})});return n}}}function init(e){e.appId&&(0,uuid_1.validate)(e.appId)||console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:e.appId?.trim(),adminToken:e.adminToken?.trim(),useDateObjects:e.useDateObjects??!1};return new InstantAdminDatabase(t)}Object.defineProperty(exports,"Webhooks",{enumerable:!0,get:function(){return webhooks_1.Webhooks}}),Object.defineProperty(exports,"WebhooksManager",{enumerable:!0,get:function(){return webhooks_1.WebhooksManager}});const init_experimental=init;function steps(e){return(Array.isArray(e)?e:[e]).flatMap(core_1.getOps)}exports.init_experimental=init_experimental;class Rooms{config;constructor(e){this.config=e}async getPresence(e,t){return(await jsonFetch(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(e)}&room-id=${t}`,{method:"GET",headers:authorizedHeaders(this.config)})).sessions||{}}}class Auth{config;constructor(e){this.config=e,this.createToken=this.createToken.bind(this)}generateMagicCode=async e=>jsonFetch(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e})});sendMagicCode=async e=>jsonFetch(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e})});verifyMagicCode=async(e,t)=>{const{user:n}=await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e,code:t})});return n};checkMagicCode=async(e,t,n)=>{const s=await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e,code:t,...n?.extraFields?{"extra-fields":n.extraFields}:{}})});return{user:s.user,created:s.created}};async createToken(e){const t="string"==typeof e?{email:e}:e;return(await jsonFetch(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify(t)})).user.refresh_token}verifyToken=async e=>(await jsonFetch(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":e})})).user;getUser=async e=>{const t=new URLSearchParams(Object.entries(e)).toString();return(await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${t}`,{method:"GET",headers:authorizedHeaders(this.config)})).user};deleteUser=async e=>{const t=new URLSearchParams(Object.entries(e)).toString();return(await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${t}`,{method:"DELETE",headers:authorizedHeaders(this.config)})).deleted};async signOut(e){const t="string"==typeof e?{email:e}:e,n=this.config;await jsonFetch(`${n.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(n),body:JSON.stringify(t)})}getUserFromRequest=async(e,t)=>{const n=e.headers.get("cookie")||"",s=(0,cookie_1.parseCookie)(n),i="instant_user_"+this.config.appId;if(!s[i])return null;const o=s[i],r=JSON.parse(o);if(!r?.refresh_token)return null;if(t?.disableValidation)return r;return await this.verifyToken(r.refresh_token)}}const isNodeReadable=e=>e&&"object"==typeof e&&"function"==typeof e.pipe&&"function"==typeof e.read,isWebReadable=e=>e&&"function"==typeof e.getReader;class Storage{config;impersonationOpts;constructor(e,t){this.config=e,this.impersonationOpts=t}uploadFile=async(e,t,n={})=>{const s={...authorizedHeaders(this.config,this.impersonationOpts),path:e};let i;if(n.contentDisposition&&(s["content-disposition"]=n.contentDisposition),delete s["content-type"],n.contentType&&(s["content-type"]=n.contentType),isNodeReadable(t)&&(i="half"),isNodeReadable(t)||isWebReadable(t)){if(!n.fileSize)throw new Error("fileSize is required in metadata when uploading streams");s["content-length"]=n.fileSize.toString()}let o={method:"PUT",headers:s,body:t,...i&&{duplex:i}};return jsonFetch(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)};delete=async e=>jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(e)}`,{method:"DELETE",headers:authorizedHeaders(this.config,this.impersonationOpts)});deleteMany=async e=>jsonFetch(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify({filenames:e})});upload=async(e,t,n={})=>{const{data:s}=await jsonFetch(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({app_id:this.config.appId,filename:e})}),i={},o=n.contentType;o&&(i["Content-Type"]=o);const{ok:r}=await fetch(s,{method:"PUT",body:t,headers:i});return r};list=async()=>{const{data:e}=await jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:authorizedHeaders(this.config)});return e};getDownloadUrl=async e=>{const{data:t}=await jsonFetch(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(e)}`,{method:"GET",headers:authorizedHeaders(this.config)});return t}}class Streams{#t;constructor(e){this.#t=e}createReadStream=e=>this.#t().createReadStream(e);createWriteStream=e=>this.#t().createWriteStream(e)}function createLogger(e,t=console){return{info:e?(...e)=>t.info(...e):()=>{},debug:e?(...e)=>t.debug(...e):()=>{},error:e?(...e)=>t.error(...e):()=>{}}}class InstantAdminDatabase{config;auth;storage;streams;rooms;impersonationOpts;webhooks;#n=null;#s=0;#i=null;#o;tx=(0,core_1.txInit)();constructor(e){this.config=instantConfigWithDefaults(e),this.auth=new Auth(this.config),this.storage=new Storage(this.config,this.impersonationOpts),this.streams=new Streams(this.#t.bind(this)),this.rooms=new Rooms(this.config),this.webhooks=new webhooks_1.Webhooks(this.config,jsonFetch),this.#o=createLogger(!!this.config.verbose,this.config.logger)}asUser=e=>{const t=new InstantAdminDatabase({...this.config});return t.impersonationOpts=e,t.storage=new Storage(this.config,e),t};query=(e,t={})=>{e&&t&&"ruleParams"in t&&(e={$$ruleParams:t.ruleParams,...e}),this.config.disableValidation||(0,core_1.validateQuery)(e,this.config.schema);const n=t.fetchOpts||{},s=n.headers||{};return jsonFetch(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...n,method:"POST",headers:{...s,...authorizedHeaders(this.config,this.impersonationOpts)},body:JSON.stringify({query:e,"inference?":!!this.config.schema})})};subscribeQuery(e,t,n={}){e&&n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e}),this.config.disableValidation||(0,core_1.validateQuery)(e,this.config.schema);const s={...(n.fetchOpts||{}).headers||{},...authorizedHeaders(this.config,this.impersonationOpts)},i=!!this.config.schema;return(0,subscribe_ts_1.subscribe)(e,t,{headers:s,inference:i,apiURI:this.config.apiURI})}transact=e=>(this.config.disableValidation||(0,core_1.validateTransactions)(e,this.config.schema),jsonFetch(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify({steps:steps(e),"throw-on-missing-attrs?":!!this.config.schema})}));debugQuery=async(e,t)=>{e&&t&&"ruleParams"in t&&(e={$$ruleParams:t.ruleParams,...e});const n={query:e,"rules-override":t?.rules,"inference?":t?.cardinalityInference??!!this.config.schema};t?.ip&&(n["ip-override"]=t.ip),t?.origin&&(n["origin-override"]=t.origin);const s=await jsonFetch(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify(n)});return{result:s.result,checkResults:s["check-results"]}};debugTransact=(e,t)=>{const n={steps:steps(e),"rules-override":t?.rules,"dangerously-commit-tx":t?.__dangerouslyCommit};return t?.ip&&(n["ip-override"]=t.ip),t?.origin&&(n["origin-override"]=t.origin),jsonFetch(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify(n)})};#r(){this.#n&&this.#n.close();const e=makeEventSourceWrapper({headers:{...authorizedHeaders(this.config,this.impersonationOpts)},inference:!!this.config.schema}),t=new core_1.SSEConnection(e,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return t.onopen=this.#a,t.onmessage=this.#c,t.onclose=this.#h,t.onerror=this.#d,this.#n=t,t}#p(){return this.#n||this.#r()}#u(e,t){const n=this.#p();this.#o.info("[send]",e,t,{isOpen:n.isOpen()}),n.isOpen()&&n.send({"client-event-id":e,...t})}#f(){this.#p();const e=new core_1.InstantStream({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(e,t)=>{this.#u(e,t)},log:this.#o});return this.#i=e,e}#t(){return this.#i||this.#f()}#a=e=>{e.target===this.#n?(this.#o.info("[socket][open]",e.target.id),this.#s=0,this.#i?.onConnectionStatusChange("authenticated")):this.#o.info("[socket][open]",e.target.id,"skip; this is no longer the current transport")};#h=e=>{e.target===this.#n?(this.#o.info("[socket][close]",e.target.id),this.#i?.onConnectionStatusChange("closed"),this.#n&&(this.#n=null,this.#g()||(setTimeout(()=>this.#p(),this.#s),this.#s=Math.min(15e3,2*Math.max(this.#s,500))))):this.#o.info("[socket][close]",e.target.id,"skip; this is no longer the current transport")};#d=e=>{e.target===this.#n?(this.#o.info("[socket][error]",e.target.id),this.#i?.onConnectionStatusChange("closed")):this.#o.info("[socket][error]",e.target.id,"skip; this is no longer the current transport")};#g(){return!this.#i||!this.#i.hasActiveStreams()}#m(){if(this.#n&&this.#g()){const e=this.#n;this.#o.info("cleaning up unused socket",e.id),this.#n=null,e.close()}}#c=e=>{if(e.target!==this.#n)return void this.#o.info("[socket][message]",e.target.id,"skip; this is no longer the current transport");const t=e.message;switch(this.#o.info("[receive]",t),t.op){case"start-stream-ok":this.#i?.onStartStreamOk(t);break;case"stream-flushed":this.#i?.onStreamFlushed(t);break;case"append-failed":this.#i?.onAppendFailed(t);break;case"stream-append":this.#i?.onStreamAppend(t);break;case"error":switch(t["original-event"]?.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":this.#i?.onRecieveError(t)}}this.#m()}}
//# sourceMappingURL=/sm/16cd4c9826110e9db8bee4b1092c51a428920957ce45b33ec84c58c15574d1cd.map