bknd
Version:
Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.
2 lines • 58.6 kB
JavaScript
"use client";
import*as nt from'react';import nt__default,{createContext,forwardRef,useContext,cloneElement,createElement,isValidElement,useState,useRef,useImperativeHandle,useEffect,memo,useCallback,useMemo,Children,Fragment as Fragment$1,useId}from'react';import {useApi}from'bknd/client';import {Form}from'json-schema-form-react';import {transform}from'lodash-es';import {useSyncExternalStore}from'use-sync-external-store/shim/index.js';import*as tt from'@sinclair/typebox';import {SetErrorFunction,DefaultErrorFunction}from'@sinclair/typebox/errors';import {Value}from'@sinclair/typebox/value';import _1 from'dayjs';import Da from'dayjs/plugin/weekOfYear.js';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {Switch}from'radix-ui';import {useClickOutside,useInViewport}from'@mantine/hooks';import jr from'use-sync-external-store/shim/with-selector.js';import {decode}from'hono/jwt';import Yr,{useSWRConfig}from'swr';import t2 from'swr/infinite';var V0=Object.create;var v1=Object.defineProperty;var X0=Object.getOwnPropertyDescriptor;var K0=Object.getOwnPropertyNames;var Q0=Object.getPrototypeOf,$0=Object.prototype.hasOwnProperty;var Z0=(t,a)=>()=>(a||t((a={exports:{}}).exports,a),a.exports);var Y0=(t,a,r,o)=>{if(a&&typeof a=="object"||typeof a=="function")for(let e of K0(a))!$0.call(t,e)&&e!==r&&v1(t,e,{get:()=>a[e],enumerable:!(o=X0(a,e))||o.enumerable});return t};var J0=(t,a,r)=>(r=t!=null?V0(Q0(t)):{},Y0(v1(r,"default",{value:t,enumerable:true}),t));var N1=Z0((A2,Ht)=>{var u=String,I1=function(){return {isColorSupported:false,reset:u,bold:u,dim:u,italic:u,underline:u,inverse:u,hidden:u,strikethrough:u,black:u,red:u,green:u,yellow:u,blue:u,magenta:u,cyan:u,white:u,gray:u,bgBlack:u,bgRed:u,bgGreen:u,bgYellow:u,bgBlue:u,bgMagenta:u,bgCyan:u,bgWhite:u,blackBright:u,redBright:u,greenBright:u,yellowBright:u,blueBright:u,magentaBright:u,cyanBright:u,whiteBright:u,bgBlackBright:u,bgRedBright:u,bgGreenBright:u,bgYellowBright:u,bgBlueBright:u,bgMagentaBright:u,bgCyanBright:u,bgWhiteBright:u}};Ht.exports=I1();Ht.exports.createColors=I1;});var Rt=t=>{let[a,r]=useState(),o=useApi(t?.baseUrl);return useEffect(()=>{(async()=>{let e=await o.auth.strategies();e.res.ok&&r(e.body);})();},[t?.baseUrl]),{strategies:a?.strategies,basepath:a?.basepath,loading:!a}};function M1(t){var a,r,o="";if(typeof t=="string"||typeof t=="number")o+=t;else if(typeof t=="object")if(Array.isArray(t)){var e=t.length;for(a=0;a<e;a++)t[a]&&(r=M1(t[a]))&&(o&&(o+=" "),o+=r);}else for(r in t)t[r]&&(o&&(o+=" "),o+=r);return o}function oa(){for(var t,a,r=0,o="",e=arguments.length;r<e;r++)(t=arguments[r])&&(a=M1(t))&&(o&&(o+=" "),o+=a);return o}var it=oa;function j(...t){return t.filter(Boolean).join(" ")}function k1(t,a){if(t instanceof RegExp)return {keys:false,pattern:t};var r,o,e,l,i=[],h="",d=t.split("/");for(d[0]||d.shift();e=d.shift();)r=e[0],r==="*"?(i.push(r),h+=e[1]==="?"?"(?:/(.*))?":"/(.*)"):r===":"?(o=e.indexOf("?",1),l=e.indexOf(".",1),i.push(e.substring(1,~o?o:~l?l:e.length)),h+=~o&&!~l?"(?:/([^/]+?))?":"/([^/]+?)",~l&&(h+=(~o?"?":"")+"\\"+e.substring(l))):h+="/"+e;return {keys:i,pattern:new RegExp("^"+h+(a?"(?=$|/)":"/?$"),"i")}}var ea=nt.useInsertionEffect,la=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",f1=la?nt.useLayoutEffect:nt.useEffect,ia=ea||f1,At=t=>{let a=nt.useRef([t,(...r)=>a[0](...r)]).current;return ia(()=>{a[0]=t;}),a[1]};var ca="popstate",Et="pushState",It="replaceState",pa="hashchange",m1=[ca,Et,It,pa],ga=t=>{for(let a of m1)addEventListener(a,t);return ()=>{for(let a of m1)removeEventListener(a,t);}},j1=(t,a)=>useSyncExternalStore(ga,t,a),sa=()=>location.search,z1=({ssrSearch:t=""}={})=>j1(sa,()=>t),T1=()=>location.pathname,ua=({ssrPath:t}={})=>j1(T1,t?()=>t:T1);var va=(t,{replace:a=false,state:r=null}={})=>history[a?It:Et](r,"",t),y1=(t={})=>[ua(t),va],W1=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[W1]>"u"){for(let t of [Et,It]){let a=history[t];history[t]=function(){let r=a.apply(this,arguments),o=new Event(t);return o.arguments=arguments,dispatchEvent(o),r};}Object.defineProperty(window,W1,{value:true});}var Ma=(t,a)=>a.toLowerCase().indexOf(t.toLowerCase())?"~"+a:a.slice(t.length)||"/",F1=(t="")=>t==="/"?"":t,ka=(t,a)=>t[0]==="~"?t.slice(1):F1(a)+t,fa=(t="",a)=>Ma(S1(F1(t)),S1(a));var S1=t=>{try{return decodeURI(t)}catch{return t}};var xa={hook:y1,searchHook:z1,parser:k1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:t=>t},La=createContext(xa),Nt=()=>useContext(La),Ca={};createContext(Ca);var ba=t=>{let[a,r]=t.hook(t);return [fa(t.base,a),At((o,e)=>r(ka(o,t.base),e))]};var D1=forwardRef((t,a)=>{let r=Nt(),[o,e]=ba(r),{to:l="",href:i=l,onClick:h,asChild:d,children:s,className:g,replace:n,state:p,...b}=t,m=At(B=>{B.ctrlKey||B.metaKey||B.altKey||B.shiftKey||B.button!==0||(h?.(B),B.defaultPrevented||(B.preventDefault(),e(i,t)));}),k=r.hrefs(i[0]==="~"?i.slice(1):r.base+i,r);return d&&isValidElement(s)?cloneElement(s,{onClick:m,href:k}):createElement("a",{...b,onClick:m,href:k,className:g?.call?g(o===i):g,children:s,ref:a})});function P1(t,a){let r="";function o(e){return e}for(let e in t){let l=t[e];if(l!==void 0)if(Array.isArray(l))for(let i=0;i<l.length;i++)r.length>0&&(r+="&"),r+=`${o(e)}=${o(l[i])}`;else typeof l=="object"&&(l=JSON.stringify(l)),r.length>0&&(r+="&"),r+=`${o(e)}=${o(l)}`;}return ("")+r}var Ut=(t,a)=>typeof t=="string"?[1,"1","true"].includes(t):!!(t||a);function ht(){try{return Ut(0)}catch{return false}}var Ba={cli_log_level:{key:"BKND_CLI_LOG_LEVEL",validate:t=>{if(typeof t=="string"&&["log","info","warn","error","debug"].includes(t.toLowerCase()))return t.toLowerCase()}},cli_create_ref:{key:"BKND_CLI_CREATE_REF",validate:t=>typeof t=="string"?t:void 0},cli_telemetry:{key:"BKND_CLI_TELEMETRY",validate:t=>{if(!(typeof t>"u"))return Ut(t,true)}},modules_debug:{key:"BKND_MODULES_DEBUG",validate:Ut}},qt=(t,a,r)=>{try{let o=r?.source??process.env,e=Ba[t],l=o[e.key],i=e.validate(l);if(typeof i<"u")return r?.onValid?.(i),i;r?.onFallback?.(l);}catch{}return a};function wa(t,a=" "){return !t||t.length===0?t:t.split(a).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(a)}function ma(t){return !t||t.length===0?t:t.split("_").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")}function R1(t,a=" "){return wa(ma(t),a)}function A1(t,a){let r=new Set(a),o={};for(let[e,l]of Object.entries(t))r.has(e)||(o[e]=l);return o}function O1(){return (navigator.userAgent.indexOf("Opera")||navigator.userAgent.indexOf("OPR"))!==-1?"Opera":navigator.userAgent.indexOf("Edg")!==-1?"Edge":navigator.userAgent.indexOf("Chrome")!==-1?"Chrome":navigator.userAgent.indexOf("Safari")!==-1?"Safari":navigator.userAgent.indexOf("Firefox")!==-1?"Firefox":navigator.userAgent.indexOf("MSIE")!==-1||document.documentMode?"IE":"unknown"}var Ta={video:["mp4","webm"],audio:["ogg"],image:["jpeg","png","gif","webp","bmp","tiff","avif","heic","heif"],text:["html","css","mdx","yaml","vcard","csv","vtt"],application:["zip","xml","toml","json","json5"],font:["woff","woff2","ttf","otf"]},M={vnd:"vnd.openxmlformats-officedocument",z:"application/x-7z-compressed",t:(t="plain")=>`text/${t}`,a:(t="octet-stream")=>`application/${t}`,i:t=>`image/${t}`,v:t=>`video/${t}`},Wa=new Map([["7z",M.z],["7zip",M.z],["ai",M.a("pdf")],["apk",M.a("vnd.android.package-archive")],["doc",M.a("msword")],["docx",`${M.vnd}.wordprocessingml.document`],["eps",M.a("postscript")],["epub",M.a("epub+zip")],["ini",M.t()],["jar",M.a("java-archive")],["jsonld",M.a("ld+json")],["jpg",M.i("jpeg")],["log",M.t()],["m3u",M.t()],["m3u8",M.a("vnd.apple.mpegurl")],["manifest",M.t("cache-manifest")],["md",M.t("markdown")],["mkv",M.v("x-matroska")],["mp3",M.a("mpeg")],["mobi",M.a("x-mobipocket-ebook")],["ppt",M.a("powerpoint")],["pptx",`${M.vnd}.presentationml.presentation`],["qt",M.v("quicktime")],["svg",M.i("svg+xml")],["tif",M.i("tiff")],["tsv",M.t("tab-separated-values")],["tgz",M.a("x-tar")],["txt",M.t()],["text",M.t()],["vcd",M.a("x-cdlink")],["vcs",M.t("x-vcalendar")],["wav",M.a("x-wav")],["webmanifest",M.a("manifest+json")],["xls",M.a("vnd.ms-excel")],["xlsx",`${M.vnd}.spreadsheetml.sheet`],["yml",M.t("yaml")]]);function E1(t){try{let a=t.split(".").pop();if(!a)return M.a();for(let[r,o]of Object.entries(Ta))if(o.includes(a))return `${r}/${a}`;return Wa.get(a)}catch{return M.a()}}var O=J0(N1());function ja(){try{let t=process||{},a=t.argv||[],r=t.env||{};return !(r.NO_COLOR||a.includes("--no-color"))&&(!!r.FORCE_COLOR||a.includes("--color")||t.platform==="win32"||(t.stdout||{}).isTTY&&r.TERM!=="dumb"||!!r.CI)}catch{return false}}var _t={critical:{prefix:"CRT",color:O.default.red,args_color:O.default.red,original:console.error},error:{prefix:"ERR",color:O.default.red,args_color:O.default.red,original:console.error},warn:{prefix:"WRN",color:O.default.yellow,args_color:O.default.yellow,original:console.warn},info:{prefix:"INF",color:O.default.cyan,original:console.info},log:{prefix:"LOG",color:O.default.dim,args_color:O.default.dim,original:console.log},debug:{prefix:"DBG",color:O.default.yellow,args_color:O.default.dim,original:console.debug}};function za(t,a){let r=ja(),o=_t[t],e=o.color(`[${o.prefix}]`),l=a.map(i=>"args_color"in o&&r&&typeof i=="string"?o.args_color(i):i);return o.original(e,O.default.gray(H1()),...l)}var q1=qt("cli_log_level","log"),ft=globalThis.__consoleConfig??={level:q1},U1=Object.keys(_t),Gt=new Proxy(ft,{get:(t,a)=>{switch(a){case "original":return console;case "setLevel":return e=>{ft.level=e;};case "resetLevel":return ()=>{ft.level=q1;}}let r=U1.indexOf(ft.level),o=U1.indexOf(a);return a in _t&&o<=r?(...e)=>za(a,e):()=>null}});function Fa(t){t.Set("StringEnum",(a,r)=>typeof r=="string"&&a.enum.includes(r));}Fa(tt.TypeRegistry);tt.Type.String({pattern:"^[a-zA-Z_][a-zA-Z0-9_]*$",minLength:2,maxLength:150});SetErrorFunction(t=>t?.schema?.errorMessage?t.schema.errorMessage:t?.schema?.[tt.Kind]==="StringEnum"?`Expected: ${t.schema.enum.map(a=>`"${a}"`).join(", ")}`:DefaultErrorFunction(t));_1.extend(Da);function H1(t){return _1(t).format("YYYY-MM-DD HH:mm:ss")}function G1(t,a,r){let o=Math.min(a,r),e=Math.max(a,r);return Math.max(o,Math.min(t,e))}var V1={fileSize:(t,a=2)=>{if(t===0)return "0 Bytes";let r=1024,o=a<0?0:a,e=["Bytes","KB","MB","GB","TB"],l=Math.floor(Math.log(t)/Math.log(r));return Number.parseFloat((t/r**l).toFixed(o))+" "+e[l]}};var I=t=>(ht(),t);var Pa=(t="",a="")=>a.toLowerCase().indexOf(t.toLowerCase())?"~"+a:a.slice(t.length)||"/",K1=(t,a="")=>t[0]==="~"?t.slice(1):a+t;var Ra=t=>{try{return decodeURI(t)}catch{return t}},Aa=t=>{let[a,r]=t.hook(t);return [Ra(Pa(t.base,a)),I((o,e)=>r(K1(o,t.base),e))]};function Q1({className:t,native:a,onClick:r,...o}){let e=Nt(),[l,i]=Aa(e);function h(b,m){if(b.startsWith(m)){let k=b.replace(m,"");return k.length===0||k[0]==="/"}return false}let d=o.href??o.to,s=e.hrefs(d[0]==="~"?d.slice(1):e.base+d,e).replace("//","/"),g=K1(l,e.base).replace("//","/"),n=s.replace(e.base,"").length<=1?s===g:h(g,s);if(a)return jsx("a",{className:`${n?"active ":""}${t}`,...o});let p=b=>{r?.(b);};return jsx(D1,{className:`${n?"active ":""}${t}`,...o,onClick:p})}var Ea={small:"px-2 py-1.5 rounded-md gap-1 text-sm",default:"px-3 py-2.5 rounded-md gap-1.5",large:"px-4 py-3 rounded-md gap-2.5 text-lg"},Ia={small:12,default:16,large:20},Na={default:"bg-primary/5 hover:bg-primary/10 link text-primary/70",primary:"bg-primary hover:bg-primary/80 link text-background",ghost:"bg-transparent hover:bg-primary/5 link text-primary/70",outline:"border border-primary/20 bg-transparent hover:bg-primary/5 link text-primary/80",red:"dark:bg-red-950 dark:hover:bg-red-900 bg-red-100 hover:bg-red-200 link text-primary/70",subtlered:"dark:text-red-700 text-red-700 dark:hover:bg-red-900 dark:hover:text-red-200 bg-transparent hover:bg-red-50 link"},Z1=({children:t,size:a,variant:r,IconLeft:o,IconRight:e,iconSize:l=Ia[a??"default"],iconProps:i,labelClassName:h,...d})=>({...d,className:j("flex flex-row flex-nowrap items-center !font-semibold disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed transition-[opacity,background-color,color,border-color]",Ea[a??"default"],Na[r??"default"],d.className),children:jsxs(Fragment,{children:[o&&jsx(o,{size:l,...i}),t&&Children.count(t)===1?jsx("span",{className:j("leading-none",h),children:t}):t,e&&jsx(e,{size:l,...i})]})}),at=forwardRef((t,a)=>jsx("button",{type:"button",ref:a,...Z1(t)}));forwardRef((t,a)=>jsx(Q1,{ref:a,href:"#",...Z1(t)}));var Xt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Kt=nt__default.createContext&&nt__default.createContext(Xt);var Ha=["attr","size","title"];function _a(t,a){if(t==null)return {};var r=Ga(t,a),o,e;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(e=0;e<l.length;e++)o=l[e],!(a.indexOf(o)>=0)&&Object.prototype.propertyIsEnumerable.call(t,o)&&(r[o]=t[o]);}return r}function Ga(t,a){if(t==null)return {};var r={};for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)){if(a.indexOf(o)>=0)continue;r[o]=t[o];}return r}function xt(){return xt=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var r=arguments[a];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o]);}return t},xt.apply(this,arguments)}function J1(t,a){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);a&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,o);}return r}function Lt(t){for(var a=1;a<arguments.length;a++){var r=arguments[a]!=null?arguments[a]:{};a%2?J1(Object(r),true).forEach(function(o){Va(t,o,r[o]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):J1(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o));});}return t}function Va(t,a,r){return a=Xa(a),a in t?Object.defineProperty(t,a,{value:r,enumerable:true,configurable:true,writable:true}):t[a]=r,t}function Xa(t){var a=Ka(t,"string");return typeof a=="symbol"?a:a+""}function Ka(t,a){if(typeof t!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,a);if(typeof o!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return (a==="string"?String:Number)(t)}function t0(t){return t&&t.map((a,r)=>nt__default.createElement(a.tag,Lt({key:r},a.attr),t0(a.child)))}function H(t){return a=>nt__default.createElement(Qa,xt({attr:Lt({},t.attr)},a),t0(t.child))}function Qa(t){var a=r=>{var{attr:o,size:e,title:l}=t,i=_a(t,Ha),h=e||r.size||"1em",d;return r.className&&(d=r.className),t.className&&(d=(d?d+" ":"")+t.className),nt__default.createElement("svg",xt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},r.attr,o,i,{className:d,style:Lt(Lt({color:t.color||r.color},r.style),t.style),height:h,width:h,xmlns:"http://www.w3.org/2000/svg"}),l&&nt__default.createElement("title",null,l),t.children)};return Kt!==void 0?nt__default.createElement(Kt.Consumer,null,r=>a(r)):a(Xt)}function a0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12z"},child:[]},{tag:"path",attr:{d:"M16 3v4"},child:[]},{tag:"path",attr:{d:"M8 3v4"},child:[]},{tag:"path",attr:{d:"M4 11h16"},child:[]},{tag:"path",attr:{d:"M11 15h1"},child:[]},{tag:"path",attr:{d:"M12 15v3"},child:[]}]})(t)}function r0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 9l6 6l6 -6"},child:[]}]})(t)}function o0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"},child:[]},{tag:"path",attr:{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"},child:[]},{tag:"path",attr:{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"},child:[]}]})(t)}function e0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6"},child:[]},{tag:"path",attr:{d:"M11 13l9 -9"},child:[]},{tag:"path",attr:{d:"M15 4h5v5"},child:[]}]})(t)}function l0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10.585 10.587a2 2 0 0 0 2.829 2.828"},child:[]},{tag:"path",attr:{d:"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87"},child:[]},{tag:"path",attr:{d:"M3 3l18 18"},child:[]}]})(t)}function i0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"},child:[]},{tag:"path",attr:{d:"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"},child:[]}]})(t)}function h0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 7l16 0"},child:[]},{tag:"path",attr:{d:"M10 11l0 6"},child:[]},{tag:"path",attr:{d:"M14 11l0 6"},child:[]},{tag:"path",attr:{d:"M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"},child:[]},{tag:"path",attr:{d:"M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"},child:[]}]})(t)}function d0(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"},child:[]},{tag:"path",attr:{d:"M7 9l5 -5l5 5"},child:[]},{tag:"path",attr:{d:"M12 4l0 12"},child:[]}]})(t)}var Za={xs:{className:"p-0.5",size:13},sm:{className:"p-0.5",size:15},md:{className:"p-1",size:18},lg:{className:"p-1.5",size:22}},ct=forwardRef(({Icon:t,size:a,variant:r="ghost",onClick:o,disabled:e,iconProps:l,...i},h)=>{let d=Za[a??"md"];return jsx(at,{ref:h,variant:r,iconSize:d.size,iconProps:l,IconLeft:t,className:j(d.className,i.className),onClick:o,disabled:e})});var Qt=({error:t,as:a,...r})=>jsx(a||"div",{...r,className:j("flex flex-col gap-1.5",a==="fieldset"&&"border border-primary/10 p-3 rounded-md",a==="fieldset"&&t&&"border-red-500",t&&"text-red-500",r.className)});var $t=({as:t,...a})=>jsx(t||"label",{...a});var pt=forwardRef((t,a)=>{let r=t.disabled||t.readOnly;return jsx("input",{type:"text",...t,ref:a,className:j("bg-muted/40 h-11 rounded-md py-2.5 px-4 outline-none w-full",r&&"bg-muted/50 text-primary/50",!r&&"focus:bg-muted focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all",t.className)})});forwardRef((t,a)=>t.type==="password"?jsx(Zt,{...t,ref:a}):jsx(pt,{...t,ref:a}));var Zt=forwardRef((t,a)=>{let[r,o]=useState(false);function e(){o(l=>!l);}return jsxs("div",{className:"relative w-full",children:[jsx(pt,{...t,type:r?"text":"password",className:"w-full",ref:a}),jsx("div",{className:"absolute right-3 top-0 bottom-0 flex items-center",children:jsx(ct,{Icon:r?l0:i0,onClick:e,variant:"ghost",className:"opacity-70"})})]})});forwardRef((t,a)=>jsx("textarea",{rows:3,...t,ref:a,className:j("bg-muted/40 min-h-11 rounded-md py-2.5 px-4 focus:bg-muted outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50",t.className)}));forwardRef((t,a)=>{let r=useRef(null),o=O1();useImperativeHandle(a,()=>r.current);let e=I(()=>{r?.current&&(r.current.focus(),["Safari"].includes(o)?r.current.click():r.current.showPicker());});return jsxs("div",{className:"relative w-full",children:[jsx("div",{className:"absolute h-full right-3 top-0 bottom-0 flex items-center",children:jsx(ct,{Icon:a0,onClick:e})}),jsx(pt,{...t,type:t.type??"date",ref:r,className:"w-full appearance-none"})]})});forwardRef((t,a)=>{let[r,o]=useState(!!t.value);useEffect(()=>{o(!!t.value);},[t.value]);function e(l){o(l.target.checked),t.onChange?.(l.target.checked);}return jsx("div",{className:"h-11 flex items-center",children:jsx("input",{...t,type:"checkbox",ref:a,className:"outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 transition-all disabled:opacity-70 scale-150 ml-1",checked:r,onChange:e,disabled:t.disabled})})});var c0={xs:{root:"h-5 w-8",thumb:"data-[state=checked]:left-[calc(100%-1rem)]"},sm:{root:"h-6 w-10",thumb:"data-[state=checked]:left-[calc(100%-1.25rem)]"},md:{root:"h-7 w-12",thumb:"data-[state=checked]:left-[calc(100%-1.5rem)]"}};forwardRef(({type:t,required:a,...r},o)=>jsx(Switch.Root,{className:it("relative cursor-pointer rounded-full bg-muted border-2 border-transparent outline-none ring-1 dark:ring-primary/10 ring-primary/20 data-[state=checked]:ring-primary/60 data-[state=checked]:bg-primary/60 appearance-none transition-colors hover:bg-muted/80",c0[r.size??"md"].root,r.disabled&&"opacity-50 !cursor-not-allowed"),onCheckedChange:e=>{console.log("setting",e),r.onChange?.({target:{value:e}});},...r,checked:typeof r.checked<"u"?r.checked:typeof r.value<"u"?!!r.value:void 0,ref:o,children:jsx(Switch.Thumb,{className:it("absolute top-0 left-0 h-full aspect-square rounded-full bg-primary/30 data-[state=checked]:bg-background transition-[left,right] duration-100 border border-muted",c0[r.size??"md"].thumb)})}));forwardRef(({children:t,options:a,...r},o)=>jsxs("div",{className:"flex w-full relative",children:[jsx("select",{...r,ref:o,className:j("bg-muted/40 focus:bg-muted rounded-md py-2.5 px-4 outline-none focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:border-transparent transition-all disabled:bg-muted/50 disabled:text-primary/50","appearance-none h-11 w-full",!r.multiple&&"border-r-8 border-r-transparent",r.className),children:a?jsxs(Fragment,{children:[!r.required&&jsx("option",{value:""}),a.map(e=>typeof e!="object"?{value:e,label:String(e)}:e).map(e=>jsx("option",{value:e.value,children:e.label},e.value))]}):t}),!r.multiple&&jsx(r0,{className:"absolute right-3 top-0 bottom-0 h-full opacity-70 pointer-events-none",size:18})]}));function bt({label:t,provider:a,icon:r,action:o,method:e="POST",basepath:l="/api/auth",children:i}){let h=[l,a,o].join("/");return jsxs("form",{method:e,action:h,className:"w-full",children:[jsxs(at,{type:"submit",size:"large",variant:"outline",className:"justify-center w-full",IconLeft:r,children:["Continue with ",t??R1(a)]}),i]})}var{Type:Yt}=tt,Jt=class{async validate(a,r){return Value.Check(a,r)?[]:[...Value.Errors(a,r)]}},ir=new Jt,hr=Yt.Object({email:Yt.String({pattern:"^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"}),password:Yt.String({minLength:8})});function Bt({formData:t,className:a,method:r="POST",action:o,auth:e,buttonLabel:l=o==="login"?"Sign in":"Sign up",...i}){let h=e?.basepath??"/api/auth",d={action:`${h}/password/${o}`,strategy:e?.strategies?.password??{}},s=transform(e?.strategies??{},(n,p,b)=>{p.type!=="password"&&(n[b]=p.config);},{}),g=Object.keys(s).length>0;return jsxs("div",{className:"flex flex-col gap-4 w-full",children:[g&&jsxs(Fragment,{children:[jsx("div",{children:Object.entries(s)?.map(([n,p],b)=>jsx(bt,{provider:n,method:r,basepath:h,action:o},b))}),jsx(dr,{})]}),jsx(Form,{method:r,action:d.action,...i,schema:hr,validator:ir,validationMode:"change",className:it("flex flex-col gap-3 w-full",a),children:({errors:n,submitting:p})=>jsxs(Fragment,{children:[jsxs(Qt,{children:[jsx($t,{htmlFor:"email",children:"Email address"}),jsx(pt,{type:"email",name:"email"})]}),jsxs(Qt,{children:[jsx($t,{htmlFor:"password",children:"Password"}),jsx(Zt,{name:"password"})]}),jsx(at,{type:"submit",variant:"primary",size:"large",className:"w-full mt-2 justify-center",disabled:n.length>0||p,children:l})]})})]})}var dr=()=>jsxs("div",{className:"w-full flex flex-row items-center",children:[jsx("div",{className:"relative flex grow",children:jsx("div",{className:"h-px bg-primary/10 w-full absolute top-[50%] z-0"})}),jsx("div",{className:"mx-5",children:"or"}),jsx("div",{className:"relative flex grow",children:jsx("div",{className:"h-px bg-primary/10 w-full absolute top-[50%] z-0"})})]});function u0({method:t="POST",action:a="login",logo:r,intro:o,formOnly:e}){let{strategies:l,basepath:i,loading:h}=Rt(),d=jsx(Bt,{auth:{basepath:i,strategies:l},method:t,action:a});return e?h?null:d:jsx("div",{className:"flex flex-1 flex-col select-none h-dvh w-dvw justify-center items-center bknd-admin",children:!h&&jsxs("div",{className:"flex flex-col gap-4 items-center w-96 px-6 py-7",children:[r||null,isValidElement(o)?o:jsxs("div",{className:"flex flex-col items-center",children:[jsxs("h1",{className:"text-xl font-bold",children:["Sign ",a==="login"?"in":"up"," to your admin panel"]}),jsx("p",{className:"text-primary/50",children:"Enter your credentials below to get access."})]}),d]})})}var me={Screen:u0,Form:Bt,SocialLink:bt};function v0(){let t=useRef(0);return t.current++,t.current}function M0({children:t,defaultOpen:a=false,openEvent:r="onClick",position:o="bottom-start",dropdownWrapperProps:e,items:l,title:i,hideOnEmpty:h=true,onClickItem:d,renderItem:s,itemsClassName:g,className:n}){let[p,b]=useState(a),[m,k]=useState(o),B=useClickOutside(()=>b(false)),_=l.filter(Boolean),[G,N]=useState(0),v=I((x=50)=>setTimeout(()=>b(P=>!P),typeof x=="number"?x:0)),L=r==="onClick"?x=>{x.stopPropagation(),v();}:void 0,f=I(x=>{if(r!=="onContextMenu")return;if(x.preventDefault(),p){v(0),setTimeout(()=>{k(o),N(0);},10);return}let P=x.clientX-x.currentTarget.getBoundingClientRect().left,{left:q=0,right:Z=0}=B.current?.getBoundingClientRect()??{};if(q>0&&Z>0){let Mt=G1(P,q,Z);P<(q+Z)/2?(k("bottom-start"),N(Mt)):(k("bottom-end"),N(Z-Mt));}else k(o),N(0);v();}),w=4,z={"bottom-start":{top:"100%",left:G,marginTop:w},"bottom-end":{right:G,top:"100%",marginTop:w},"top-start":{bottom:"100%",marginBottom:w},"top-end":{bottom:"100%",right:G,marginBottom:w}}[m],K=I(x=>{x.onClick&&x.onClick(),d&&d(x),v(50);});if(_.length===0&&h)return null;let et=_.some(x=>"icon"in x&&x.icon),$=s||((x,{key:P,onClick:q})=>typeof x=="function"?jsx(Fragment$1,{children:x()},P):jsxs("button",{type:"button",disabled:x.disabled,className:j("flex flex-row flex-nowrap text-nowrap items-center outline-none cursor-pointer px-2.5 rounded-md link leading-none h-8",g,x.disabled?"opacity-50 cursor-not-allowed":"hover:bg-primary/10",x.destructive&&"text-red-500 hover:bg-red-600 hover:text-white"),onClick:q,title:x.title,children:[et&&jsx("div",{className:"size-[16px] text-left mr-1.5 opacity-80",children:x.icon&&jsx(x.icon,{className:"size-[16px]"})}),jsx("div",{className:"flex flex-grow truncate text-nowrap",children:x.label})]},P));return jsxs("div",{role:"dropdown",className:j("relative flex",n),ref:B,onContextMenu:f,children:[cloneElement(t,{onClick:L}),p&&jsxs("div",{...e,className:j("absolute z-30 flex flex-col bg-background border border-muted px-1 py-1 rounded-lg shadow-lg min-w-full",e?.className),style:z,children:[i&&jsx("div",{className:"text-sm font-bold px-2.5 mb-1 mt-1 opacity-50 truncate",children:i}),_.map((x,P)=>$(x,{key:P,onClick:q=>{q.stopPropagation(),K(x);}}))]})]})}var ur=[".DS_Store","Thumbs.db"];function st(t,a){let r=vr(t);if(typeof r.path!="string"){let{webkitRelativePath:o}=t;Object.defineProperty(r,"path",{value:typeof a=="string"?a:typeof o=="string"&&o.length>0?o:t.name,writable:false,configurable:false,enumerable:true});}return r}function vr(t){let{name:a}=t,r=a&&a.lastIndexOf(".")!==-1;if(console.log("withMimeType",a,r),r&&!t.type){let o=E1(a);console.log("guessed",o),o&&Object.defineProperty(t,"type",{value:o,writable:false,configurable:false,enumerable:true});}return t}async function ut(t){return wt(t)&&Mr(t.dataTransfer)?Lr(t.dataTransfer,t.type):kr(t)?fr(t):Array.isArray(t)&&t.every(a=>"getFile"in a&&typeof a.getFile=="function")?xr(t):[]}function Mr(t){return wt(t)}function kr(t){return wt(t)&&wt(t.target)}function wt(t){return typeof t=="object"&&t!==null}function fr(t){return e1(t.target.files).map(a=>st(a))}async function xr(t){return (await Promise.all(t.map(r=>r.getFile()))).map(r=>st(r))}async function Lr(t,a){if(t.items){let r=e1(t.items).filter(e=>e.kind==="file");if(a!=="drop")return r;let o=await Promise.all(r.map(Cr));return k0(x0(o))}return k0(e1(t.files).map(r=>st(r)))}function k0(t){return t.filter(a=>ur.indexOf(a.name)===-1)}function e1(t){if(t===null)return [];let a=[];for(let r=0;r<t.length;r++){let o=t[r];a.push(o);}return a}function Cr(t){if(typeof t.webkitGetAsEntry!="function")return f0(t);let a=t.webkitGetAsEntry();return a?.isDirectory?L0(a):f0(t)}function x0(t){return t.reduce((a,r)=>[...a,...Array.isArray(r)?x0(r):[r]],[])}function f0(t){let a=t.getAsFile();if(!a)return Promise.reject(`${t} is not a File`);let r=st(a);return Promise.resolve(r)}async function br(t){return t.isDirectory?L0(t):Br(t)}function L0(t){let a=t.createReader();return new Promise((r,o)=>{let e=[];function l(){a.readEntries(async i=>{if(i.length){let h=Promise.all(i.map(br));e.push(h),l();}else try{let h=await Promise.all(e);r(h);}catch(h){o(h);}},i=>{o(i);});}l();})}async function Br(t){return new Promise((a,r)=>{t.file(o=>{let e=st(o,t.fullPath);a(e);},o=>{r(o);});})}var l1={enter:["dragenter","dragover","dragstart"],leave:["dragleave","drop"]},b0=[...l1.enter,...l1.leave];function B0({onDropped:t,onOver:a,onLeave:r}){let[o,e]=useState(false),l=useRef(null),i=useRef(false),h=useCallback(n=>{n.preventDefault(),n.stopPropagation();},[]),d=useCallback(async n=>{let p=l1.enter.includes(n.type);a&&p!==o&&!i.current&&(a(await ut(n),n),i.current=true),e(p),p===false&&i.current&&(i.current=false,r?.());},[]),s=useCallback(async n=>{let p=await ut(n);t?.(p),i.current=false;},[t]),g=useCallback(async n=>{let p=await ut(n);t?.(p);},[t]);return useEffect(()=>{let n=l.current;return b0.forEach(p=>{n.addEventListener(p,h),n.addEventListener(p,d);}),n.addEventListener("drop",s),()=>{b0.forEach(p=>{n.removeEventListener(p,h),n.removeEventListener(p,d);}),n.removeEventListener("drop",s);}},[]),{ref:l,isOver:o,fromEvent:ut,onDropped:t,handleFileInputChange:g}}function Tr(t,a={overrides:{},baseUrl:""}){return {body:`${a.baseUrl}/api/media/file/${t.path}`,path:t.path,name:t.path,size:t.size??0,type:t.mime_type??"",state:"uploaded",progress:0,...a.overrides}}function w0(t,a={overrides:{},baseUrl:""}){return t.map(r=>Tr(r,a))}function i1({maxItems:t,current:a=0,overwrite:r,added:o}){if(!t)return {reject:false,to_drop:0};let e=t-a,l=o>e?o:o-e>0?o-e:0;return {reject:r?o>t:e-o<0,to_drop:l}}var m0=t=>{let a,r=new Set,o=(g,n)=>{let p=typeof g=="function"?g(a):g;if(!Object.is(p,a)){let b=a;a=n??(typeof p!="object"||p===null)?p:Object.assign({},a,p),r.forEach(m=>m(a,b));}},e=()=>a,d={setState:o,getState:e,getInitialState:()=>s,subscribe:g=>(r.add(g),()=>r.delete(g)),destroy:()=>{(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear();}},s=a=t(o,e,d);return d},T0=t=>t?m0(t):m0;var {useDebugValue:zr}=nt__default,{useSyncExternalStoreWithSelector:yr}=jr,Sr=t=>t;function E(t,a=Sr,r){(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&r;let o=yr(t.subscribe,t.getState,t.getServerState||t.getInitialState,a,r);return zr(o),o}var j0=(t,a)=>(...r)=>Object.assign({},t,a(...r));var z0=()=>T0(j0({files:[],isOver:false,isOverAccepted:false,uploading:false},(t,a)=>({setFiles:r=>t(({files:o})=>({files:r(o)})),getFilesLength:()=>a().files.length,setIsOver:(r,o)=>t({isOver:r,isOverAccepted:o}),setUploading:r=>t({uploading:r}),setIsOverAccepted:r=>t({isOverAccepted:r}),reset:()=>t({files:[],isOver:false,isOverAccepted:false}),addFile:r=>t(o=>({files:[...o.files,r]})),removeFile:r=>t(o=>({files:o.files.filter(e=>e.path!==r)})),removeAllFiles:()=>t({files:[]}),setFileProgress:(r,o)=>t(e=>({files:e.files.map(l=>l.path===r?{...l,progress:o}:l)})),setFileState:(r,o,e)=>t(l=>({files:l.files.map(i=>i.path===r?{...i,state:o,progress:e??i.progress}:i)}))})));function Pr(t){if(t&&t instanceof XMLHttpRequest){let a=JSON.parse(t.responseText);alert(`Upload failed with code ${t.status}: ${a.error}`);}else alert("Upload failed");}function D0({getUploadInfo:t,handleDelete:a,initialItems:r=[],flow:o="start",allowedMimeTypes:e,maxItems:l,overwrite:i,autoUpload:h,placeholder:d,onRejected:s,onDeleted:g,onUploaded:n,children:p,onClick:b,footer:m}){let k=useRef(z0()).current,B=E(k,c=>c.files),_=E(k,c=>c.setFiles),G=E(k,c=>c.getFilesLength),N=E(k,c=>c.setUploading),v=E(k,c=>c.setIsOver),L=E(k,c=>c.uploading),f=E(k,c=>c.setFileState),w=E(k,c=>c.removeFile),z=useRef(null);useEffect(()=>{_(()=>r);},[r.length]);function K(c){return (Array.isArray(c)?c:[c]).map(y=>({kind:"kind"in y?y.kind:"file",type:y.type,size:"size"in y?y.size:0})).every(y=>y.kind!=="file"?false:!(e&&!e.includes(y.type)))}let{handleFileInputChange:et,ref:$}=B0({onDropped:c=>{if(console.log("onDropped",c),!K(c))return;let R=c.length;_(D=>{let y=0;if(l){let S=i1({maxItems:l,overwrite:i,added:R,current:D.length});if(S.reject)return s?s(c):console.warn("maxItems reached"),D;y=S.to_drop;}let Y=D.slice(y),kt=Y.map(S=>S.path),lt=c.filter(S=>S.path&&!kt.includes(S.path)).map(S=>({body:S,path:S.path,name:S.name,size:S.size,type:S.type,state:"pending",progress:0})),W=o==="start"?[...lt,...Y]:[...Y,...lt];return h&<.length>0&&setTimeout(()=>N(true),0),W});},onOver:c=>{if(!K(c)){v(true,false);return}let R=G(),D=i1({maxItems:l,overwrite:i,added:c.length,current:R});console.log("--files in onOver",R,D),v(true,!D.reject);},onLeave:()=>{v(false,false);}});useEffect(()=>{console.log("files updated");},[B]),useEffect(()=>{L&&(async()=>{let c=B.filter(R=>R.state==="pending");if(c.length===0){N(false);return}else {let R=[];for(let D of c)try{R.push(await x(D));}catch(y){Pr(y);}N(false),n?.(R);}})();},[L]);function x(c){return new Promise((R,D)=>{if(c.body){if(c.state!=="pending"){console.error("File is not pending"),D();return}else if(!(c.body instanceof File)){console.error("File body is not a File instance"),D();return}}else {console.error("File has no body"),D();return}let y=t({path:c.body.path});console.log("dropzone:uploadInfo",y);let{url:Y,headers:kt,method:lt="POST"}=y,W=new XMLHttpRequest;console.log("xhr:url",Y);let S=new URLSearchParams;i&&S.append("overwrite","1"),W.open(lt,String(Y)+"?"+String(S),true),kt&&kt.forEach((F,J)=>{W.setRequestHeader(J,F);}),W.upload.addEventListener("progress",F=>{if(console.log("progress",F.loaded,F.total),F.lengthComputable){f(c.path,"uploading",F.loaded/F.total);let J=F.loaded/F.total*100;console.log(`Progress: ${J.toFixed(2)}%`);}else console.log("Unable to compute progress information since the total size is unknown");}),W.onload=()=>{if(console.log("onload",c.path,W.status),W.status>=200&&W.status<300){console.log("Upload complete");try{let F=JSON.parse(W.responseText);console.log("Response:",c,F);let J={...F.state,progress:1,state:"uploaded"};f(c.path,J.state),R({...F,...c,...J});}catch(F){f(c.path,"uploaded",1),console.error("Error parsing response",F),D(F);}}else f(c.path,"failed",1),console.error("Upload failed with status: ",W.status,W.statusText),D(W);},W.onerror=()=>{console.error("Error during the upload process.");},W.onloadstart=()=>{f(c.path,"uploading",0),console.log("loadstart");},W.setRequestHeader("Accept","application/json"),W.send(c.body);})}let P=useCallback(async c=>{switch(console.log("deleteFile",c),c.state){case "uploaded":case "initial":window.confirm("Are you sure you want to delete this file?")&&(console.log('setting state to "deleting"',c),f(c.path,"deleting"),await a(c),w(c.path),g?.(c));break}},[]),q=useCallback(async c=>{let R=await x(c);n?.([R]);},[]),Z=useCallback(()=>z.current?.click(),[z]),Mt=useMemo(()=>!!(d?.show===true||!l||l&&B.length<l),[d,l,B.length]),Pt=useMemo(()=>({store:k,wrapperRef:$,inputProps:{ref:z,type:"file",multiple:!l||l>1,onChange:et},showPlaceholder:Mt,actions:{uploadFile:q,deleteFile:P,openFileInput:Z},dropzoneProps:{maxItems:l,placeholder:d,autoUpload:h,flow:o},onClick:b,footer:m}),[l,o,d,h,m]);return jsx(P0.Provider,{value:Pt,children:p?typeof p=="function"?p(Pt):p:jsx(R0,{...Pt})})}var P0=createContext(void 0);function Tt(){return useContext(P0)}var Wt=()=>{let{store:t}=Tt(),a=E(t,e=>e.files),r=E(t,e=>e.isOver),o=E(t,e=>e.isOverAccepted);return {files:a,isOver:r,isOverAccepted:o}},Q=(t,a)=>{let{store:r}=Tt();return E(r,o=>{let e=typeof t=="string"?o.files.find(l=>l.path===t):o.files.find(l=>l.path===t.path);return e?a(e):void 0})};function Ar(t){if(t&&t instanceof XMLHttpRequest){let a=JSON.parse(t.responseText);alert(`Upload failed with code ${t.status}: ${a.error}`);}else alert("Upload failed");}var R0=({wrapperRef:t,inputProps:a,showPlaceholder:r,actions:{uploadFile:o,deleteFile:e,openFileInput:l},dropzoneProps:{placeholder:i,flow:h},onClick:d,footer:s})=>{let{files:g,isOver:n,isOverAccepted:p}=Wt(),b=r&&jsx(Or,{onClick:l,text:i?.text}),m=useCallback(async k=>{try{return await o(k)}catch(B){Ar(B);}},[o]);return jsxs("div",{ref:t,className:j("dropzone w-full h-full align-start flex flex-col select-none",n&&p&&"bg-green-200/10",n&&!p&&"bg-red-200/40 cursor-not-allowed"),children:[jsx("div",{className:"hidden",children:jsx("input",{...a})}),jsx("div",{className:"flex flex-1 flex-col",children:jsxs("div",{className:"flex flex-row flex-wrap gap-2 md:gap-3",children:[h==="start"&&b,g.map(k=>jsx(Ir,{file:k,handleUpload:m,handleDelete:e,onClick:d},k.path)),h==="end"&&b,s]})})]})},Or=({onClick:t,text:a="Upload files"})=>jsx("div",{className:"w-[49%] aspect-square md:w-60 flex flex-col border-2 border-dashed border-muted relative justify-center items-center text-primary/30 hover:border-primary/30 hover:text-primary/50 hover:cursor-pointer hover:bg-muted/20 transition-colors duration-200",onClick:t,children:jsx("span",{className:"",children:a})}),Er=({file:t,fallback:a,...r})=>t.type.startsWith("image/")?jsx(Hr,{...r,file:t}):t.type.startsWith("video/")?jsx(_r,{...r,file:t}):a?a({file:t}):null,c1=memo(Er,(t,a)=>t.file.path===a.file.path),Ir=memo(({file:t,handleUpload:a,handleDelete:r,onClick:o})=>{v0();let l=Q(t,h=>{let{progress:d,...s}=h;return s});if(!l)return null;let i=useCallback(()=>{o&&o(l);},[o,l.path]);return jsxs("div",{className:j("w-[49%] md:w-60 aspect-square flex flex-col border border-muted relative hover:bg-primary/5 cursor-pointer transition-colors",l.state==="failed"&&"border-red-500 bg-red-200/20",l.state==="deleting"&&"opacity-70"),onClick:i,children:[jsx("div",{className:"absolute top-2 right-2",children:jsx(Ur,{file:l,handleDelete:r,handleUpload:a})}),jsx(Nr,{file:l}),jsx("div",{className:"flex bg-primary/5 aspect-[1/0.78] overflow-hidden items-center justify-center",children:jsx(c1,{file:l,fallback:Gr,className:"max-w-full max-h-full"})}),jsxs("div",{className:"flex flex-col px-1.5 py-1",children:[jsxs("div",{className:"flex flex-row gap-2 items-center",children:[jsx("p",{className:"truncate select-text w-[calc(100%-10px)]",children:l.name}),jsx(qr,{file:l})]}),jsxs("div",{className:"flex flex-row justify-between text-sm font-mono opacity-50 text-nowrap gap-2",children:[jsx("span",{className:"truncate select-text",children:l.type}),jsx("span",{children:V1.fileSize(l.size)})]})]})]})},(t,a)=>t.file.path===a.file.path&&t.file.state===a.file.state),Nr=({file:t})=>{let a=Q(t.path,r=>({state:r.state,progress:r.progress}));return !a||a.state!=="uploading"?null:jsx("div",{className:"absolute w-full top-0 left-0 right-0 h-1",children:jsx("div",{className:"bg-blue-600 h-1 transition-all duration-75",style:{width:(a.progress*100).toFixed(0)+"%"}})})},Ur=memo(({file:t,handleDelete:a,handleUpload:r})=>{let o=Q(t.path,l=>{let{progress:i,...h}=l;return h});if(!o)return null;let e=useMemo(()=>[o.state==="uploaded"&&typeof o.body=="string"&&{label:"Open",icon:e0,onClick:()=>{window.open(o.body,"_blank");}},["initial","uploaded"].includes(o.state)&&{label:"Delete",destructive:true,icon:h0,onClick:()=>a(o)},["initial","pending"].includes(o.state)&&{label:"Upload",icon:d0,onClick:()=>r(o)}],[o,a,r]);return jsx(M0,{items:e,position:"bottom-end",children:jsx(ct,{Icon:o0})})},(t,a)=>t.file.path===a.file.path),qr=({file:t})=>{let a=Q(t.path,o=>o.state);if(!a||a==="uploaded")return null;let r={failed:"bg-red-500",deleting:"bg-orange-500 animate-pulse",uploading:"bg-blue-500 animate-pulse"}[a]??"bg-primary/50";return jsx("div",{className:"w-2 h-2 rounded-full mt-px "+r,title:a})},Hr=({file:t,...a})=>{let r=typeof t.body=="string"?t.body:URL.createObjectURL(t.body);return jsx("img",{...a,src:r})},_r=({file:t,...a})=>{let r=typeof t.body=="string"?t.body:URL.createObjectURL(t.body);return jsx("video",{...a,src:r})},Gr=({file:t})=>jsx("div",{className:"text-xs text-primary/50 text-center",children:t.type});var U=class{constructor(a={},r){this._options=a;this.fetcher=r??fetch;}fetcher;getDefaultOptions(){return {}}get options(){return {host:"http://localhost",token:void 0,...this.getDefaultOptions(),...this._options}}key(){return this.options.basepath??""}getUrl(a){let r=this.options.basepath??"";return this.options.host+(r+"/"+a).replace(/\/{2,}/g,"/").replace(/\/$/,"")}request(a,r,o){let e=o?.method??"GET",l=Array.isArray(a)?a.join("/"):a,i=this.getUrl(l);r instanceof URLSearchParams?i+="?"+r.toString():typeof r=="object"&&Object.keys(r).length>0&&(i+="?"+P1(r));let h=new Headers(this.options.headers??{});for(let[g,n]of Object.entries(o?.headers??{}))h.set(g,n);h.has("Accept")||h.set("Accept","application/json"),this.options.token&&this.options.token_transport==="header"&&h.set("Authorization",`Bearer ${this.options.token}`);let d=o?.body;if(o&&"body"in o&&["POST","PATCH","PUT"].includes(e)){let g=h.get("Content-Type")??void 0;(!g||g.startsWith("application/json"))&&(d=JSON.stringify(o.body),h.set("Content-Type","application/json"));}let s=new Request(i,{...o,method:e,body:d,headers:h});return new vt(s,{fetcher:this.fetcher,verbose:this.options.verbose})}get(a,r,o){return this.request(a,r,{...o,method:"GET"})}post(a,r,o){return this.request(a,void 0,{...o,body:r,method:"POST"})}patch(a,r,o){return this.request(a,void 0,{...o,body:r,method:"PATCH"})}put(a,r,o){return this.request(a,void 0,{...o,body:r,method:"PUT"})}delete(a,r,o){return this.request(a,void 0,{...o,body:r,method:"DELETE"})}};function Vr(t,a,r){let o=typeof r<"u"?r:a,e=["raw","body","ok","status","res","data","toJSON"];return typeof o!="object"&&(o={}),new Proxy(o,{get(l,i,h){return i==="raw"||i==="res"?t:i==="body"?a:i==="data"?r:i==="ok"?t.ok:i==="status"?t.status:i==="toJSON"?()=>l:Reflect.get(l,i,h)},has(l,i){return e.includes(i)?true:Reflect.has(l,i)},ownKeys(l){return Array.from(new Set([...Reflect.ownKeys(l),...e]))},getOwnPropertyDescriptor(l,i){return e.includes(i)?{configurable:true,enumerable:true,value:Reflect.get({raw:t,body:a,ok:t.ok,status:t.status},i)}:Reflect.getOwnPropertyDescriptor(l,i)}})}var vt=class t{constructor(a,r,o){this.request=a;this.options=r;this.refineData=o;}[Symbol.toStringTag];get verbose(){return this.options?.verbose??false}refine(a){return new t(this.request,this.options,a)}async execute(){ht()&&await new Promise(i=>setTimeout(i,200));let a=this.options?.fetcher??fetch;this.verbose&&Gt.debug("[FetchPromise] Request",{method:this.request.method,url:this.request.url});let r=await a(this.request);this.verbose&&Gt.debug("[FetchPromise] Response",{res:r,ok:r.ok,status:r.status});let o,e,l=r.headers.get("Content-Type")??"";if(l.startsWith("application/json")?(o=await r.json(),typeof o=="object"&&(e="data"in o?o.data:o)):l.startsWith("text")?o=await r.text():o=r.body,this.refineData)try{e=this.refineData(e);}catch(i){console.warn("[FetchPromise] Error in refineData",i),e=void 0;}return Vr(r,o,e)}then(a,r){return this.execute().then(a,r)}catch(a){return this.then(void 0,a)}finally(a){return this.then(r=>(a?.(),r),r=>{throw a?.(),r})}path(){return new URL(this.request.url).pathname}key(a){let r=new URL(this.request.url);return a?.search!==false?this.path()+r.search:this.path()}keyArray(a){let r=new URL(this.request.url),o=this.path().split("/");return (a?.search!==false?[...o,r.searchParams.toString()]:o).filter(Boolean)}toString(){return this.key({search:true})}toJSON(){return {url:this.request.url,method:this.request.method}}};var jt=class extends U{getDefaultOptions(){return {basepath:"/api/auth",credentials:"include"}}async login(a,r){let o=await this.post([a,"login"],r,{credentials:this.options.credentials});return o.ok&&o.body.token&&await this.options.onTokenUpdate?.(o.body.token),o}async register(a,r){let o=await this.post([a,"register"],r,{credentials:this.options.credentials});return o.ok&&o.body.token&&await this.options.onTokenUpdate?.(o.body.token),o}async actionSchema(a,r){return this.get([a,"actions",r,"schema.json"])}async action(a,r,o){return this.post([a,"actions",r],o)}async loginWithPassword(a){return this.login("password",a)}async registerWithPassword(a){return this.register("password",a)}me(){return this.get(["me"])}strategies(){return this.get(["strategies"])}async logout(){await this.options.onTokenUpdate?.(void 0);}};var zt=class extends U{getDefaultOptions(){return {basepath:"/api/data",queryLengthLimit:1e3,defaultQuery:{limit:10}}}requireObjectSet(a,r){if(!a||typeof a!="object"||Object.keys(a).length===0)throw new Error(r??"object is required")}readOne(a,r,o={}){return this.get(["entity",a,r],o)}readOneBy(a,r={}){return this.readMany(a,{...r,limit:1,offset:0}).refine(o=>o[0])}readMany(a,r={}){let o=r??this.options.defaultQuery,e=this.get(["entity",a],o);return e.request.url.length<=this.options.queryLengthLimit?e:this.post(["entity",a,"query"],o)}readManyByReference(a,r,o,e={}){return this.get(["entity",a,r,o],e??this.options.defaultQuery)}createOne(a,r){return this.post(["entity",a],r)}createMany(a,r){if(!r||!Array.isArray(r)||r.length===0)throw new Error("input is required");return this.post(["entity",a],r)}updateOne(a,r,o){if(!r)throw new Error("ID is required");return this.patch(["entity",a,r],o)}updateMany(a,r,o){return this.requireObjectSet(r),this.patch(["entity",a],{update:o,where:r})}deleteOne(a,r){if(!r)throw new Error("ID is required");return this.delete(["entity",a,r])}deleteMany(a,r){return this.requireObjectSet(r),this.delete(["entity",a],r)}count(a,r={}){return this.post(["entity",a,"fn","count"],r)}exists(a,r={}){return this.post(["entity",a,"fn","exists"],r)}};var yt=class extends U{getDefaultOptions(){return {basepath:"/api/media",upload_fetcher:fetch}}listFiles(){return this.get(["files"])}getFile(a){return this.get(["file",a],void 0,{headers:{Accept:"*/*"}})}async getFileStream(a){let{res:r}=await this.getFile(a);if(!r.ok||!r.body)throw new Error("Failed to fetch file");return r.body}async download(a){let{res:r}=await this.getFile(a);if(!r.ok||!r.body)throw new Error("Failed to fetch file");return await r.blob()}getFileUploadUrl(a){return a?this.getUrl(`/upload/${a.path}`):this.getUrl("/upload")}getEntityUploadUrl(a,r,o){return this.getUrl(`/entity/${a}/${r}/${o}`)}getUploadHeaders(){return this.options.token_transport==="header"&&this.options.token?new Headers({Authorization:`Bearer ${this.options.token}`}):new Headers}uploadFile(a,r){let o={"Content-Type":"application/octet-stream",...r?._init?.headers||{}},e=r?.filename||"";try{typeof a.type<"u"&&(o["Content-Type"]=a.type),r?.filename||(e=a.name);}catch{}e&&e.length>0&&e.includes("/")&&(e=e.split("/").pop()||"");let l={...r?._init||{},headers:o};if(r?.path)return this.post(r.path,a,l);if(!e||e.length===0)throw new Error("Invalid filename");return this.post(r?.path??["upload",e],a,l)}async upload(a,r={}){if(a instanceof Request||typeof a=="string"){let e=await(r.fetcher??this.options.upload_fetcher)(a);if(!e.ok||!e.body)throw new Error("Failed to fetch file");return this.uploadFile(e.body,r)}else if(a instanceof Response){if(!a.body)throw new Error("Invalid response");return this.uploadFile(a.body,{...r??{},_init:{...r._init??{},headers:{...r._init?.headers??{},"Content-Type":a.headers.get("Content-Type")||"application/octet-stream"}}})}return this.uploadFile(a,r)}async uploadToEntity(a,r,o,e,l){return this.upload(e,{...l,path:["entity",a,r,o]})}deleteFile(a){return this.delete(["file",a])}};var St=class extends U{getDefaultOptions(){return {basepath:"/api/system"}}readConfig(){return this.get("config")}readSchema(a){return this.get("schema",{config:a?.config?1:0,secrets:a?.secrets?1:0,fresh:a?.fresh?1:0})}setConfig(a,r,o){return this.post(["config","set",a].join("/")+`?force=${o?1:0}`,r)}addConfig(a,r,o){return this.post(["config","add",a,r],o)}patchConfig(a,r,o){return this.patch(["config","patch",a,r],o)}overwriteConfig(a,r,o){return this.put(["config","overwrite",a,r],o)}removeConfig(a,r){return this.delete(["config","remove",a,r])}};var Ft=class{constructor(a={}){this.options=a;this.verified=a.verified===true,"request"in a&&a.request?(this.options.host=a.host??new URL(a.request.url).origin,this.options.headers=a.headers??a.request.headers,this.extractToken()):"token"in a&&a.token?(this.token_transport="header",this.updateToken(a.token,{trigger:false})):"user"in a&&a.user?(this.token_transport="none",this.user=a.user,this.verified=a.verified!==false):this.extractToken(),this.buildApis();}token;user;verified=false;token_transport="header";system;data;auth;media;get fetcher(){return this.options.fetcher??fetch}get baseUrl(){return this.options.host??"http://localhost"}get tokenKey(){return this.options.key??"auth"}extractToken(){if(this.verified=false,this.options.headers){let a=Kr(this.options.headers.get("cookie"),"auth");if(a){this.token_transport="cookie",this.updateToken(a);return}let r=this.opti