bknd
Version:
Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.
7 lines (4 loc) • 30.6 kB
JavaScript
import W from"dayjs";import he from"dayjs/plugin/weekOfYear.js";W.extend(he);function q(e){return W(e).format("YYYY-MM-DD HH:mm:ss")}function mr(e){return(e?new Date(e):new Date).toISOString().replace("T"," ").split(".")[0]}function dr(){return new Date().getTimezoneOffset()}function pr(){return Intl.DateTimeFormat().resolvedOptions().timeZone}import m from"picocolors";var J=(e,r)=>typeof e=="string"?[1,"1","true"].includes(e):!!(e||r);var Te={cli_log_level:{key:"BKND_CLI_LOG_LEVEL",validate:e=>{if(typeof e=="string"&&["log","info","warn","error","debug"].includes(e.toLowerCase()))return e.toLowerCase()}},cli_create_ref:{key:"BKND_CLI_CREATE_REF",validate:e=>typeof e=="string"?e:void 0},cli_telemetry:{key:"BKND_CLI_TELEMETRY",validate:e=>{if(!(typeof e>"u"))return J(e,!0)}},modules_debug:{key:"BKND_MODULES_DEBUG",validate:J}},Q=(e,r,t)=>{try{let n=t?.source??process.env,o=Te[e],s=n[o.key],a=o.validate(s);if(typeof a<"u")return t?.onValid?.(a),a;t?.onFallback?.(s)}catch{t?.onFallback?.(void 0)}return r};function we(){try{let e=process||{},r=e.argv||[],t=e.env||{};return!(t.NO_COLOR||r.includes("--no-color"))&&(!!t.FORCE_COLOR||r.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&t.TERM!=="dumb"||!!t.CI)}catch{return!1}}var E={critical:{prefix:"CRT",color:m.red,args_color:m.red,original:console.error},error:{prefix:"ERR",color:m.red,args_color:m.red,original:console.error},warn:{prefix:"WRN",color:m.yellow,args_color:m.yellow,original:console.warn},info:{prefix:"INF",color:m.cyan,original:console.info},log:{prefix:"LOG",color:m.dim,args_color:m.dim,original:console.log},debug:{prefix:"DBG",color:m.yellow,args_color:m.dim,original:console.debug}};function Ee(e,r){let t=we(),n=E[e],o=n.color(`[${n.prefix}]`),s=r.map(a=>"args_color"in n&&t&&typeof a=="string"?n.args_color(a):a);return n.original(o,m.gray(q()),...s)}var X=Q("cli_log_level","log"),p=globalThis.__consoleConfig??={level:X,enabled:!0},Z=Object.keys(E),g=new Proxy(p,{get:(e,r)=>{switch(r){case"original":return console;case"disable":return()=>{p.enabled=!1};case"enable":return()=>{p.enabled=!0};case"setLevel":return o=>{p.level=o};case"resetLevel":return()=>{p.level=X}}if(!p.enabled)return()=>null;let t=Z.indexOf(p.level),n=Z.indexOf(r);return r in E&&n<=t?(...o)=>Ee(r,o):()=>null}});function wr(e){for(let[r]of Object.entries(E))e[r]=g[r]}function Or(){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"}function br(e){return Object.keys(e).map(r=>({key:r,value:e[r]}))}function C(e){return!e||e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}function Oe(e,r=" "){return!e||e.length===0?e:e.split(r).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(r)}function H(e,r=!1){let o="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+(r?"!@#$%^&*()_+{}:\"<>?|[];',./`~":""),s="";for(let a=0;a<e;a++)s+=o[Math.floor(Math.random()*o.length)];return s}function v(e){return!e||e.length===0?e:e.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(" ")}function O(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Ae(e){return/^[a-z]+(_[a-z]+)*$/.test(e)?"snake_case":/^[A-Z][a-zA-Z]*$/.test(e)?"PascalCase":/^[a-z][a-zA-Z]*$/.test(e)?"camelCase":/^[a-z]+(-[a-z]+)*$/.test(e)?"kebab-case":/^[A-Z]+(_[A-Z]+)*$/.test(e)?"SCREAMING_SNAKE_CASE":"unknown"}function be(e){switch(Ae(e)){case"snake_case":return v(e);case"PascalCase":return N(O(e));case"camelCase":return C(N(O(e)));case"kebab-case":return N(e);case"SCREAMING_SNAKE_CASE":return v(e.toLowerCase());case"unknown":return C(e)}}function _r(e){return be(e)}function N(e){return e.split("-").map(C).join(" ")}function Rr(e,r=" "){return Oe(v(e),r)}function kr(e,r){return e.replace(/\{\$(\w+)\}/g,(t,n)=>n in r?r[n]:t)}function Nr(e,r){return r instanceof RegExp?r.test(e):typeof r=="string"&&r.startsWith("/")?new RegExp(r).test(e):typeof r=="string"?e.startsWith(r):!1}function Cr(e){return String(e).normalize("NFKD").replace(/[\u0300-\u036f]/g,"").trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function vr(e,r=50,t="..."){return e.length<=r?e:e.substring(0,r)+t}function Ur(e,r=2){return JSON.stringify(e,null,r)}function U(e){return Object.prototype.toString.call(e)==="[object Object]"}function h(e){return e!==null&&typeof e=="object"}function Lr(e,r){let t=new Set(r),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function Pr(e,r){let t=new Set(r),n={};for(let[o,s]of Object.entries(e))t.has(o)&&(n[o]=s);return n}function Fr(e){return Object.entries(e).reduce((r,[t,n])=>{try{r[t]=JSON.parse(n)}catch{r[t]=n}return r},{})}function Mr(e,r){return Object.keys(r).reduce((t,n)=>(r[n]!==e[n]&&(t[n]=r[n]),t),{})}function ee(e,r=[]){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(t=>ee(t,r)):Object.keys(e).reduce((t,n)=>{let o=r.includes(n)?n:O(n);return t[o]=ee(e[n],r),t},{})}function _e(e,r){let t={};for(let n in e)r.some(s=>n.includes(s))||(typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(e[n])?t[n]=_e(e[n],r):t[n]=e[n]);return t}function Re(e,r){let t={};for(let[n,o]of Object.entries(e)){let s=r(o,n);typeof s<"u"&&(t[n]=s)}return t}var jr=Re;function $r(e,r){Object.entries(e).forEach(([t,n])=>{r(n,t)},{})}function re(e,...r){if(!r.length)return e;let t=r.shift();if(h(e)&&h(t))for(let n in t)h(t[n])?(e[n]||Object.assign(e,{[n]:{}}),re(e[n],t[n])):Object.assign(e,{[n]:t[n]});return re(e,...r)}function ke(e,r=""){let t=[];for(let n in e){let o=r?`${r}.${n}`:n;t.push(o),typeof e[n]=="object"&&e[n]!==null&&(t=t.concat(ke(e[n],o)))}return t}function ne(e,r="",t={}){for(let n in e)if(n in e){let o=r?`${r}.${n}`:n;typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(e[n])?ne(e[n],o,t):Array.isArray(e[n])?e[n].forEach((s,a)=>{let c=`${o}.${a}`;typeof s=="object"&&s!==null?ne(s,c,t):t[c]=s}):t[o]=e[n]}return t}function Ne(e){let r=1;for(let t in e)if(typeof e[t]=="object"){let n=Ne(e[t])+1;r=Math.max(n,r)}return r}function Br(e,r){function t(n,o){if(U(n)){if(o>r)return;let s={};for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s[a]=t(n[a],o+1));return s}return Array.isArray(n)?n.map(s=>t(s,o)):n}return t(e,1)}function te(e){return e&&Object.entries(e).reduce((r,[t,n])=>{if(n&&Array.isArray(n)&&n.some(o=>typeof o=="object")){let o=n.map(te);o.length>0&&(r[t]=o)}else if(n&&typeof n=="object"&&!Array.isArray(n)){let o=te(n);Object.keys(o).length>0&&(r[t]=o)}else n!==""&&n!==null&&n!==void 0&&(r[t]=n);return r},{})}function Ce(e,...r){for(let t of r)for(let[n,o]of Object.entries(t))o!==void 0&&(!U(o)&&!Array.isArray(o)||Array.isArray(o)&&!Array.isArray(e[n])?e[n]=o:h(e[n])?Ce(e[n],o):e[n]=o);return e}function ve(e,r,t){for(let[n,o]of Object.entries(r)){let s=t(e[n],o,n,e,r);if(s!==void 0){e[n]=s;continue}o!==void 0&&(!U(o)&&!Array.isArray(o)||Array.isArray(o)&&!Array.isArray(e[n])?e[n]=o:h(e[n])?ve(e[n],o,t):e[n]=o)}return e}function I(e,r){let t=o=>{if(o!==Object(o))return"primitive";if(Array.isArray(o))return"array";if(o instanceof Map)return"map";if(o!=null&&[null,Object.prototype].includes(Object.getPrototypeOf(o)))return"plainObject";if(o instanceof Function)return"function";throw new Error(`deeply comparing an instance of type ${e.constructor?.name} is not supported.`)},n=t(e);if(n!==t(r))return!1;if(n==="primitive")return e===r||Number.isNaN(e)&&Number.isNaN(r);if(n==="array")return e.length===r.length&&e.every((o,s)=>I(o,r[s]));if(n==="map")return e.size===r.size&&[...e].every(([o,s])=>r.has(o)&&I(s,r.get(o)));if(n==="plainObject"){let o=new Map(Object.entries(e)),s=new Map(Object.entries(r));return o.size===s.size&&[...o].every(([a,c])=>s.has(a)&&I(c,s.get(a)))}else{if(n==="function")return e.toString()===r.toString();throw new Error("Unreachable")}}function D(e,r,t=void 0){let n=typeof r=="string"?r.split(/[.\[\]\"]+/).filter(o=>o):r;if(n.length===0)return e;try{let[o,...s]=n;return!o||!(o in e)?t:D(e[o],s,t)}catch{if(typeof t<"u")return t;throw new Error(`Invalid path: ${n.join(".")}`)}}function Ie(e,r,t){let n=r;if(typeof n=="string"){let a=c=>c[0]==='"'&&c.at(-1)==='"';n=n.split(/[.\[\]]+/).filter(c=>c).map(c=>Number.isNaN(Number(c))?c:Number(c)).map(c=>typeof c=="string"&&a(c)?c.slice(1,-1):c)}if(n.length===0)throw new Error("The path must have at least one entry in it");let[o,...s]=n;return s.length===0?(e[o]=t,e):(o in e||(e[o]=typeof s[0]=="number"?[]:{}),Ie(e[o],s,t),e)}function oe(e,r=0,t=0){let n=r?`
`:"",o=u=>r?" ".repeat(r*u):"",s=o(t+1),a=o(t);if(e===null)return"null";if(e===void 0)return"undefined";let c=typeof e;if(c==="string")return JSON.stringify(e);if(c==="number"||c==="boolean")return String(e);if(Array.isArray(e)){let u=e.map(d=>oe(d,r,t+1)).join(", "+(r?n+s:""));return"["+(r&&e.length?n+s:"")+u+(r&&e.length?n+a:"")+"]"}if(c==="object"){let u=Object.entries(e).map(([x,xe])=>(/^[A-Za-z_$][\w$]*$/.test(x)?x:JSON.stringify(x))+": "+oe(xe,r,t+1)),d=u.join(", "+(r?n+s:""));return"{"+(r&&u.length?n+s:"")+d+(r&&u.length?n+a:"")+"}"}throw new TypeError(`Unsupported data type: ${c}`)}function Sr(e,r){return r.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}function De(e){if(Object.isFrozen(e))return e;let r=Reflect.ownKeys(e);for(let t of r){let n=e[t];(n&&typeof n=="object"||typeof n=="function")&&De(n)}return Object.freeze(e)}function Kr(e){return Object.keys(e).every(r=>Number.isInteger(Number(r)))?Object.values(e):e}function ie(e,r,t,n){if(typeof e=="string"){let o=e.match(r);if(o&&o[0]===e&&o[1]){let s=o[1],a=D(t,s,null);return a!==null?a:n!==void 0?n:e}if(r.test(e))return e.replace(r,(s,a)=>{let c=D(t,a,null);return c!==null?String(c):n!==void 0?String(n):s})}return Array.isArray(e)?e.map(o=>ie(o,r,t,n)):e&&typeof e=="object"?Object.entries(e).reduce((o,[s,a])=>(o[s]=ie(a,r,t,n),o),{}):e}var se=class e{marks=[];startTime;endTime=null;constructor(){this.startTime=performance.now()}static start(){return new e}mark(r){if(this.endTime!==null)throw new Error("Cannot add marks after perf measurement has been closed.");let t=performance.now(),n=this.marks.length>0?this.marks[this.marks.length-1].time:this.startTime,o=t-n;this.marks.push({mark:r,time:o})}close(){if(this.endTime!==null)throw new Error("Perf measurement has already been closed.");this.endTime=performance.now()}result(){if(this.endTime===null)throw new Error("Perf measurement has not been closed yet.");let r=this.endTime-this.startTime;return{total:Number.parseFloat(r.toFixed(2)),marks:this.marks.map(t=>({mark:t.mark,time:Number.parseFloat(t.time.toFixed(2))}))}}static async execute(r,t=1){let n=e.start();for(let o=0;o<t;o++)await r(),n.mark(`iteration-${o}`);return n.close(),n.result()}};var L={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","toml","json","json5","pdf","xml"],font:["woff","woff2","ttf","otf"]},f={vnd:"vnd.openxmlformats-officedocument",z:"application/x-7z-compressed",t:(e="plain")=>`text/${e}`,a:(e="octet-stream")=>`application/${e}`,i:e=>`image/${e}`,v:e=>`video/${e}`,au:e=>`audio/${e}`},P=new Map([["7z",f.z],["7zip",f.z],["txt",f.t()],["ai",f.a("postscript")],["apk",f.a("vnd.android.package-archive")],["doc",f.a("msword")],["docx",`${f.vnd}.wordprocessingml.document`],["eps",f.a("postscript")],["epub",f.a("epub+zip")],["ini",f.t()],["ico",f.i("vnd.microsoft.icon")],["jar",f.a("java-archive")],["jsonld",f.a("ld+json")],["jpg",f.i("jpeg")],["js",f.t("javascript")],["log",f.t()],["m3u",f.au("x-mpegurl")],["m3u8",f.a("vnd.apple.mpegurl")],["manifest",f.t("cache-manifest")],["md",f.t("markdown")],["mkv",f.v("x-matroska")],["mp3",f.au("mpeg")],["mobi",f.a("x-mobipocket-ebook")],["ppt",f.a("powerpoint")],["pptx",`${f.vnd}.presentationml.presentation`],["qt",f.v("quicktime")],["svg",f.i("svg+xml")],["tif",f.i("tiff")],["tsv",f.t("tab-separated-values")],["tgz",f.a("x-tar")],["text",f.t()],["vcd",f.a("x-cdlink")],["vcs",f.t("x-vcalendar")],["wav",f.au("vnd.wav")],["webmanifest",f.a("manifest+json")],["xls",f.a("vnd.ms-excel")],["xlsx",`${f.vnd}.spreadsheetml.sheet`],["yml",f.t("yaml")]]);function ae(e){try{let r=e.split(".").pop();if(!r)return f.a();for(let[t,n]of Object.entries(L))if(n.includes(r))return`${t}/${r}`;return P.get(r)}catch{return f.a()}}function ce(e,r=[]){let t=e.toLowerCase();if(r.includes(t))return!1;if(Object.entries(L).flatMap(([n,o])=>o.map(s=>`${n}/${s}`)).includes(t))return!0;for(let[n,o]of P.entries())if(o===t&&!r.includes(n))return!0;return!1}function fe(e){let r=e.toLowerCase();for(let[t,n]of Object.entries(L))for(let o of n)if(r===`${t}/${o}`)return o;for(let[t,n]of P.entries())if(n===r)return t;return""}import{getRuntimeKey as Ue}from"hono/adapter";function Le(){let e=globalThis;return e?.process?.env?.NEXT_RUNTIME==="nodejs"?"nextjs":e?.process?.env?.NEXT_RUNTIME==="edge"?"nextjs-edge":typeof window<"u"&&window.__NEXT_DATA__?"nextjs-client":Ue()}var le={redirects_non_fq:!0};function Wr(e){return Le().startsWith("nextjs")&&(le.redirects_non_fq=!1),le[e]}function qr(){try{return global?.process?.release?.name==="node"}catch{return!1}}function Jr(){try{return typeof Bun<"u"}catch{return!1}}function F(e,r){if(!e)throw new Error(r)}function Qr(e,r){try{return e(),!1}catch(t){if(r){if(t instanceof r)return!0;throw t}return!0}}async function Zr(e,r){try{return await e,!1}catch(t){if(r){if(t instanceof r)return!0;throw t}return!0}}async function Xr(e,r,t=100,n=10){let o=0;for(;o<n;){if(await r())return;await new Promise(s=>setTimeout(s,t)),o++}throw new Error(`$waitUntil: "${e}" failed after ${n} attempts`)}function Pe(e){let r="";typeof e=="string"?r=e:e instanceof Headers?r=e.get("Content-Disposition")||"":e instanceof Request&&(r=e.headers.get("Content-Disposition")||"");let t=r.match(/filename\*?=(?:UTF-8'')?("?)([^";]+)\1/);return t?t[2]:void 0}function Fe(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function A(e){return typeof e=="object"&&e!==null&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"}function T(e){return A(e)&&typeof e.name=="string"&&typeof e.lastModified=="number"}function Me(e){return typeof e=="object"&&e!==null&&Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function je(e){return typeof e=="object"&&e!==null&&ArrayBuffer.isView(e)}var $e={"89504E47":"image/png",FFD8FF:"image/jpeg",47494638:"image/gif","49492A00":"image/tiff","4D4D002A":"image/tiff","52494646????57454250":"image/webp","504B0304":"application/zip",25504446:"application/pdf","00000020667479706D70":"video/mp4","000001BA":"video/mpeg","000001B3":"video/mpeg","1A45DFA3":"video/webm","4F676753":"audio/ogg",494433:"audio/mpeg",FFF1:"audio/aac",FFF9:"audio/aac","52494646????41564920":"audio/wav","52494646????57415645":"audio/wave","52494646????415550":"audio/aiff"};async function Be(e){if(!e)return;let r;if(Fe(e)){let n=e.getReader(),{value:o}=await n.read();if(!o)return;r=new Uint8Array(o)}else if(A(e)||T(e))r=new Uint8Array(await e.slice(0,12).arrayBuffer());else if(Me(e))r=new Uint8Array(e);else if(je(e))r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(typeof e=="string")r=new TextEncoder().encode(e);else return;let t=Array.from(r.slice(0,12)).map(n=>n.toString(16).padStart(2,"0").toUpperCase()).join("");for(let[n,o]of Object.entries($e))if(new RegExp("^"+n.replace(/\?\?/g,"..")).test(t))return o}async function Se(e){let r=e.req.header("Content-Type")??"application/octet-stream";if(r?.startsWith("multipart/form-data")||r?.startsWith("application/x-www-form-urlencoded"))try{let t=await e.req.formData();if([...t.values()].length>0){let n=[...t.values()][0];return await ue(n)}}catch(t){g.warn("Error parsing form data",t)}else try{let t=await e.req.blob();if(T(t))return t;if(A(t))return await ue(t,{name:Pe(e.req.raw),type:r})}catch(t){g.warn("Error parsing blob",t)}throw new Error("No file found in request")}async function on(e){let r=e.req.header("Content-Type")??"application/octet-stream";if(!r?.startsWith("multipart/form-data")&&!r?.startsWith("application/x-www-form-urlencoded")){let t=e.req.raw.body;if(t)return t}return Se(e)}async function sn(e,r){let t=T(e),n=t?e.type:r;F(n&&typeof n=="string"&&n.startsWith("image/"),"type must be image/*");let o=t?await e.arrayBuffer():e;F(o.byteLength>=128,"Buffer must be at least 128 bytes");let s=new DataView(o);if(n==="image/jpeg"){let a=2;for(;a<s.byteLength;){let c=s.getUint16(a);if(a+=2,c===65472||c===65474)return{width:s.getUint16(a+5),height:s.getUint16(a+3)};a+=s.getUint16(a)}}else{if(n==="image/png")return{width:s.getUint32(16),height:s.getUint32(20)};if(n==="image/gif")return{width:s.getUint16(6),height:s.getUint16(8)};if(n==="image/tiff"){let a=s.getUint16(0)===18761,c=s.getUint32(4,a),u=s.getUint32(c+18,a),d=s.getUint32(c+10,a);return{width:u,height:d}}}throw new Error("Unsupported image format")}async function ue(e,r={}){if(T(e))return e;if(!A(e))throw new Error("Not a Blob");let t=ce(r.type,["application/octet-stream"])?r.type:await Be(e),n=t?fe(t):"",o=r.name||[H(16),n].filter(Boolean).join(".");return new File([e],o,{type:t||ae(o),lastModified:Date.now()})}function an(e,r){let t=Array.isArray(r)?r.join(","):r;if(!t||!t.trim())return!0;if(!T(e))throw new Error("Given file is not a File instance");let n=e.name.toLowerCase(),o=(e.type||"").trim().toLowerCase();return t.split(",").map(a=>a.trim().toLowerCase()).filter(Boolean).some(a=>{if(a.startsWith("."))return n.endsWith(a);if(a.indexOf("/")!==-1){let[u,d]=a.split("/");if(d==="*"){if(!o)return!1;let[x]=o.split("/");return x===u}else return o.startsWith(a)}return!1})}function Ke(e){return e?{...Object.fromEntries(e.entries())}:{}}function fn(e,r){let t=Ke(e),n={};for(let o of r)t[o]&&(n[o]=t[o]);return n}function ln(e,r){let t=new Headers;for(let n of r)e.has(n)&&t.set(n,e.get(n));return t}var un=(e,r)=>{let t=e;for(let[n,o]of Object.entries(r)){let s=new RegExp(`/:${n}(?:{[^/]+})?`);t=t.replace(s,`/${o}`)}return t};function mn(e,r){let t="";function n(o){return r?.encode?encodeURIComponent(o):o}for(let o in e){let s=e[o];if(s!==void 0)if(Array.isArray(s))for(let a=0;a<s.length;a++)t.length>0&&(t+="&"),t+=`${n(o)}=${n(s[a])}`;else typeof s=="object"&&(s=JSON.stringify(s)),t.length>0&&(t+="&"),t+=`${n(o)}=${n(s)}`}return(r?.prefix||"")+t}function dn(e){function r(a){if(!a)return"";let c=decodeURIComponent(a);if(c==="false")return!1;if(c==="true")return!0;try{return JSON.parse(c)}catch{return+c*0===0?+c:c}}let t,n,o={},s=e.split("&");for(;t=s.shift();)t=t.split("="),n=t.shift(),o[n]!==void 0?o[n]=[].concat(o[n],r(t.shift())):o[n]=r(t.shift());return o}var ze=(i=>(i[i.CONTINUE=100]="CONTINUE",i[i.PROCESSING=102]="PROCESSING",i[i.EARLY_HINTS=103]="EARLY_HINTS",i[i.OK=200]="OK",i[i.CREATED=201]="CREATED",i[i.ACCEPTED=202]="ACCEPTED",i[i.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",i[i.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",i[i.MULTI_STATUS=207]="MULTI_STATUS",i[i.ALREADY_REPORTED=208]="ALREADY_REPORTED",i[i.IM_USED=226]="IM_USED",i[i.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",i[i.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",i[i.FOUND=302]="FOUND",i[i.SEE_OTHER=303]="SEE_OTHER",i[i.USE_PROXY=305]="USE_PROXY",i[i.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",i[i.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",i[i.BAD_REQUEST=400]="BAD_REQUEST",i[i.UNAUTHORIZED=401]="UNAUTHORIZED",i[i.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",i[i.FORBIDDEN=403]="FORBIDDEN",i[i.NOT_FOUND=404]="NOT_FOUND",i[i.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",i[i.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",i[i.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",i[i.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",i[i.CONFLICT=409]="CONFLICT",i[i.GONE=410]="GONE",i[i.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",i[i.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",i[i.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",i[i.URI_TOO_LONG=414]="URI_TOO_LONG",i[i.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",i[i.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",i[i.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",i[i.IM_A_TEAPOT=418]="IM_A_TEAPOT",i[i.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",i[i.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",i[i.LOCKED=423]="LOCKED",i[i.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",i[i.TOO_EARLY=425]="TOO_EARLY",i[i.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",i[i.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",i[i.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",i[i.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",i[i.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",i[i.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",i[i.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",i[i.BAD_GATEWAY=502]="BAD_GATEWAY",i[i.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",i[i.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",i[i.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",i[i.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",i[i.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",i[i.LOOP_DETECTED=508]="LOOP_DETECTED",i[i.NOT_EXTENDED=510]="NOT_EXTENDED",i[i.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",i))(ze||{}),Ve=(o=>(o[o.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",o[o.NO_CONTENT=204]="NO_CONTENT",o[o.RESET_CONTENT=205]="RESET_CONTENT",o[o.NOT_MODIFIED=304]="NOT_MODIFIED",o))(Ve||{});import{XMLParser as Ge}from"fast-xml-parser";function yn(e){return new Ge().parse(e)}var Ye=["SHA-1","SHA-256","SHA-384","SHA-512"];async function M(e,r,t,n){if(!Ye.includes(e))throw new Error(`Invalid hash algorithm: ${e}`);let o=new TextEncoder().encode((t??"")+r+(n??"")),s=await crypto.subtle.digest(e,o);return Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join("")}var hn={sha256:async(e,r,t)=>M("SHA-256",e,r,t),sha1:async(e,r,t)=>M("SHA-1",e,r,t)};async function Tn(e){let r=typeof e=="string"?e:JSON.stringify(e);return await M("SHA-1",r)}function wn(e){let r=new Uint8Array(e);return crypto.getRandomValues(r),Array.from(r,t=>String.fromCharCode(33+t%94)).join("")}var me=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function We(e){return typeof e=="string"&&me.test(e)}var w=We;var l=[];for(let e=0;e<256;++e)l.push((e+256).toString(16).slice(1));function b(e,r=0){return(l[e[r+0]]+l[e[r+1]]+l[e[r+2]]+l[e[r+3]]+"-"+l[e[r+4]]+l[e[r+5]]+"-"+l[e[r+6]]+l[e[r+7]]+"-"+l[e[r+8]]+l[e[r+9]]+"-"+l[e[r+10]]+l[e[r+11]]+l[e[r+12]]+l[e[r+13]]+l[e[r+14]]+l[e[r+15]]).toLowerCase()}var j,qe=new Uint8Array(16);function y(){if(!j){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");j=crypto.getRandomValues.bind(crypto)}return j(qe)}var Je=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),$={randomUUID:Je};function Qe(e,r,t){e=e||{};let n=e.random??e.rng?.()??y();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,r){if(t=t||0,t<0||t+16>r.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let o=0;o<16;++o)r[t+o]=n[o];return r}return b(n)}function Ze(e,r,t){return $.randomUUID&&!r&&!e?$.randomUUID():Qe(e,r,t)}var B=Ze;var S={};function Xe(e,r,t){let n;if(e)n=de(e.random??e.rng?.()??y(),e.msecs,e.seq,r,t);else{let o=Date.now(),s=y();He(S,o,s),n=de(s,S.msecs,S.seq,r,t)}return r??b(n)}function He(e,r,t){return e.msecs??=-1/0,e.seq??=0,r>e.msecs?(e.seq=t[6]<<23|t[7]<<16|t[8]<<8|t[9],e.msecs=r):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function de(e,r,t,n,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),o=0;else if(o<0||o+16>n.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return r??=Date.now(),t??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],n[o++]=r/1099511627776&255,n[o++]=r/4294967296&255,n[o++]=r/16777216&255,n[o++]=r/65536&255,n[o++]=r/256&255,n[o++]=r&255,n[o++]=112|t>>>28&15,n[o++]=t>>>20&255,n[o++]=128|t>>>14&63,n[o++]=t>>>6&255,n[o++]=t<<2&255|e[10]&3,n[o++]=e[11],n[o++]=e[12],n[o++]=e[13],n[o++]=e[14],n[o++]=e[15],n}var K=Xe;function er(e){if(!w(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}var z=er;function zn(){return B()}function Vn(){return K()}function Gn(e,r){return w(e)&&z(e)===r}var rr={log:console.log,warn:console.warn,error:console.error},pe,ge;async function qn(e,r=["log","warn","error"]){let t={log:console.log,warn:console.warn,error:console.error};nr(r);let n=()=>{Object.entries(t).forEach(([o,s])=>{console[o]=s})};try{let o=await e();return n(),o}catch(o){throw n(),o}}function nr(e=["log","warn"]){e.forEach(r=>{console[r]=()=>null}),pe=process.stderr.write,ge=process.stdout.write,process.stderr.write=()=>!0,process.stdout.write=()=>!0,g?.setLevel("critical")}function Jn(){process.stderr.write=pe,process.stdout.write=ge,Object.entries(rr).forEach(([e,r])=>{console[e]=r}),g?.resetLevel()}function Qn(){let e=process.memoryUsage();return{rss:e.rss/1024/1024,heapUsed:e.heapUsed/1024/1024,external:e.external/1024/1024,arrayBuffers:e.arrayBuffers/1024/1024}}function Xn(e,r,t){let n=Math.min(r,t),o=Math.max(r,t);return Math.max(n,Math.min(e,o))}function Hn(e){return e==null?0:typeof e=="number"?e:Number.parseInt(e,10)}var et={fileSize:(e,r=2)=>{if(e===0)return"0 B";let t=1024,n=r<0?0:r,o=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(e)/Math.log(t));return Number.parseFloat((e/t**s).toFixed(n))+" "+o[s]}};var _=class extends Error{code=400;name="Exception";_context=void 0;constructor(r,t){super(r),t&&(this.code=t)}context(r){return this._context=r,this}toJSON(){return{error:this.message,type:this.name,context:this._context}}};import{HttpStatus as ir}from"bknd/utils";import*as k from"jsonv-ts";import{validator as mt}from"jsonv-ts/hono";import{describeRoute as pt,schemaToSpec as gt,openAPISpecs as yt,info as xt}from"jsonv-ts/hono";import{mcp as Tt,McpServer as wt,Resource as Et,Tool as Ot,mcpTool as At,mcpResource as bt,getMcpServer as _t,stdioTransport as Rt,McpClient as kt,logLevels as Nt}from"jsonv-ts/mcp";import{StringSchema as tr}from"jsonv-ts";var R=class extends tr{},or=e=>new R(e);var V=Symbol("bknd-validation-mark");function at(e){let r=structuredClone(e);return ye(r,!1),r}function ye(e,r=!0){try{if(typeof e=="object"&&e!==null&&!Array.isArray(e)){r?e[V]=!0:delete e[V];for(let t in e)typeof e[t]=="object"&&e[t]!==null&&ye(e[t],r)}}catch{}}function sr(e){return typeof e!="object"||e===null?!1:e[V]===!0}var ct=k.string({pattern:"^[a-zA-Z_][a-zA-Z0-9_]*$",minLength:2,maxLength:150}),G=class extends _{constructor(t,n,o=[]){super(`Invalid schema given for ${JSON.stringify(n,null,2)}
Error: ${JSON.stringify(o[0],null,2)}
Schema: ${JSON.stringify(t.toJSON(),null,2)}`);this.schema=t;this.value=n;this.errors=o}name="InvalidSchemaError";code=ir.UNPROCESSABLE_ENTITY;first(){return this.errors[0]}firstToString(){let t=this.first();return`${t.error} at ${t.instanceLocation}`}},ar=e=>{let r=e.toJSON();return k.fromSchema(r)};function ft(e,r,t){if(!t?.forceParse&&!t?.coerce&&sr(r))return r;let n=t?.clone?ar(e):e,o=t?.coerce!==!1?n.coerce(r,{dropUnknown:t?.coerceDropUnknown??!1}):r;t?.withDefaults!==!1&&(o=n.template(o,{withOptional:!0,withExtendedOptional:t?.withExtendedDefaults??!1}));let s=e.validate(o,{shortCircuit:!0,ignoreUnsupported:!0});if(!s.valid)if(t?.onError)t.onError(s.errors);else throw new G(n,r,s.errors);return o}var Y=class{_context=[];_enabled=!0;id=Math.random().toString(36).substr(2,9);last=0;constructor(r=!0){this._enabled=r}context(r){return this._context.push(r),this}clear(){return this._context.pop(),this}reset(){return this.last=0,this}log(...r){if(!this._enabled)return this;let t=performance.now(),n=this.last===0?0:Number.parseInt(String(t-this.last)),o=" ".repeat(Math.max(this._context.length-1,0)),s=this._context.length>0?`[${this._context[this._context.length-1]}]`:"";return console.log(o,s,n,...r),this.last=t,this}};export{g as $console,Xr as $waitUntil,Y as DebugLogger,Ye as HashAlgorithms,ze as HttpStatus,Ve as HttpStatusEmpty,G as InvalidSchemaError,kt as McpClient,wt as McpServer,se as Perf,Et as Resource,R as SecretSchema,Ot as Tool,Ur as _jsonp,_r as autoFormatString,ue as blobToFile,Tn as checksum,Xn as clampNumber,ar as cloneSchema,wr as colorizeConsole,Kr as convertNumberedObjectToArray,q as datetimeStringLocal,mr as datetimeStringUTC,W as dayjs,dn as decodeSearch,De as deepFreeze,pt as describeRoute,Ae as detectCase,sn as detectImageDimensions,M as digest,nr as disableConsoleLog,Jn as enableConsoleLog,mn as encodeSearch,Hn as ensureInt,_e as filterKeys,ne as flattenObject,Qn as formatMemoryUsage,et as formatNumber,on as getBodyFromContext,Or as getBrowser,Pe as getContentName,Se as getFileFromContext,ke as getFullPathKeys,_t as getMcpServer,D as getPath,Le as getRuntimeKey,pr as getTimezone,dr as getTimezoneOffset,hn as hash,Ke as headersToObject,be as identifierToHumanReadable,xt as info,F as invariant,Me as isArrayBuffer,je as isArrayBufferView,A as isBlob,Jr as isBun,I as isEqual,T as isFile,an as isFileAccepted,sr as isMarked,qr as isNode,h as isObject,U as isPlainObject,Fe as isReadableStream,mt as jsc,N as kebabToPascalWithSpaces,Mr as keepChanged,Br as limitObjectDepth,ye as mark,Tt as mcp,Nt as mcpLogLevels,bt as mcpResource,At as mcpTool,re as mergeDeep,Ce as mergeObject,ve as mergeObjectWith,te as objectCleanEmpty,Ne as objectDepth,$r as objectEach,ee as objectKeysPascalToKebab,oe as objectToJsLiteral,br as objectToKeyValueArray,jr as objectTransform,Lr as omitKeys,yt as openAPISpecs,ft as parse,O as pascalToKebab,Nr as patternMatch,Sr as pick,fn as pickHeaders,ln as pickHeaders2,Pr as pickKeys,H as randomString,ie as recursivelyReplacePlaceholders,kr as replaceSimplePlaceholders,un as replaceUrlParam,Wr as runtimeSupports,k as s,Fr as safelyParseObjectValues,gt as schemaToSpec,or as secret,wn as secureRandomString,Ie as setPath,Cr as slugify,v as snakeToPascalWithSpaces,Rt as stdioTransport,ct as stringIdentifier,at as stripMark,Qr as threw,Zr as threwAsync,Re as transformObject,vr as truncate,C as ucFirst,Oe as ucFirstAll,Rr as ucFirstAllSnakeToPascalWithSpaces,zn as uuid,Gn as uuidValidate,Vn as uuidv7,qn as withDisabledConsole,yn as xmlToObject};